commit 709f9b707a3cd1b52370f22fac01fe95dc04d866 Author: astar76 Date: Sat Oct 24 11:47:43 2026 -0500 Dezio: an all-in-one Discord bot in Rust Music with a live player, Last.fm, video downloads, games, AI chat, moderation, logging, a web dashboard and a Game Boy Activity. Co-Authored-By: Claude Sonnet 5.5 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..4d38d6c --- /dev/null +++ b/.env.example @@ -0,0 +1,6 @@ +DISCORD_BOT_TOKEN= +LASTFM_API_KEY= +OPENROUTER_KEY= +STEAMGRIDDB_API_KEY= +DASHBOARD_URL= +DASHBOARD_CLIENT_SECRET= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..805a49f --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/target +.env +data/ + +# Game Boy ROMs are never committed (copyrighted); the library folders are filled on the host +/assets/roms/*/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..a730e95 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,6644 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +dependencies = [ + "serde", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bit-set" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "btoi" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b5ab9db53bcda568284df0fd39f6eac24ad6f7ba7ff1168b9e76eba6576b976" +dependencies = [ + "num-traits", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20 0.9.1", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout", + "zeroize", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-models" +version = "0.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "657f625ff361906f779745d08375ae3cc9fef87a35fba5f22874cf773010daf4" +dependencies = [ + "hax-lib", + "pastey", + "rand 0.9.5", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "cosmic-text" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be17b688510d934ce13f48a2beba700e11583e281e0fda99c22bb256a14eda73" +dependencies = [ + "bitflags 2.13.2", + "fontdb", + "harfrust", + "linebender_resource_handle", + "log", + "rangemap", + "rustc-hash", + "self_cell", + "skrifa 0.40.0", + "smol_str", + "swash", + "sys-locale", + "unicode-bidi", + "unicode-linebreak", + "unicode-script", + "unicode-segmentation", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crossterm" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" +dependencies = [ + "bitflags 2.13.2", + "crossterm_winapi", + "derive_more 2.1.1", + "document-features", + "mio", + "parking_lot 0.12.5", + "rustix", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "csscolorparser" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb2a7d3066da2de787b7f032c736763eb7ae5d355f81a68bab2675a96008b0bf" +dependencies = [ + "lab", + "phf 0.11.3", +] + +[[package]] +name = "cssparser" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11119743ad110e8c1bdccd930d7f5c30c99e5fc76a7b63ec9807e84eef0c5f59" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf 0.14.0", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" +dependencies = [ + "quote", + "syn 3.0.9", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d706e75d87e35569db781a9b5e2416cff1236a47ed380831f959382ccd5f858" +dependencies = [ + "darling_core 0.10.2", + "darling_macro 0.10.2", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core 0.24.1", + "darling_macro 0.24.1", +] + +[[package]] +name = "darling_core" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0c960ae2da4de88a91b2d920c2a7233b400bc33cb28453a2987822d8392519b" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim 0.9.3", + "syn 1.0.109", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim 0.11.1", + "syn 3.0.9", +] + +[[package]] +name = "darling_macro" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b5a2f4ac4969822c62224815d069952656cadc7084fdca9751e6d959189b72" +dependencies = [ + "darling_core 0.10.2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core 0.24.1", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dashmap" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core 0.9.12", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "davey" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27466c95d1885cc506b29cec686a91ba7c472376cca09850d026cceb9c29a888" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "hex-literal", + "hmac", + "num-derive", + "num-traits", + "openmls", + "openmls_basic_credential", + "openmls_rust_crypto", + "p256", + "rand 0.8.8", + "scrypt", + "sha2 0.10.9", + "subtle", + "thiserror 2.0.21", + "tracing", +] + +[[package]] +name = "deltae" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5729f5117e208430e437df2f4843f5e5952997175992d1414f94c57d61e270b4" + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_builder" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2658621297f2cf68762a6f7dc0bb7e1ff2cfd6583daef8ee0fed6f7ec468ec0" +dependencies = [ + "darling 0.10.2", + "derive_builder_core", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_builder_core" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2791ea3e372c8495c0bc2033991d76b512cd799d07491fbd6890124db9458bef" +dependencies = [ + "darling 0.10.2", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_more" +version = "0.99.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f" +dependencies = [ + "convert_case 0.4.0", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case 0.10.0", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "dezio" +version = "0.1.0" +dependencies = [ + "ab_glyph", + "anyhow", + "async-trait", + "axum", + "base64 0.23.1", + "chrono", + "cosmic-text", + "dotenvy", + "futures", + "html-escape", + "image", + "mime_guess", + "num-bigint 0.5.1", + "num-traits", + "rand 0.10.3", + "ratatui", + "regex", + "reqwest 0.13.5", + "rustls 0.23.46", + "scraper", + "serde", + "serde_json", + "sha1 0.11.0", + "sha2 0.11.1", + "shakmaty", + "songbird", + "symphonia", + "tokio", + "tower", + "tower-http", + "tracing", + "tracing-subscriber", + "twilight-cache-inmemory", + "twilight-gateway", + "twilight-http", + "twilight-model", + "twilight-util", + "url", + "urlencoding", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.2", + "crypto-common 0.2.2", +] + +[[package]] +name = "discortp" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c793408a15d361754613fa68123ffa60424c2617fafdf82127b4bedf37d3f5d" +dependencies = [ + "pnet_macros", + "pnet_macros_support", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "rand_core 0.6.4", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + +[[package]] +name = "ego-tree" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bd50d24b1b75aa817bb0339cb9f2e0e664bdfab1e160a69a0fda9145b77fab2" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "enum-map" +version = "2.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6866f3bfdf8207509a033af1a75a7b08abda06bbaaeae6669323fd5a097df2e9" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f282cfdfe92516eb26c2af8589c274c7c17681f5ecc03c18255fe741c6aa64eb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "fancy-regex" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b95f7c0680e4142284cf8b22c14a476e87d61b004a3a0861872b32ef7ead40a2" +dependencies = [ + "bit-set", + "regex", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "finl_unicode" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bb028c8b4148c9ee0cca68fcd9add6044e81d3619f48577ddf13a263d047a2" + +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "nanorand", + "spin", +] + +[[package]] +name = "fluvio-wasm-timer" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b768c170dc045fa587a8f948c91f9bcfb87f774930477c6215addf54317f137f" +dependencies = [ + "futures", + "js-sys", + "parking_lot 0.11.2", + "pin-utils", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "fontdb" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" +dependencies = [ + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "from_map" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99f31122ab0445ff8cee420b805f24e07683073815de1dd276ee7d588d301700" +dependencies = [ + "hashmap_derive", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generator" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc16584ff22b460a382b7feec54b23d2908d858152e5739a120b949293bd74e" +dependencies = [ + "cc", + "libc", + "log", + "rustversion", + "windows", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getopts" +version = "0.2.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "harfrust" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da2e5ae821f6e96664977bf974d6d6a2d6682f9ccee23e62ec1d134246845f9" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "core_maths", + "read-fonts 0.37.0", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashmap_derive" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb30bf173e72cc31b5265dac095423ca14e7789ff7c3b0e6096a37a996f12883" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "hax-lib" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "543f93241d32b3f00569201bfce9d7a93c92c6421b23c77864ac929dc947b9fc" +dependencies = [ + "hax-lib-macros", + "num-bigint 0.4.8", + "num-traits", +] + +[[package]] +name = "hax-lib-macros" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8755751e760b11021765bb04cb4a6c4e24742688d9f3aa14c2079638f537b0f" +dependencies = [ + "hax-lib-macros-types", + "proc-macro-error2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "hax-lib-macros-types" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f177c9ae8ea456e2f71ff3c1ea47bf4464f772a05133fcbba56cd5ba169035a2" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_json", + "uuid", +] + +[[package]] +name = "heck" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hex-literal" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebdb29d2ea9ed0083cd8cece49bbd968021bd99b0849edb4a9a7ee0fdf6a4e0" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hls_m3u8" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b906521a5b0e6d2ec07ea0bb855d92a1db30b48812744a645a3b2a1405cb8159" +dependencies = [ + "derive_builder", + "derive_more 0.99.20", + "hex", + "shorthand", + "stable-vec", + "strum 0.17.1", + "thiserror 1.0.69", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "hpke-rs" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6ad6a58eb3e0ee30be8bfc7a9770ae98adcfa1d9bc820a5847732ce84f70837" +dependencies = [ + "hpke-rs-crypto", + "hpke-rs-libcrux", + "hpke-rs-rust-crypto", + "libcrux-sha3", + "log", + "rand_core 0.9.5", + "serde", + "subtle", + "tls_codec", + "zeroize", +] + +[[package]] +name = "hpke-rs-crypto" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a73a99d9008010d73289f41335a3f6e14fb8c04eaf60e9111b450463b1bbc7f" +dependencies = [ + "rand_core 0.9.5", + "zeroize", +] + +[[package]] +name = "hpke-rs-libcrux" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0ce6b7e54aebe540faee869c67ee253bede44ea6cb67c6e72c7847d6c59f1df" +dependencies = [ + "hpke-rs-crypto", + "libcrux-aead", + "libcrux-ecdh", + "libcrux-hkdf", + "libcrux-kem", + "libcrux-traits", + "rand 0.10.3", + "rand_chacha 0.10.0", + "rand_core 0.10.1", + "zeroize", +] + +[[package]] +name = "hpke-rs-rust-crypto" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14b28be6cba9081c7feda2651d51c2a900029798e78b4c1e093e792f4571a870" +dependencies = [ + "aes-gcm", + "chacha20poly1305", + "hkdf", + "hpke-rs-crypto", + "k256", + "p256", + "p384", + "rand 0.8.8", + "rand_chacha 0.3.1", + "rand_core 0.10.1", + "rand_core 0.6.4", + "sha2 0.10.9", + "subtle", + "x25519-dalek", + "zeroize", +] + +[[package]] +name = "html-escape" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "491194d601b4fa9fac3c9571e014070a0ad1bc3392d1bc10419695196a8b3cc3" + +[[package]] +name = "html5ever" +version = "0.40.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456a1a377e608e555d22ddab27ac0114bc7a7b4199078108e34c2aeae6c9b130" +dependencies = [ + "log", + "markup5ever", + "memchr", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "http-range-header" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c" + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls 0.23.46", + "rustls-platform-verifier", + "tokio", + "tokio-rustls 0.26.6", + "tower-service", + "webpki-roots 1.0.11", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2 0.6.5", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "instability" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" +dependencies = [ + "darling 0.24.1", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "k256" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" +dependencies = [ + "cfg-if", + "elliptic-curve", +] + +[[package]] +name = "kasuari" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f14c90e40a6133f4805b83542a7ed7364f56070b447f56e7f4e90297122209" +dependencies = [ + "hashbrown 0.17.1", + "portable-atomic", + "thiserror 2.0.21", +] + +[[package]] +name = "lab" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf36173d4167ed999940f804952e6b08197cae5ad5d572eb4db150ce8ad5d58f" + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libcrux-aead" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13297ce29869a5c0edab0378837b0fc5f88bf99a843712d9201c3b1150b3b476" +dependencies = [ + "libcrux-aesgcm", + "libcrux-chacha20poly1305", + "libcrux-secrets", + "libcrux-traits", +] + +[[package]] +name = "libcrux-aesgcm" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99f2a019dab4097585a7d4f5b9deebe46cd1e628b16a5bc4cb0ce35e1da334e6" +dependencies = [ + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-secrets", + "libcrux-traits", +] + +[[package]] +name = "libcrux-chacha20poly1305" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc08d044676af21343b32b988411fa98dbb5cf65a03c9df478ced221bbdfdb1b" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-poly1305", + "libcrux-secrets", + "libcrux-traits", +] + +[[package]] +name = "libcrux-curve25519" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb1e5fd8476a6ed609d24ef42aee5ab6f99f7c65d054f92412da9f499e423299" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-secrets", + "libcrux-traits", +] + +[[package]] +name = "libcrux-ecdh" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b65f73ce79337c762eb38bbac91e4c9b9e60cf318e8501b812750c640814d45e" +dependencies = [ + "libcrux-curve25519", + "libcrux-p256", + "rand 0.9.5", +] + +[[package]] +name = "libcrux-hacl-rs" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2637dc87d158e1f1b550fd9b226443e84153fded4de69028d897b534d16d22e6" +dependencies = [ + "libcrux-macros", +] + +[[package]] +name = "libcrux-hkdf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c1a89ca0c89be3a268a921e47105fb7873badf7267f5e3ebf4ea46baedd73ef" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-hmac", + "libcrux-secrets", +] + +[[package]] +name = "libcrux-hmac" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7a242707d65960770bd7e14e4f18a92bdf0b967777dd404887db8d087a643b" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-sha2", +] + +[[package]] +name = "libcrux-intrinsics" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1b5db005ff8001e026b73a6842ee81bbef8ec5ff0e1915a67ae65fd2a9fafa5" +dependencies = [ + "core-models", + "hax-lib", +] + +[[package]] +name = "libcrux-kem" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12631592f491d22fd1a176d32b2c6edfb673998fd3987e9d95f8fa79ad2a737b" +dependencies = [ + "libcrux-curve25519", + "libcrux-ecdh", + "libcrux-ml-kem", + "libcrux-p256", + "libcrux-sha3", + "libcrux-traits", + "rand 0.9.5", +] + +[[package]] +name = "libcrux-macros" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffd6aa2dcd5be681662001b81d493f1569c6d49a32361f470b0c955465cd0338" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "libcrux-ml-kem" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a14ab3e477de9df6ee1273a114018ff62c4996ca9220070c4e5cb1743f94a67d" +dependencies = [ + "hax-lib", + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-secrets", + "libcrux-sha3", + "libcrux-traits", + "rand 0.9.5", + "tls_codec", +] + +[[package]] +name = "libcrux-p256" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4778ba25cb08bb8a96bd100e19ed9aecf78337198fd176036e21042b2dd99bc" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-secrets", + "libcrux-sha2", + "libcrux-traits", +] + +[[package]] +name = "libcrux-platform" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d9e21d7ed31a92ac539bd69a8c970b183ee883872d2d19ce27036e24cb8ecc4" +dependencies = [ + "libc", +] + +[[package]] +name = "libcrux-poly1305" +version = "0.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02491808ee5b9db8cb65fad64ae0be812db64beef179d945c00c7787dc7dfcf9" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", +] + +[[package]] +name = "libcrux-secrets" +version = "0.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ce650f3041b44ba40d4263852347d007cd2cd9d1cc856a6f6c8b2e10c3fd40b" +dependencies = [ + "hax-lib", +] + +[[package]] +name = "libcrux-sha2" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9d253473f259fc74a280c43f29c464f7e374abdf28b4942234dc707f529d4b7" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-traits", +] + +[[package]] +name = "libcrux-sha3" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1ae0b7d0e1cc4793a609fd0ff2ca3b3a3fabae523770c619a3d4bc86417b0d7" +dependencies = [ + "hax-lib", + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-traits", +] + +[[package]] +name = "libcrux-traits" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812e4fa89f3f5e34b47f928b22b1b78395a0d4ec23b1f583db635f128159d65f" +dependencies = [ + "libcrux-secrets", + "rand 0.9.5", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libopus_sys" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b81c32f233fb2507347a93f97b9919493be9db7ec2249ce2c3ed0c89ad8edf60" +dependencies = [ + "cmake", + "log", + "pkg-config", +] + +[[package]] +name = "line-clipping" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "loom" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff50ecb28bb86013e935fb6683ab1f6d3a20016f123c76fd4c27470076ac30f5" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "serde", + "serde_json", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown 0.17.1", +] + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "mac_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3d0581a75c45969c63afd2bb87b1d8b25cfcc556c7a918cf9bb13b0fe8d2381" +dependencies = [ + "nix 0.31.3", + "windows-sys 0.61.2", +] + +[[package]] +name = "markup5ever" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab3dc68ac4a0f5719e560136778c1ee716e296030d75dbd4484e37e39e3a842" +dependencies = [ + "log", + "tendril", + "web_atoms", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memmem" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a64a92489e2744ce060c349162be1c5f33c6969234104dbd99ddb5feb08b8c15" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "nanorand" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + +[[package]] +name = "no-std-net" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43794a0ace135be66a25d3ae77d41b91615fb68ae937f904090203e81f755b65" + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nonmax" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "num_threads" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" +dependencies = [ + "libc", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "openmls" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380199a3bd922198b71a834e8acec831798f1eacf8fa472eb012c35d28ffb3e2" +dependencies = [ + "fluvio-wasm-timer", + "getrandom 0.3.4", + "log", + "openmls_traits", + "rayon", + "serde", + "serde_bytes", + "thiserror 2.0.21", + "tls_codec", + "zeroize", +] + +[[package]] +name = "openmls_basic_credential" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "983e8be1457dd6f316f409292cec334af3b57b49a19deadc925c83c3c35e15b6" +dependencies = [ + "ed25519-dalek", + "openmls_traits", + "p256", + "rand 0.8.8", + "serde", + "tls_codec", +] + +[[package]] +name = "openmls_memory_storage" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a52c927ddb9940acb96d51aebd54b8b9c601c7119e6609622fb3f2cbe16abe3" +dependencies = [ + "log", + "openmls_traits", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "openmls_rust_crypto" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fafcc8a3552b10fbb3ab757cccaf1a34081e826ca819f49aa7e6645b1d95c00f" +dependencies = [ + "aes-gcm", + "chacha20poly1305", + "ed25519-dalek", + "hkdf", + "hmac", + "hpke-rs", + "hpke-rs-crypto", + "hpke-rs-rust-crypto", + "openmls_memory_storage", + "openmls_traits", + "p256", + "rand 0.8.8", + "rand_chacha 0.3.1", + "serde", + "sha2 0.10.9", + "thiserror 2.0.21", + "tls_codec", +] + +[[package]] +name = "openmls_traits" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f88ccdd53448dfdbfa5b8da8ba4e527c418fdb966418172bace2e3b41eedd56" +dependencies = [ + "serde", + "tls_codec", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "opus2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49521e33fbf825d2abc8d696506c278cb8469d0c6cc05d3785bef5c5f7ee957b" +dependencies = [ + "libopus_sys", +] + +[[package]] +name = "ordered-float" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-float" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951" +dependencies = [ + "num-traits", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "elliptic-curve", + "primeorder", +] + +[[package]] +name = "palette" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64" +dependencies = [ + "approx", + "libm", + "palette_derive", + "palette_math", +] + +[[package]] +name = "palette_derive" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be" +dependencies = [ + "by_address", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "palette_math" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12" +dependencies = [ + "libm", +] + +[[package]] +name = "parking_lot" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" +dependencies = [ + "instant", + "lock_api", + "parking_lot_core 0.8.6", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core 0.9.12", +] + +[[package]] +name = "parking_lot_core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc" +dependencies = [ + "cfg-if", + "instant", + "libc", + "redox_syscall 0.2.16", + "smallvec", + "winapi", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "patricia_tree" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31f2f4539bffe53fc4b4da301df49d114b845b077bd5727b7fe2bd9d8df2ae68" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest 0.10.7", + "hmac", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pest" +version = "2.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd47a460a9cbc3b3429c7e22bf0d76653e779319bae45a499ca010c9a990bb23" +dependencies = [ + "memchr", + "psm", + "stacker", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "203e46697708f7519ab1608393cf89239cafb46b8e6d08a8ffe359359b11ef44" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e84ae6340a458d3d6cfc73cf328cf3cfe90b2484cd0de25eb66aa954615ed4d5" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "pest_meta" +version = "2.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b57f92f32b3dbce6598fd8f5cdf1f06a6072570b8103fa21728fa9036923e710" +dependencies = [ + "pest", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros 0.11.3", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros 0.14.0", + "phf_shared 0.14.0", + "serde", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf_codegen" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand 0.8.8", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared 0.14.0", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pin-utils" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13bee6c73da26345c729282832b60b0363cf3dd9f4bfd81d8551b7a1c889a113" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "pnet_base" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe4cf6fb3ab38b68d01ab2aea03ed3d1132b4868fa4e06285f29f16da01c5f4c" +dependencies = [ + "no-std-net", +] + +[[package]] +name = "pnet_macros" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "688b17499eee04a0408aca0aa5cba5fc86401d7216de8a63fdf7a4c227871804" +dependencies = [ + "proc-macro2", + "quote", + "regex", + "syn 2.0.119", +] + +[[package]] +name = "pnet_macros_support" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eea925b72f4bd37f8eab0f221bbe4c78b63498350c983ffa9dd4bcde7e030f56" +dependencies = [ + "pnet_base", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "primal-check" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08" +dependencies = [ + "num-integer", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "psm" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200b9ff220857e53e184257720a14553b2f4aa02577d2ed9842d45d4b9654810" +dependencies = [ + "cc", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls 0.23.46", + "socket2 0.6.5", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash", + "rustls 0.23.46", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2 0.6.5", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20 0.10.2", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e6af7f3e25ded52c41df4e0b1af2d047e45896c2f3281792ed68a1c243daedb" +dependencies = [ + "ppv-lite86", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "rangemap" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" + +[[package]] +name = "ratatui" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d" +dependencies = [ + "instability", + "ratatui-core", + "ratatui-crossterm", + "ratatui-macros", + "ratatui-termina", + "ratatui-termwiz", + "ratatui-widgets", + "serde", +] + +[[package]] +name = "ratatui-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c" +dependencies = [ + "bitflags 2.13.2", + "compact_str", + "critical-section", + "hashbrown 0.17.1", + "itertools", + "kasuari", + "lru", + "palette", + "serde", + "strum 0.28.0", + "thiserror 2.0.21", + "unicode-segmentation", + "unicode-truncate", + "unicode-width", +] + +[[package]] +name = "ratatui-crossterm" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0" +dependencies = [ + "cfg-if", + "crossterm", + "instability", + "ratatui-core", +] + +[[package]] +name = "ratatui-macros" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed7dc68daa7498a43e4d68e0eb078427e10c38fbcfbb1e42d955f1fa2140d814" +dependencies = [ + "ratatui-core", + "ratatui-widgets", +] + +[[package]] +name = "ratatui-termina" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0bf912d9e66f057a759d92e386a280ea886b352ab757d6ac4d653c7ed2c43c2" +dependencies = [ + "instability", + "ratatui-core", + "termina", +] + +[[package]] +name = "ratatui-termwiz" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf03e0380b7744054d6cb74224fe3adf062a029754933f575ca1e3b4c2ce977" +dependencies = [ + "ratatui-core", + "termwiz", +] + +[[package]] +name = "ratatui-widgets" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1" +dependencies = [ + "bitflags 2.13.2", + "hashbrown 0.17.1", + "indoc", + "instability", + "itertools", + "line-clipping", + "ratatui-core", + "serde", + "strum 0.28.0", + "time", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "read-fonts" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b634fabf032fab15307ffd272149b622260f55974d9fad689292a5d33df02e5" +dependencies = [ + "bytemuck", + "core_maths", + "font-types 0.11.3", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types 0.12.7", + "once_cell", +] + +[[package]] +name = "realfft" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f821338fddb99d089116342c46e9f1fbf3828dba077674613e734e01d6ea8677" +dependencies = [ + "rustfft", +] + +[[package]] +name = "redox_syscall" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls 0.23.46", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls 0.26.6", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots 1.0.11", +] + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls 0.23.46", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls 0.26.6", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "ringbuf" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe47b720588c8702e34b5979cb3271a8b1842c7cb6f57408efa70c779363488c" +dependencies = [ + "crossbeam-utils", + "portable-atomic", + "portable-atomic-util", +] + +[[package]] +name = "rubato" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5258099699851cfd0082aeb645feb9c084d9a5e1f1b8d5372086b989fc5e56a1" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "realfft", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustfft" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "primal-check", + "strength_reduce", + "transpose", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" +dependencies = [ + "log", + "ring", + "rustls-pki-types", + "rustls-webpki 0.102.8", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki 0.103.16", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls 0.23.46", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki 0.103.16", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.102.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "rusty_pool" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ed36cdb20de66d89a17ea04b8883fc7a386f2cf877aaedca5005583ce4876ff" +dependencies = [ + "crossbeam-channel", + "futures", + "futures-channel", + "futures-executor", + "num_cpus", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "scraper" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6844b5f49a5579f12ba4f89d9f7eec6d71889e4aa0bc7181821040ce66f08fff" +dependencies = [ + "cssparser", + "ego-tree", + "getopts", + "html5ever", + "precomputed-hash", + "selectors", +] + +[[package]] +name = "scrypt" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" +dependencies = [ + "pbkdf2", + "salsa20", + "sha2 0.10.9", +] + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "secrecy" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bd1c54ea06cfd2f6b63219704de0b9b4f72dcc2b8fdef820be6cd799780e91e" +dependencies = [ + "serde", + "zeroize", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "selectors" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8322aebea94a6cc288ff884e8a49bdbceef60206c400c6c46d22e62fc4fd91a6" +dependencies = [ + "bitflags 2.13.2", + "cssparser", + "derive_more 2.1.1", + "log", + "new_debug_unreachable", + "precomputed-hash", + "rustc-hash", + "servo_arc", + "smallvec", +] + +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-aux" +version = "4.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "207f67b28fe90fb596503a9bf0bf1ea5e831e21307658e177c5dfcdfc3ab8a0a" +dependencies = [ + "chrono", + "serde", + "serde-value", + "serde_json", +] + +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float 2.10.1", + "serde", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_cow" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7bbbec7196bfde255ab54b65e34087c0849629280028238e67ee25d6a4b7da" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serenity" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bde37f42765dfdc34e2a039e0c84afbf79a3101c1941763b0beb816c2f17541" +dependencies = [ + "arrayvec", + "async-trait", + "base64 0.22.1", + "bitflags 2.13.2", + "bytes", + "flate2", + "futures", + "mime_guess", + "percent-encoding", + "reqwest 0.12.28", + "secrecy", + "serde", + "serde_cow", + "serde_json", + "time", + "tokio", + "tokio-tungstenite 0.21.0", + "tracing", + "typemap_rev", + "url", +] + +[[package]] +name = "serenity-voice-model" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "910c6511e59df6fa362921e4900cdbd3192210231a2ba135594c480871422af6" +dependencies = [ + "bitflags 2.13.2", + "num-traits", + "serde", + "serde_json", + "serde_repr", +] + +[[package]] +name = "servo_arc" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4eceb519ec34d8290aaf6e46f435102f2bfa63f22b05a144fb16ab266d3b198" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "shakmaty" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d465a6a07031a8c60d92dc9b656cc8f59f8c1640493576d5d88f898883b4bd67" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "btoi", + "nohash-hasher", + "serde", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "shorthand" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "474f77f985d8212610f170332eaf173e768404c0c1d4deb041f32c297cf18931" +dependencies = [ + "from_map", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "skrifa" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fbdfe3d2475fbd7ddd1f3e5cf8288a30eb3e5f95832829570cd88115a7434ac" +dependencies = [ + "bytemuck", + "read-fonts 0.37.0", +] + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts 0.41.0", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "smol_str" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeb7109d23f319619d4cc0de5464613c8b7b1a09db2774a58101459cf6be2f10" + +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "songbird" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "371362adce10df3244fbf93475ac53391aedd425482f160a9dbb3e042577de8b" +dependencies = [ + "aead", + "aes-gcm", + "async-trait", + "byteorder", + "bytes", + "chacha20poly1305", + "crypto-common 0.1.7", + "dashmap", + "davey", + "derivative", + "discortp", + "either", + "enum-map", + "flume", + "futures", + "nohash-hasher", + "nonmax", + "opus2", + "parking_lot 0.12.5", + "pin-project", + "rand 0.9.5", + "reqwest 0.12.28", + "ringbuf", + "rubato", + "rusty_pool", + "serde", + "serde-aux", + "serde_json", + "serenity", + "serenity-voice-model", + "socket2 0.5.10", + "stream_lib", + "streamcatcher", + "symphonia", + "symphonia-core", + "tokio", + "tokio-tungstenite 0.26.2", + "tokio-util", + "tokio-websockets 0.11.4", + "tracing", + "tracing-futures", + "twilight-gateway", + "twilight-model", + "typenum", + "url", + "uuid", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable-vec" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "047720fbc1c4cc7daa75c925adba9ce3fa8e1f7b039337c281b142d4ecc6d86b" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "stream_lib" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e106dd009a0dfd2cf57777c39cad08f852debd366df6e841b250d956cec3277e" +dependencies = [ + "bytes", + "futures-core", + "futures-util", + "hls_m3u8", + "patricia_tree", + "reqwest 0.12.28", + "tokio", + "tracing", + "url", +] + +[[package]] +name = "streamcatcher" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71664755c349abb0758fda6218fb2d2391ca2a73f9302c03b145491db4fcea29" +dependencies = [ + "crossbeam-utils", + "futures-util", + "loom", +] + +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + +[[package]] +name = "string_cache" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffa8a5dbe8b3f0bbe29d4c3225daafaeead63afdc1b65fc4c01a1384166038e6" +dependencies = [ + "new_debug_unreachable", + "parking_lot 0.12.5", + "phf_shared 0.14.0", + "precomputed-hash", +] + +[[package]] +name = "string_cache_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928dcdf75e47626b3617a976ec205d9f057584c371c1f23b782129268d0e6edc" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", + "proc-macro2", + "quote", +] + +[[package]] +name = "strsim" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6446ced80d6c486436db5c078dde11a9f73d42b57fb273121e160b84f63d894c" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "530efb820d53b712f4e347916c5e7ed20deb76a4f0457943b3182fb889b06d2c" +dependencies = [ + "strum_macros 0.17.1", +] + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros 0.28.0", +] + +[[package]] +name = "strum_macros" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6e163a520367c465f59e0a61a23cfae3b10b6546d78b6f672a382be79f7110" +dependencies = [ + "heck 0.3.3", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "swash" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e" +dependencies = [ + "skrifa 0.44.0", + "yazi", + "zeno", +] + +[[package]] +name = "symphonia" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039" +dependencies = [ + "lazy_static", + "symphonia-codec-pcm", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-codec-pcm" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e89d716c01541ad3ebe7c91ce4c8d38a7cf266a3f7b2f090b108fb0cb031d95" +dependencies = [ + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-core" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af" +dependencies = [ + "arrayvec", + "bitflags 1.3.2", + "bytemuck", + "lazy_static", + "log", +] + +[[package]] +name = "symphonia-metadata" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16" +dependencies = [ + "encoding_rs", + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "libc", +] + +[[package]] +name = "tendril" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" +dependencies = [ + "new_debug_unreachable", +] + +[[package]] +name = "termina" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9048a889effe34a5cddee0af7f53285198b16dca3be510858d38dfdb3e62a04e" +dependencies = [ + "bitflags 2.13.2", + "parking_lot 0.12.5", + "rustix", + "signal-hook", + "windows-sys 0.61.2", +] + +[[package]] +name = "terminfo" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ea810f0692f9f51b382fff5893887bb4580f5fa246fde546e0b13e7fcee662" +dependencies = [ + "fnv", + "nom", + "phf 0.11.3", + "phf_codegen 0.11.3", +] + +[[package]] +name = "termios" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411c5bf740737c7918b8b1fe232dca4dc9f8e754b8ad5e20966814001ed0ac6b" +dependencies = [ + "libc", +] + +[[package]] +name = "termwiz" +version = "0.23.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4676b37242ccbd1aabf56edb093a4827dc49086c0ffd764a5705899e0f35f8f7" +dependencies = [ + "anyhow", + "base64 0.22.1", + "bitflags 2.13.2", + "fancy-regex", + "filedescriptor", + "finl_unicode", + "fixedbitset", + "hex", + "lazy_static", + "libc", + "log", + "memmem", + "nix 0.29.0", + "num-derive", + "num-traits", + "ordered-float 4.6.0", + "pest", + "pest_derive", + "phf 0.11.3", + "sha2 0.10.9", + "signal-hook", + "siphasher", + "terminfo", + "termios", + "thiserror 1.0.69", + "ucd-trie", + "unicode-segmentation", + "vtparse", + "wezterm-bidi", + "wezterm-blob-leases", + "wezterm-color-types", + "wezterm-dynamic", + "wezterm-input-types", + "winapi", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tls_codec" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b" +dependencies = [ + "serde", + "tls_codec_derive", + "zeroize", +] + +[[package]] +name = "tls_codec_derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot 0.12.5", + "pin-project-lite", + "signal-hook-registry", + "socket2 0.6.5", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" +dependencies = [ + "rustls 0.22.4", + "rustls-pki-types", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls 0.23.46", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83b561d025642014097b66e6c1bb422783339e0909e4429cde4749d1990bc38" +dependencies = [ + "futures-util", + "log", + "rustls 0.22.4", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.25.0", + "tungstenite 0.21.0", + "webpki-roots 0.26.11", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084" +dependencies = [ + "futures-util", + "log", + "rustls 0.23.46", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.26.6", + "tungstenite 0.26.2", + "webpki-roots 0.26.11", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "slab", + "tokio", +] + +[[package]] +name = "tokio-websockets" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fcaf159b4e7a376b05b5bfd77bfd38f3324f5fce751b4213bfc7eaa47affb4e" +dependencies = [ + "base64 0.22.1", + "bytes", + "fastrand", + "futures-core", + "futures-sink", + "http", + "httparse", + "ring", + "rustls-native-certs", + "rustls-pki-types", + "sha1_smol", + "simdutf8", + "tokio", + "tokio-rustls 0.26.6", + "tokio-util", +] + +[[package]] +name = "tokio-websockets" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d52efb639344a7c6adb8e62c6f3d2c19c001ff1b79a5041ba1c6ed42e19c6aa5" +dependencies = [ + "base64 0.22.1", + "bytes", + "fastrand", + "futures-core", + "futures-sink", + "http", + "httparse", + "rustls-native-certs", + "rustls-pki-types", + "rustls-platform-verifier", + "sha1_smol", + "simdutf8", + "tokio", + "tokio-rustls 0.26.6", + "tokio-util", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "http-range-header", + "httpdate", + "mime", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "tokio", + "tokio-util", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-futures" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97d095ae15e245a057c8e8451bab9b3ee1e1f68e9ba2b4fbc18d0ac5237835f2" +dependencies = [ + "pin-project", + "tracing", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "transpose" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e" +dependencies = [ + "num-integer", + "strength_reduce", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + +[[package]] +name = "tungstenite" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ef1a641ea34f399a848dea702823bbecfb4c486f911735368f1f137cb8257e1" +dependencies = [ + "byteorder", + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.8.8", + "rustls 0.22.4", + "rustls-pki-types", + "sha1 0.10.7", + "thiserror 1.0.69", + "url", + "utf-8", +] + +[[package]] +name = "tungstenite" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "rustls 0.23.46", + "rustls-pki-types", + "sha1 0.10.7", + "thiserror 2.0.21", + "url", + "utf-8", +] + +[[package]] +name = "twilight-cache-inmemory" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d205ec8d1fc62db874cc7af787cc5919a6d8513974159de950764917c563f30" +dependencies = [ + "bitflags 2.13.2", + "dashmap", + "serde", + "twilight-model", +] + +[[package]] +name = "twilight-gateway" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59267541c31f888c1587da5e7cbab182ae6efd98faedd9ea2e35a4eef43ff204" +dependencies = [ + "bitflags 2.13.2", + "fastrand", + "futures-core", + "futures-sink", + "serde", + "serde_json", + "tokio", + "tokio-websockets 0.13.3", + "tracing", + "twilight-gateway-queue", + "twilight-http", + "twilight-model", + "zstd-safe", +] + +[[package]] +name = "twilight-gateway-queue" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366a73fe47f61a3d522c3aaf70475e60634b0ae59e7b94272ed7496fffa7ceb7" +dependencies = [ + "tokio", + "tracing", +] + +[[package]] +name = "twilight-http" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05b868001d7bfb953732b3f1cd92f63cb88cd2ea902f590b1d084c66aea60e48" +dependencies = [ + "brotli-decompressor", + "fastrand", + "http", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "percent-encoding", + "rustls 0.23.46", + "serde", + "serde_json", + "tokio", + "tracing", + "twilight-http-ratelimiting", + "twilight-model", + "twilight-validate", +] + +[[package]] +name = "twilight-http-ratelimiting" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0515b0c30814068a7540fcb5f58b634259ca453fa335d42c3b2c8f2b06ac6a59" +dependencies = [ + "hashbrown 0.16.1", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "twilight-model" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf6bb7b93a7f765d89b3388cc710c0ae16104579e06bb30ea1ee6bd41420a8b" +dependencies = [ + "bitflags 2.13.2", + "serde", + "serde-value", + "serde_repr", + "time", +] + +[[package]] +name = "twilight-util" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e71de79d48ce27aba1f591b10c84677f1317489c2ea154d9b8ed01efa8bceb53" +dependencies = [ + "twilight-model", + "twilight-validate", +] + +[[package]] +name = "twilight-validate" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6a27472e023e3841d1c4e4e20253ed796e8440aada8b5205b8544f1172e661d" +dependencies = [ + "twilight-model", +] + +[[package]] +name = "typemap_rev" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74b08b0c1257381af16a5c3605254d529d3e7e109f3c62befc5d168968192998" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + +[[package]] +name = "unicode-script" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +dependencies = [ + "atomic", + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vtparse" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9b2acfb050df409c972a37d3b8e08cdea3bddb0c09db9d53137e504cfabed0" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web_atoms" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7572660c8890448ba236b7376f27e389c6a7e1c70195622faced601f855c0ada" +dependencies = [ + "phf 0.14.0", + "phf_codegen 0.14.0", + "string_cache", + "string_cache_codegen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.11", +] + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wezterm-bidi" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0a6e355560527dd2d1cf7890652f4f09bb3433b6aadade4c9b5ed76de5f3ec" +dependencies = [ + "log", + "wezterm-dynamic", +] + +[[package]] +name = "wezterm-blob-leases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "692daff6d93d94e29e4114544ef6d5c942a7ed998b37abdc19b17136ea428eb7" +dependencies = [ + "getrandom 0.3.4", + "mac_address", + "sha2 0.10.9", + "thiserror 1.0.69", + "uuid", +] + +[[package]] +name = "wezterm-color-types" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7de81ef35c9010270d63772bebef2f2d6d1f2d20a983d27505ac850b8c4b4296" +dependencies = [ + "csscolorparser", + "deltae", + "lazy_static", + "wezterm-dynamic", +] + +[[package]] +name = "wezterm-dynamic" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f2ab60e120fd6eaa68d9567f3226e876684639d22a4219b313ff69ec0ccd5ac" +dependencies = [ + "log", + "ordered-float 4.6.0", + "strsim 0.11.1", + "thiserror 1.0.69", + "wezterm-dynamic-derive", +] + +[[package]] +name = "wezterm-dynamic-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c0cf2d539c645b448eaffec9ec494b8b19bd5077d9e58cb1ae7efece8d575b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "wezterm-input-types" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7012add459f951456ec9d6c7e6fc340b1ce15d6fc9629f8c42853412c029e57e" +dependencies = [ + "bitflags 1.3.2", + "euclid", + "lazy_static", + "serde", + "wezterm-dynamic", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core 0.6.4", + "serde", + "zeroize", +] + +[[package]] +name = "yazi" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01738255b5a16e78bbb83e7fbba0a1e7dd506905cfc53f4622d89015a03fbb5" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeno" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.2+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +dependencies = [ + "cc", + "pkg-config", +] + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4e2a4c9 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,47 @@ +[package] +name = "dezio" +version = "0.1.0" +edition = "2024" + +[dependencies] +ab_glyph = "0.2.32" +anyhow = "1.0.104" +async-trait = "0.1.92" +axum = "0.8" +base64 = "0.23.1" +chrono = { version = "0.4.45", default-features = false, features = ["clock", "std"] } +cosmic-text = { version = "0.19.0", default-features = false, features = ["std", "swash"] } +dotenvy = "0.15.7" +futures = "0.3.34" +html-escape = "0.3.0" +image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp", "gif"] } +mime_guess = "2.0.5" +num-bigint = "0.5.1" +num-traits = "0.2.19" +rand = "0.10.3" +ratatui = "0.30.2" +regex = "1.13.1" +reqwest = { version = "0.13.5", default-features = false, features = ["form", "json", "multipart", "query", "rustls"] } +rustls = { version = "0.23.46", default-features = false, features = ["ring", "std"] } +scraper = "0.29.0" +serde = { version = "1.0.229", features = ["derive"] } +serde_json = { version = "1.0.154", features = ["preserve_order"] } +sha1 = "0.11.0" +sha2 = "0.11.1" +shakmaty = "0.30.2" +songbird = { version = "0.6.1", default-features = false, features = ["driver", "gateway", "rustls", "twilight", "tungstenite"] } +symphonia = { version = "0.5.5", default-features = false, features = ["pcm"] } +tokio = { version = "1.54.1", features = ["full"] } +tower-http = { version = "0.6", features = ["fs"] } +tracing = "0.1.44" +tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } +twilight-cache-inmemory = "0.17.1" +twilight-gateway = "0.17.1" +twilight-http = "0.17.1" +twilight-model = "0.17.1" +twilight-util = { version = "0.17.0", features = ["builder", "permission-calculator"] } +url = "2.5.8" +urlencoding = "2.1.3" + +[dev-dependencies] +tower = { version = "0.5", features = ["util"] } diff --git a/README.md b/README.md new file mode 100644 index 0000000..f1b4263 --- /dev/null +++ b/README.md @@ -0,0 +1,69 @@ +

Dezio

+ +

Dezio

+ +

+ An all-in-one Discord bot written in Rust — music with a live player, Last.fm, video downloads, games, AI chat, + moderation, logging and a web dashboard. +

+ +

+ ➕ Add to your server · + Website · + Support server +

+ +--- + +## What it does + +| | | +|---|---| +| 🎵 **Music** | Songs and playlists from a search or link, a live player with buttons, `/music`, vote-skip, read-ahead buffering for slow connections, auto-leave | +| 📊 **Last.fm** | Now playing, top artists/albums/tracks, collages, "Who knows?" charts, lyrics, Pixel Jumble | +| ⬇️ **Downloads** | TikTok, Instagram, YouTube, X, Reddit and more — converted while downloading, sized for Discord | +| 🛡️ **Moderation & logs** | Kick, ban, timeout, purge (15 filters), locks, slowmode, full event logging | +| 👋 **Server setup** | Welcome cards, autoroles, sticky roles, reaction roles, role menus, media-only and voting channels | +| 🎮 **Games & casino** | Chess, Connect 4, Wordle, Akinator, Cookie Clicker, blackjack, slots, roulette … | +| 🤖 **Fun** | AI chat, GIF actions, confessions, phone calls between servers, styled quotes | +| 🕹️ **Game Boy** | A Game Boy you can play inside Discord (Activity) | +| ⚙️ **Dashboard** | Sign in with Discord to change settings, quote style and role menus | + +Every command works as a slash command and most with the `D!` prefix. Run `/help` for the full list. + +## Built with + +[twilight](https://github.com/twilight-rs/twilight) (gateway, HTTP, cache) · [songbird](https://github.com/serenity-rs/songbird) (voice) · +tokio · axum (dashboard) · ratatui (console) · cosmic-text (text and emoji drawing) · yt-dlp and ffmpeg (media) + +## Run it yourself + +You need Rust, `ffmpeg`, `yt-dlp` and `curl` on the host (plus `libopus`). + +```bash +cp .env.example .env # DISCORD_BOT_TOKEN=… (and optional keys, see below) +cargo build --release +DEZIO_LIVE=1 ./target/release/dezio # console UI in a terminal +DEZIO_LIVE=1 ./target/release/dezio --headless # plain logs (for a service) +``` + +Without `DEZIO_LIVE=1` it only lists its commands and exits, so tests never touch Discord. +`cargo test` runs the unit tests (some live tests are `#[ignore]`d and need the internet). + +Optional settings (environment or `.env`): `LASTFM_API_KEY`, `OPENROUTER_KEY` (AI chat), `STEAMGRIDDB_API_KEY` (Game Boy +covers), `DASHBOARD_URL`, `DASHBOARD_CLIENT_SECRET`, `DASHBOARD_HOST` / `DASHBOARD_PORT`, `IG_COOKIES`. + +Data lives in `data/*.json`. Game Boy ROMs are **not** included — put your own in `assets/roms//`. + +## Layout + +``` +src/commands/ one folder or file per feature (music, lastfm, media, games, fun, logs …) +src/web/ dashboard + Game Boy Activity server +src/tui.rs terminal console +assets/ fonts, images, word lists, presets +web/ website, dashboard and Activity pages +docs/ Top.gg listing text +``` + +Project history and decisions are in [ROADMAP.md](ROADMAP.md). diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..dcf6e18 --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,101 @@ +# Dezio (Rust) — roadmap + +Port of the Python bot in `~/Projects/Discord Bot` (kept until this reaches parity). Backups: `~/Projects/Discord Bot-backups/dezio-python-2026-10-23.tar.gz`, Chromebook `/root/dezio-python-2026-10-23-pre-rust.tar.gz`. + +Stack: tokio, twilight (gateway/http/model — has Components V2 `Container` etc.), songbird for voice, serde. Build on the PC (`~/.cargo/env`), copy the release binary to the Chromebook (x86_64). +Never log in with the real token on the PC (the live bot would answer twice). + +Order: 1 core (config, JsonStore with debounce, V2 card builder, command framework, prefix `D!` + slash) → 2 admin/moderation/logs → 3 utility/search/info/help → 4 media (/download incl. parallel convert) → 5 fun/AI/games/casino → 6 music + Last.fm → 7 dashboard + Game Boy Activity server + TUI → 8 data migration check against the old `data/*.json`. + +FINAL STEP (owner request): fix the Chromebook's start-at-boot service (systemd unit for the Rust binary; previously the bot ran by hand in screen). + +## Status +- Stage 1 (2026-10-23): paths, JsonStore (same file format, debounced atomic saves), V2 `Card` builder, one command framework for `D!` + slash (per-guild prefix from data/prefixes.json, permission check, user-install contexts, slash sync with hash), commands `ping` and `prefix`. 5 unit tests pass; release binary builds (14 MB). NOT run against Discord: the bot only connects when `DEZIO_LIVE=1` (set that on the Chromebook only). +- Stage 2a (2026-10-23): member/role cache (twilight-cache-inmemory, members requested on GuildCreate), converters (durations, member lookup by name/mention/id/reply), error cards (user errors / 403 / unexpected), permission + role-hierarchy checks, Moderation (kick, ban, unban, timeout, untimeout, nick, role, slowmode), purge (all 15 filters, bulk + one-by-one, Stop button, progress card), help (categories, paged, detail pages, select menu, works after restarts). 18 unit tests incl. a check that every help page fits Discord's V2 limits. +- Not yet in 2a: /unban and /timeout autocomplete, `help` autocomplete, bot-permission pre-checks, per-command cooldowns. +- Next: stage 2b = logs (audit-log matching, 1174 lines in Python), welcome, role menus, channel tools, dashboard cog. + +## Stage 2b status (2026-10-23) +- Done: cdn link refresher, welcome/goodbye/autorole/sticky roles (setup panel with channel + role selects, edit modal, test; join/leave/pending handlers), reqwest HTTPS (tested), 21 unit tests. +- Still to do in 2b: logs (audit-log matching), channel tools (lock/media/reddit/nsfw/pin), role menus. + +## Role menus — owner request (keep presets, but configurable in Discord AND on the website) +Today: stock categories live in assets/data/role_menus.json (name, emoji, role names); each server only picks which preset +names to use (data/role_menus.json: {guild: {cat: {roles:[names], stock:"one"|"many"}, public_messages:{cat:{channel,message}}}}), +and only through the Discord editor; the dashboard has no role-menu page. +Plan (backward compatible with the existing file): +- Presets stay as templates. A server's category may override `name` and `emoji`, edit its `roles` (add/remove/reorder, any + name, not just preset ones; missing roles are created with a colour on publish), switch `stock` one/many, and can be a + brand-new `custom` category. "Reset to preset" restores the template. +- Discord: `/cosmetics` editor gets rename/emoji/add role/remove role/reset, plus "New custom menu". +- Website: a Role menus page with the same operations, saving to the same file; the bot re-publishes in place. +- Role menus, Discord side DONE (2026-10-23): `/cosmetics` (`D!cosmetics`) overview + editor — rename/emoji, add own roles, tick roles, pick one/many, reset to preset, new/delete custom menus, Publish (creates/deletes roles, posts or edits the dropdown in place); member dropdowns work from the message itself. Reads the existing data/role_menus.json (checked against a copy of the real file). The website page comes with the Rust dashboard (stage 7); the file format above is the shared contract. +- Still open in 2b: logs, channel tools (lock/media/reddit/nsfw/pin). + +## Stage 2b — DONE (2026-10-23) +- Channel tools: `/lock` `D!lock` `D!unlock` (saved overwrites in the Python bot's own format), `/media`, `/reddit` `D!unreddit`, `/setnsfw` `D!nsfw`, right-click "Pin Message" with a persistent Unpin button (framework now supports message context menus). +- Logger: audit-log matching (pushed entries, claims, merged message-delete/voice credits), batched webhook delivery (falls back to the bot), `/logging` setup panel, and handlers for bans, joins (with the invite used), leaves/kicks, AutoMod, pins, prune, message delete/edit/bulk (with transcript), member nick/roles/timeout/boost/screening, voice, channels + permission changes, threads, stages, webhooks, roles, emoji, stickers, server settings, scheduled events. Reads the existing data/logging.json. +- Differences from Python worth knowing: other people's username/avatar changes are noticed through member updates (Discord only sends the bot's own user updates); message edit/delete logs need the message to be in the 3000-message cache, as before. +- 35 unit tests. Nothing tested against Discord yet. +- Next: stage 3 = utility/search/info (userinfo, serverinfo, avatar, weather, wiki, define, calculator, snipe, afk, embed builder…). + +## Stage 3a — DONE (2026-10-23) +- Info cards: userinfo, serverinfo, channelinfo, roleinfo, avatar, banner + "Show Avatar"/"Show Banner" right-click apps (framework now has user menus), card colours taken from avatars/icons (`colors.rs`: median-cut palette like the Python version, cached), per-user/server prefs (`prefs.rs`, data/users.json + servers.json), snipe (deleted/edited/reactions, opt-out, paging), afk (+ welcome-back list), mpreg. 47 unit tests. +- Still open in stage 3 (3b): tools.py (calculate with keypad, color, translate, weather, viruscheck), search.py (web/image search, wikipedia, define, urban, rule34), embeds.py (/embed builder + "Edit Embed"), and the rest of other.py (dm_echo, /ad, smash, serverclone, owner DMs on join/leave). + +## Stage 3b (tools) — DONE (2026-10-23) +- Calculator (own expression parser: big integers, `2^10`, `sin 30`, `5!`, `√16`, old `16 sqrt` style, same error messages; the button keypad keeps its state on the card itself so it survives restarts), colour tool (swatch PNG drawn with the bundled Noto fonts, formats, matches, Lighter/Darker/Complement/Random buttons), translate (`D!tr`, "Translate Message" app, Google + MyMemory fallback), weather (Open-Meteo + ZIP + OpenStreetMap geocoding, autocomplete, °C/°F memory, private "saved place"), VirusTotal (link/file, free-tier limits). +- Framework: autocomplete, file-attachment options, replies with a file, private "thinking" answers. +- Verified against the live services: Paris / Denver Colorado / Springfield, IL / 10001 / Tokyo geocode and forecast correctly (`cargo test live_weather -- --ignored`). 65 unit tests. +- Still open in stage 3 (3c): search.py (web/image search, wikipedia, define, urban, rule34), embeds.py (/embed builder + "Edit Embed"), rest of other.py (dm_echo, /ad, smash, serverclone, owner DMs on join/leave). + +## Stage 3c — DONE (2026-10-23) — stage 3 complete +- Search: `/search` + `D!image` (DuckDuckGo html/lite/instant, Bing → Openverse → Zenserp images), Wikipedia (sections, languages, "other matches", random, `fr: Paris`), define (+ pronunciation audio, Urban Dictionary fallback), `D!urban`, rule34 (age-restricted only, same blocklist, TBIB/Xbooru). Generic pager (`pager.rs`) for result pages. +- Embed builder (`/embed`, "Edit Embed"): the preview embed is the draft, so editors survive restarts; text/images/author/footer/fields/JSON/import. +- `dm_echo`, `/ad` (+ the persistent edit button/form), `smash`/`smashstats`, owner-only `serverclone` (with a confirm prompt: `confirm.rs`), and DMs to server owners when the bot is added/removed. +- Framework: cooldowns, owner-only commands. +- Verified against the live services: web search, image search, Wikipedia (8 sections, 59 languages), dictionary, Urban Dictionary (`cargo test live_search -- --ignored`). 81 unit tests; 53 commands/menus registered. +- Next: stage 4 = media (/download incl. the parallel convert, images/effects, quote, emoji). + +## Stage 4 — DONE (2026-10-23) — media +- **Text engine** (`text.rs`, cosmic-text): real shaping + per-character font fallback, so Latin, CJK, Arabic (right-to-left), Indic, Thai, symbols and COLOUR emoji all draw. Fonts ship in `assets/fonts/` (Noto Sans + `fallback/`: CJK, Arabic, Hebrew, Indic scripts, Symbols, Math, Noto Color Emoji ≈ 75 MB with the rest of assets). Google Fonts picked by name are downloaded once (no API key now: the public CSS endpoint) into `data/fonts/google/`. +- **Quotes** (`media/quote.rs`): right-click → Create Quote, or reply `D!quote`. Default = the familiar "quote bot" look (greyscale portrait fading into black on the left, centred quote, "- Name", "@handle", small watermark — 1200×630). Presets: Classic, **Portrait** (630×790: picture fading into black, big quote marks, text, divider line, small avatar icon + @handle), and the four older circle styles. On the card: preset, font (any Google Font), layout, flip, B&W/colour, quote marks, name, @handle, divider, icon (off/avatar/server), bold, and a form for size / text colour / background / gradient / watermark. **Save as my default** / **Save for this server** (Manage Server) / Reset. The watermark defaults to "Dezio" (editable, empty = none). + - Shared file for the dashboard: `data/quote.json` = `{"users": {"": Style}, "servers": {"": Style}}`; every `Style` key has a default, so partial objects are fine. Keys: preset, layout (wide|portrait), image (fade|circle|none), grayscale, flip, bg, bg2 (gradient end or null), text, author, muted, font, bold, size (0 = fit), marks, name, handle, line, icon (none|avatar|server), watermark, quote_chars. Resolution order: your style → server style → Classic. +- **Image effects** (`media/images.rs`): `/image` (`D!fx`): all 10 effects and 14 filters, GIFs/animated WebP keep their animation, size-aware re-render for the upload limit. NEW `convert` option (also `/convert` and `D!convert `): picture/GIF/video → gif, mp4, webm, png, jpg, webp or mp3 (ffmpeg; retries smaller settings until it fits; a still picture becomes a 3 s clip). Sources: attachment, replied message (attachments, embed video/image, stickers), link, custom emoji, @user avatar. `/petpet` + `D!petpet`. +- **Emoji** (`media/emoji.rs`): `/steal`, `/combine` (Emoji Kitchen), `D!emoji` browser and the Get Assets menu with "Add to this server". +- **/download** (`media/download/`): the whole Python pipeline ported (yt-dlp + ffmpeg + gallery-dl as child processes): sizes checked before downloading (CDN asked when yt-dlp doesn't know), H.264+AAC preferred, size watchdog that drops to a smaller stream, **VP9/AV1/HEVC converted while downloading** (one ffmpeg reads yt-dlp's stream URLs directly; falls back to download-then-convert), ffprobe validation, one-pass compression, slideshows/carousels via gallery-dl, audio mode (Opus 96 kbps), progress card with Cancel, Delete + Original post buttons, upload retries, one job at a time. Verified against a local server (H.264, VP9, convert-while-downloading, audio, forced squeeze, cancel) and real links (a direct mp4 and a YouTube video). +- Framework: `Command::slash_as` (a slash name different from the text command: `/image` = `D!fx`), `find_slash`. +- Not tested against Discord. Known gaps: no per-command "I need Attach Files" pre-check; the quote card's controls stop working after a restart (sessions live in memory, as the Python view did). +- Next: stage 5 = fun / AI / games / casino. + +## Stage 6 — DONE (2026-10-23) — music + Last.fm +- **Music** (`commands/music/`): songbird (with Discord's required voice encryption) for voice; yt-dlp lookups in separate processes; ffmpeg → PCM read ahead in a 15 s buffer (a stall plays silence instead of rushing; position counts real frames only). `/play` (search or link, playlists, YouTube mixes load 25 first then the rest), `/pause` `/resume` `/skip` `/stop` `/queue` `/nowplaying` `/seek` `/loop` `/shuffle` `/unqueue` `/volume` `/join` `/leave` + `D!mhelp`, aliases as before. Now-playing panel with buttons that carry `music::` (work after restarts), card colour from the cover, bitrate = channel bitrate (≤96 kbps), idle leave after 5 min, prefetch of the next stream, volume saved per server. +- **Last.fm** (`commands/lastfm/`): `/fm` (now playing, top, recent, profile, link), `D!ta/tab/tt/recent/fmprofile/fmset`, Who Knows (`D!wk/wkt/wka`, prefix only), `D!chart` collage (prefix only) (drawn with the new text engine), Pixel Jumble (`D!px`, prefix only: a linked member starts a round from their own albums, then anyone can answer by typing in chat or with the button), `/lyrics` (LRCLIB + lyrics.ovh), "Listen to song" button (yt-dlp → Opus file, private, deletes itself). Cards use the games engine (owner-only buttons, switch views, idle end). Reads data/lastfm.json. +- Verified live: Last.fm API (profile, top artists, not-found, album info); YouTube search → stream → ffmpeg → 204 real audio frames. NOT verified: actually joining a voice channel (needs Discord). +- Known gap: on a stage channel the bot asks to speak but can't auto-unsuppress (twilight's builder has no "suppress: false"). +- Next: stage 7 = dashboard (+ role-menu page, quote styles page), Game Boy Activity server, TUI. + +## Stage 7 — DONE (2026-10-23) — dashboard, Game Boy Activity, console +- **Dashboard** (`src/web/`, axum): the website, `/dashboard` (the same pages as before, extended), Discord sign-in (OAuth, sessions in data/dashboard_sessions.json — same format as Python, so people stay signed in), CSRF + same-origin checks, live Manage Server checks from the member cache. API: `/api/me`, `/api/user` (Last.fm link, AFK, download quality, weather, privacy, **quote style**), `/api/guilds/` (prefix, music volume, snipe, logging channels, welcome/goodbye + autoroles, AI personality/lock, **server quote style**, **role menus**), `/api/places`, `/api/quote/preview` (the bot draws the preview, so it's exactly what Create Quote makes). `DASHBOARD_URL`, `DASHBOARD_CLIENT_SECRET`, `DASHBOARD_HOST/PORT` as before. + - New pages: **Quote style** (preset, layout, picture mode, toggles, icon, any Google Font, size, colours, gradient, watermark, live preview; saved as the person's default or the server's default → data/quote.json) and **Role menus** (edit presets, add roles, one/many, reset to preset, new custom menus, publish to a channel — the same data and publish code as `/cosmetics`). +- **Game Boy Activity** (`src/web/activity.rs`, `commands/gameboy.rs`): the same API as the Python server (config, token, web-session, library with covers from SteamGridDB, ROM download, battery saves, save states, legacy saves); `/gameboy` launches the Activity (raw interaction callback type 12), `D!gameboy` posts a Play card; slash sync keeps Discord's "Launch" entry-point command. +- **Console** (`src/tui.rs`, ratatui): live stats header, Activity / Console / Commands / Servers tabs, command box (`help`, `sync`, `status `, `send `, `servers`, `leave `, `clear`, `quit`). Starts when the bot runs in a terminal; `--headless` or no terminal (systemd) logs as plain text. Not ported: cog reload/load/unload (nothing to reload in a binary) and the Python self-test tab (the Rust tests replace it). +- **Status**: "Watching In N servers | /help | D!help" (+ owner `setstatus` / `resetstat`). +- `--web-dev` serves only the web pages with a made-up signed-in session (cookie `dezio_session=devtoken`, http://127.0.0.1:8099) for looking at the dashboard without Discord. Checked in the browser: the quote editor draws wide and portrait previews (Latin/Japanese/Arabic/emoji) and saves. +- 7 web tests (pages + security headers, sign-in gate, CSRF/origin refusals, settings saved and validated, quote preview PNG, ROM library + saves per player). +- Not tested: the server-settings endpoints (they need a live server cache), OAuth against Discord, the Activity inside Discord. +- Note: ~/Projects/Dezio/data/ holds leftovers from the unit tests (fake ids); it's git-ignored and gets replaced by the real Python data in stage 8. +- Next: stage 8 = run against the real data/*.json from the Python bot, a final comparison of every command, then deploy + the Chromebook boot service. + +## Stage 8 — IN PROGRESS (2026-10-23) — parity check +- Data: compared every file in the Python `data/` with what the Rust code reads (afk, ads, ai, casino, channels, confessions, cookieclicker, lastfm, logging, prefixes, reaction_roles, role_menus, snipes, status_roles, sticky_roles, temp_roles, welcome): same names and shapes, so the Python files can be copied over as they are. `users.json` / `servers.json` don't exist in Python's data yet (created on first use). +- Command comparison (every Python command, alias and slash name vs the Rust registry) found one gap: **reaction roles, temporary roles and status roles** (`roles.py`). Now ported in `src/commands/reactionroles.rs`: `D!rr add|remove|list| [minutes]`, `/reactionrole`, `/rr-type`, `/rep` (+ `D!rep`), the reaction add/remove handler (normal, toggle, unique, verify, temporary), a 30 s expiry loop, and status-role sync on presence changes, joins and `/rep` changes. Uses the real data (4 reaction-role messages, one `/hurtme` status role). +- Not ported on purpose: the owner-only `D!dashboard` (the web server starts by itself), `D!selftest` (Rust tests replace it). +- Still to do: deploy to the Chromebook and fix its start-at-boot service (needs the owner's go-ahead because it replaces the running Python bot); Python files stay until the owner says to delete them. + +## Stage 8 — DONE (2026-10-23) — deployed +- Chromebook (192.168.1.71): Rust bot in `/root/Dezio` (binary, assets, web, copy of Python's data + .env). `dezio-bot.service` now runs `/root/Dezio/dezio --headless` (DEZIO_LIVE=1), enabled at boot, Restart=always; the health-check timer still checks :8080. Python bot stopped (its files in `/root/Discord Bot` untouched). +- Backups: `/root/dezio-bot.service.bak` (old unit), `/root/dezio-python-data-*-pre-switch.tar.gz`, `/root/dezio-python-2026-10-23-pre-rust.tar.gz`. +- Rollback: `systemctl stop dezio-bot; cp /root/dezio-bot.service.bak /etc/systemd/system/dezio-bot.service; systemctl daemon-reload; systemctl start dezio-bot`. +- Fix found on first start: slash descriptions over 100 characters made Discord refuse the whole sync; they're now cut to 100. +- Source: forgejo:astar76/Dezio.git (branch master). diff --git a/assets/fonts/LICENSE.txt b/assets/fonts/LICENSE.txt new file mode 100644 index 0000000..a437450 --- /dev/null +++ b/assets/fonts/LICENSE.txt @@ -0,0 +1,2 @@ +Noto Sans and the fonts in google/ are licensed under the SIL Open Font License 1.1 +(https://openfontlicense.org). They are bundled so image commands look the same on every host. diff --git a/assets/fonts/NotoSans-Bold.ttf b/assets/fonts/NotoSans-Bold.ttf new file mode 100644 index 0000000..aae7546 Binary files /dev/null and b/assets/fonts/NotoSans-Bold.ttf differ diff --git a/assets/fonts/NotoSans-Regular.ttf b/assets/fonts/NotoSans-Regular.ttf new file mode 100644 index 0000000..f27f4ff Binary files /dev/null and b/assets/fonts/NotoSans-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoColorEmoji.ttf b/assets/fonts/fallback/NotoColorEmoji.ttf new file mode 100644 index 0000000..e605743 Binary files /dev/null and b/assets/fonts/fallback/NotoColorEmoji.ttf differ diff --git a/assets/fonts/fallback/NotoSansArabic-Regular.ttf b/assets/fonts/fallback/NotoSansArabic-Regular.ttf new file mode 100644 index 0000000..72c9228 Binary files /dev/null and b/assets/fonts/fallback/NotoSansArabic-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansArmenian-Regular.ttf b/assets/fonts/fallback/NotoSansArmenian-Regular.ttf new file mode 100644 index 0000000..08069ed Binary files /dev/null and b/assets/fonts/fallback/NotoSansArmenian-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansBengali-Regular.ttf b/assets/fonts/fallback/NotoSansBengali-Regular.ttf new file mode 100644 index 0000000..f558175 Binary files /dev/null and b/assets/fonts/fallback/NotoSansBengali-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansCJK-Bold.ttc b/assets/fonts/fallback/NotoSansCJK-Bold.ttc new file mode 100644 index 0000000..ce48b99 Binary files /dev/null and b/assets/fonts/fallback/NotoSansCJK-Bold.ttc differ diff --git a/assets/fonts/fallback/NotoSansCJK-Regular.ttc b/assets/fonts/fallback/NotoSansCJK-Regular.ttc new file mode 100644 index 0000000..a2033d0 Binary files /dev/null and b/assets/fonts/fallback/NotoSansCJK-Regular.ttc differ diff --git a/assets/fonts/fallback/NotoSansDevanagari-Regular.ttf b/assets/fonts/fallback/NotoSansDevanagari-Regular.ttf new file mode 100644 index 0000000..0bf16ff Binary files /dev/null and b/assets/fonts/fallback/NotoSansDevanagari-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansEthiopic-Regular.ttf b/assets/fonts/fallback/NotoSansEthiopic-Regular.ttf new file mode 100644 index 0000000..8820031 Binary files /dev/null and b/assets/fonts/fallback/NotoSansEthiopic-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansGeorgian-Regular.ttf b/assets/fonts/fallback/NotoSansGeorgian-Regular.ttf new file mode 100644 index 0000000..6c5008d Binary files /dev/null and b/assets/fonts/fallback/NotoSansGeorgian-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansGujarati-Regular.ttf b/assets/fonts/fallback/NotoSansGujarati-Regular.ttf new file mode 100644 index 0000000..cf100cf Binary files /dev/null and b/assets/fonts/fallback/NotoSansGujarati-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansGurmukhi-Regular.ttf b/assets/fonts/fallback/NotoSansGurmukhi-Regular.ttf new file mode 100644 index 0000000..3b08955 Binary files /dev/null and b/assets/fonts/fallback/NotoSansGurmukhi-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansHebrew-Regular.ttf b/assets/fonts/fallback/NotoSansHebrew-Regular.ttf new file mode 100644 index 0000000..ef33d06 Binary files /dev/null and b/assets/fonts/fallback/NotoSansHebrew-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansKannada-Regular.ttf b/assets/fonts/fallback/NotoSansKannada-Regular.ttf new file mode 100644 index 0000000..68da17f Binary files /dev/null and b/assets/fonts/fallback/NotoSansKannada-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansKhmer-Regular.ttf b/assets/fonts/fallback/NotoSansKhmer-Regular.ttf new file mode 100644 index 0000000..5c22ec4 Binary files /dev/null and b/assets/fonts/fallback/NotoSansKhmer-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansLao-Regular.ttf b/assets/fonts/fallback/NotoSansLao-Regular.ttf new file mode 100644 index 0000000..72cb424 Binary files /dev/null and b/assets/fonts/fallback/NotoSansLao-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansMalayalam-Regular.ttf b/assets/fonts/fallback/NotoSansMalayalam-Regular.ttf new file mode 100644 index 0000000..32dc2c6 Binary files /dev/null and b/assets/fonts/fallback/NotoSansMalayalam-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansMath-Regular.ttf b/assets/fonts/fallback/NotoSansMath-Regular.ttf new file mode 100644 index 0000000..a59e95c Binary files /dev/null and b/assets/fonts/fallback/NotoSansMath-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansMyanmar-Regular.ttf b/assets/fonts/fallback/NotoSansMyanmar-Regular.ttf new file mode 100644 index 0000000..5c0da8c Binary files /dev/null and b/assets/fonts/fallback/NotoSansMyanmar-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansSinhala-Regular.ttf b/assets/fonts/fallback/NotoSansSinhala-Regular.ttf new file mode 100644 index 0000000..12c260e Binary files /dev/null and b/assets/fonts/fallback/NotoSansSinhala-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansSymbols-Regular.ttf b/assets/fonts/fallback/NotoSansSymbols-Regular.ttf new file mode 100644 index 0000000..f39694c Binary files /dev/null and b/assets/fonts/fallback/NotoSansSymbols-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansSymbols2-Regular.ttf b/assets/fonts/fallback/NotoSansSymbols2-Regular.ttf new file mode 100644 index 0000000..a0a8cfe Binary files /dev/null and b/assets/fonts/fallback/NotoSansSymbols2-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansTamil-Regular.ttf b/assets/fonts/fallback/NotoSansTamil-Regular.ttf new file mode 100644 index 0000000..3999af8 Binary files /dev/null and b/assets/fonts/fallback/NotoSansTamil-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansTelugu-Regular.ttf b/assets/fonts/fallback/NotoSansTelugu-Regular.ttf new file mode 100644 index 0000000..d72413a Binary files /dev/null and b/assets/fonts/fallback/NotoSansTelugu-Regular.ttf differ diff --git a/assets/fonts/fallback/NotoSansThai-Regular.ttf b/assets/fonts/fallback/NotoSansThai-Regular.ttf new file mode 100644 index 0000000..8e1e638 Binary files /dev/null and b/assets/fonts/fallback/NotoSansThai-Regular.ttf differ diff --git a/assets/fonts/google/Ballet.ttf b/assets/fonts/google/Ballet.ttf new file mode 100755 index 0000000..d65a6a9 Binary files /dev/null and b/assets/fonts/google/Ballet.ttf differ diff --git a/assets/fonts/google/Fira_Sans.ttf b/assets/fonts/google/Fira_Sans.ttf new file mode 100755 index 0000000..6f80647 Binary files /dev/null and b/assets/fonts/google/Fira_Sans.ttf differ diff --git a/assets/fonts/google/Hind.ttf b/assets/fonts/google/Hind.ttf new file mode 100755 index 0000000..682abc3 Binary files /dev/null and b/assets/fonts/google/Hind.ttf differ diff --git a/assets/fonts/google/Lato.ttf b/assets/fonts/google/Lato.ttf new file mode 100755 index 0000000..bb2e887 Binary files /dev/null and b/assets/fonts/google/Lato.ttf differ diff --git a/assets/fonts/google/Lobster.ttf b/assets/fonts/google/Lobster.ttf new file mode 100755 index 0000000..21c0073 Binary files /dev/null and b/assets/fonts/google/Lobster.ttf differ diff --git a/assets/fonts/google/Montserrat.ttf b/assets/fonts/google/Montserrat.ttf new file mode 100755 index 0000000..895e220 Binary files /dev/null and b/assets/fonts/google/Montserrat.ttf differ diff --git a/assets/fonts/google/Nunito_Sans.ttf b/assets/fonts/google/Nunito_Sans.ttf new file mode 100755 index 0000000..2d9df4d Binary files /dev/null and b/assets/fonts/google/Nunito_Sans.ttf differ diff --git a/assets/fonts/google/Oxygen.ttf b/assets/fonts/google/Oxygen.ttf new file mode 100755 index 0000000..d03f43a Binary files /dev/null and b/assets/fonts/google/Oxygen.ttf differ diff --git a/assets/fonts/google/Playfair_Display.ttf b/assets/fonts/google/Playfair_Display.ttf new file mode 100755 index 0000000..2cd12a3 Binary files /dev/null and b/assets/fonts/google/Playfair_Display.ttf differ diff --git a/assets/fonts/google/Raleway.ttf b/assets/fonts/google/Raleway.ttf new file mode 100755 index 0000000..ec9b483 Binary files /dev/null and b/assets/fonts/google/Raleway.ttf differ diff --git a/assets/fonts/google/Roboto.ttf b/assets/fonts/google/Roboto.ttf new file mode 100755 index 0000000..7e3bb2f Binary files /dev/null and b/assets/fonts/google/Roboto.ttf differ diff --git a/assets/fonts/google/Ubuntu.ttf b/assets/fonts/google/Ubuntu.ttf new file mode 100755 index 0000000..b5505e6 Binary files /dev/null and b/assets/fonts/google/Ubuntu.ttf differ diff --git a/assets/fonts/google/Work_Sans.ttf b/assets/fonts/google/Work_Sans.ttf new file mode 100755 index 0000000..d24586c Binary files /dev/null and b/assets/fonts/google/Work_Sans.ttf differ diff --git a/assets/images/banner.jpg b/assets/images/banner.jpg new file mode 100755 index 0000000..ace94e8 Binary files /dev/null and b/assets/images/banner.jpg differ diff --git a/assets/images/confessions.png b/assets/images/confessions.png new file mode 100755 index 0000000..94ebb59 Binary files /dev/null and b/assets/images/confessions.png differ diff --git a/assets/images/dezio.png b/assets/images/dezio.png new file mode 100755 index 0000000..5c5eeeb Binary files /dev/null and b/assets/images/dezio.png differ diff --git a/assets/images/logger.png b/assets/images/logger.png new file mode 100755 index 0000000..f469b2c Binary files /dev/null and b/assets/images/logger.png differ diff --git a/assets/roms/README.md b/assets/roms/README.md new file mode 100644 index 0000000..160bc17 --- /dev/null +++ b/assets/roms/README.md @@ -0,0 +1 @@ +Put your own .gb / .gbc ROM files here (not included in the repository). diff --git a/docs/topgg.md b/docs/topgg.md new file mode 100644 index 0000000..47621c7 --- /dev/null +++ b/docs/topgg.md @@ -0,0 +1,64 @@ +# Top.gg listing for Dezio + +Copy each block into the matching field on the bot's Top.gg edit page. + +## Links + +| Field | Value | +|---|---| +| Invite URL | https://discord.com/oauth2/authorize?client_id=1387839600017412106&scope=bot%20applications.commands&permissions=8 | +| Support server | https://discord.gg/UnSga5DmR7 | +| Website | https://archlinux.tail7c4f5e.ts.net | +| GitHub / source | https://archlinux.tail7c4f5e.ts.net/git/astar76/Dezio | +| Prefix | `D!` (every command is also a slash command) | +| Library | Rust (twilight + songbird) | + +## Tags + +`Music` · `Moderation` · `Fun` · `Utility` · `Games` · `Logging` · `Social` · `Last.fm` + +## Short description (headline) + +Music with a live player, Last.fm stats, video downloads, games, AI chat, moderation and logs — one bot, set up in minutes. + +## Long description + +```markdown +# Dezio — music, Last.fm, downloads, games and moderation in one bot + +**Dezio** is an all-in-one Discord bot that does the everyday jobs of a server without needing six different bots. Everything works as a **slash command** and most things also work with the **`D!` prefix**. Type `/help` to see every command. + +## 🎵 Music +Play songs and playlists from a search or a link (YouTube, SoundCloud, Bandcamp and more) with a **live now-playing player** that has pause, skip, seek, loop, shuffle and volume buttons. +- `/music` — every music action in one command +- Vote-to-skip / stop so one person can't ruin it for everyone +- Smooth playback on slow connections: it reads ahead and re-buffers instead of stuttering +- Leaves by itself when everyone is gone or nothing is playing +- Music chat cleans itself up — only the player stays + +## 📊 Last.fm +Now-playing cards, top artists / albums / tracks, album collages, server **"Who knows?"** leaderboards, lyrics, and **Pixel Jumble** — a server-wide guess-the-album game anyone can join by typing. + +## ⬇️ Downloads +Videos, songs and photo posts from **TikTok, Instagram, YouTube, X, Reddit** and more, converted while they download and sized to fit Discord's upload limit. + +## 🛡️ Moderation & logging +Kick, ban, timeout, purge with 15 filters, channel locks and slowmode — plus detailed logs for messages, members, roles, channels, voice, invites and more that credit the right moderator. + +## 👋 Server setup +Welcome and goodbye cards, autoroles and sticky roles, **reaction roles** (normal, toggle, unique, verify and temporary), custom **role menus**, media-only and Reddit-style voting channels, and a **web dashboard**. + +## 🎮 Games & casino +Chess, Connect 4, tic-tac-toe, Wordle, hangman, minesweeper, 2048, Akinator, Cookie Clicker — plus coin flip, blackjack, slots and roulette with a server economy. + +## ✨ And more +AI chat with a personality you can change per server, anime GIF actions, confessions, a phone-call system between servers, quotes you can style, emoji tools, weather, translation, wikipedia / web / image search, a calculator and a **Game Boy you can play inside Discord** (Activity). + +## Links +- **Website & dashboard:** https://archlinux.tail7c4f5e.ts.net +- **Support server:** https://discord.gg/UnSga5DmR7 +- **Source code:** https://archlinux.tail7c4f5e.ts.net/git/astar76/Dezio +- Privacy policy and terms are on the website. + +Written in **Rust** for speed. Add it, type `/help`, and you're done. +``` diff --git a/src/audit.rs b/src/audit.rs new file mode 100644 index 0000000..b49a9a3 --- /dev/null +++ b/src/audit.rs @@ -0,0 +1,438 @@ +//! Who did it? Matching server events to the audit-log entries that explain them. +//! +//! Discord pushes every new audit-log entry to bots over the gateway. [`AuditFeed`] keeps the last +//! minute of them so an event handler (member left, channel deleted …) can ask "which entry belongs +//! to this?". +//! +//! Rules that keep attribution honest: +//! * An entry only matches an event that happened around the same time, so a ban from last week can +//! never be blamed for someone leaving today. +//! * Each entry is handed to each kind of consumer once, so a kick isn't reported again if the same +//! person rejoins and leaves a few seconds later. +//! * Message deletes are special: Discord *merges* them ("Mod deleted 3 messages by X") and only bumps +//! a counter, which is not pushed. [`AuditFeed::merged`] polls those counters and turns each +//! increase into one credit for one deleted message. +//! +//! Actions Dezio performs for someone pass `audit_reason()` as the reason so the log shows the real +//! moderator instead of just the bot. +use crate::state::State; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use tokio::sync::oneshot; +use twilight_model::guild::audit_log::{AuditLogChange, AuditLogEntry, AuditLogEventType as A}; +use twilight_model::guild::Permissions; +use twilight_model::id::marker::{GuildMarker, UserMarker}; +use twilight_model::id::Id; + +const KEEP: f64 = 60.0; // seconds a pushed entry stays searchable +const SLACK: f64 = 10.0; // an entry may be this much older than the event it explains +const CREDIT_TTL: f64 = 20.0; // an unused "deleted by" credit expires after this long +const QUIET: f64 = 900.0; // merged entries older than this are assumed closed + +pub fn now() -> f64 { + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64()) +} + +/// When the entry was made (from its id). +pub fn entry_time(e: &AuditLogEntry) -> f64 { + (((e.id.get() >> 22) + 1_420_070_400_000) as f64) / 1000.0 +} + +pub fn target_id(e: &AuditLogEntry) -> Option { + e.target_id.map(|t| t.get()) +} + +/// True if the entry changed this property (the Python code's `hasattr(entry.after, "nick")`). +pub fn changed(e: &AuditLogEntry, f: impl Fn(&AuditLogChange) -> bool) -> bool { + e.changes.iter().any(f) +} + +/// Who performed an action, and why. +#[derive(Clone, Debug, PartialEq)] +pub struct Actor { + pub user_id: Option>, + pub reason: Option, + /// Dezio carried it out for `user_id`. + pub via: bool, +} + +/// `Name (123456789012345678): reason` -> (id, reason) +pub fn parse_via_bot(reason: &str) -> Option<(Id, Option)> { + let mut from = 0; + while let Some(p) = reason[from..].find(" (") { + let start = from + p + 2; + let digits: String = reason[start..].chars().take_while(char::is_ascii_digit).collect(); + let after = start + digits.len(); + if p > 0 || from > 0 { + if (15..=21).contains(&digits.len()) && reason[after..].starts_with(')') { + let rest = &reason[after + 1..]; + let id = digits.parse().ok().and_then(Id::new_checked)?; + if rest.is_empty() { + return Some((id, None)); + } + if let Some(r) = rest.strip_prefix(": ") { + return Some((id, Some(r.to_string()))); + } + } + } + from = start; + } + None +} + +impl Actor { + pub fn from_entry(e: &AuditLogEntry, bot: Id) -> Actor { + if e.user_id == Some(bot) { + if let Some((id, reason)) = e.reason.as_deref().and_then(parse_via_bot) { + return Actor { user_id: Some(id), reason, via: true }; + } + } + Actor { user_id: e.user_id, reason: e.reason.clone(), via: false } + } +} + +/// What to look for. +#[derive(Clone)] +pub struct Query { + pub actions: Vec, + pub target: Option, + pub check: Option bool + Send + Sync>>, + pub consumer: &'static str, + pub claim_key: Option, + pub since: Option, + pub timeout: f64, +} + +impl Query { + pub fn new(consumer: &'static str, actions: &[A]) -> Self { + Self { actions: actions.to_vec(), target: None, check: None, consumer, claim_key: None, since: None, timeout: 2.5 } + } + pub fn target(mut self, t: u64) -> Self { + self.target = Some(t); + self + } + pub fn check(mut self, f: impl Fn(&AuditLogEntry) -> bool + Send + Sync + 'static) -> Self { + self.check = Some(Arc::new(f)); + self + } + pub fn claim_key(mut self, k: u64) -> Self { + self.claim_key = Some(k); + self + } + pub fn timeout(mut self, t: f64) -> Self { + self.timeout = t; + self + } + fn key_extra(&self) -> Option { + self.claim_key.or(self.target) + } +} + +type ClaimKey = (&'static str, u64, Option); + +struct Waiter { + guild: Id, + query: Query, + since: f64, + tx: Option>, +} + +#[derive(Default)] +struct Inner { + recent: HashMap, VecDeque>, + waiters: Vec, + claimed: HashSet, + claim_order: VecDeque, + live: HashSet>, + counts: HashMap<(Id, A), HashMap>, + checked_at: HashMap<(Id, A), f64>, + credits: HashMap<(Id, A, Option, Option), VecDeque<(Actor, f64)>>, + activity: HashMap<(Id, A), f64>, +} + +impl Inner { + fn claim(&mut self, key: ClaimKey) { + if self.claimed.insert(key) { + self.claim_order.push_back(key); + } + while self.claim_order.len() > 2000 { + if let Some(old) = self.claim_order.pop_front() { + self.claimed.remove(&old); + } + } + } + + fn matches(&self, q: &Query, since: f64, e: &AuditLogEntry) -> bool { + if !q.actions.contains(&e.action_type) || self.claimed.contains(&(q.consumer, e.id.get(), q.key_extra())) { + return false; + } + if entry_time(e) < since - SLACK { + return false; // older than the event: it explains something else + } + if q.target.is_some() && target_id(e) != q.target { + return false; + } + q.check.as_ref().is_none_or(|f| f(e)) + } +} + +pub enum Merged { + /// We can't read the audit log. + Unreadable, + /// Nobody else did it (e.g. the author deleted their own message). + Nobody, + By(Actor), +} + +#[derive(Default)] +pub struct AuditFeed { + inner: Mutex, + locks: Mutex, Arc>>>, +} + +fn is_merged(a: A) -> bool { + matches!(a, A::MessageDelete | A::MemberMove | A::MemberDisconnect) +} + +fn merge_key(e: &AuditLogEntry) -> (Option, Option) { + let channel = e.options.as_ref().and_then(|o| o.channel_id).map(|c| c.get()); + let author = if e.action_type == A::MessageDelete { target_id(e) } else { None }; + (channel, author) +} + +fn count_of(e: &AuditLogEntry) -> u64 { + e.options.as_ref().and_then(|o| o.count.as_deref()).and_then(|c| c.parse().ok()).unwrap_or(1).max(1) +} + +impl AuditFeed { + pub fn can_read(state: &State, guild: Id) -> bool { + state.guild_permissions(guild, state.bot_id()).contains(Permissions::VIEW_AUDIT_LOG) + } + + pub fn actor(&self, state: &State, e: Option<&AuditLogEntry>) -> Option { + e.map(|e| Actor::from_entry(e, state.bot_id())) + } + + /// An entry pushed over the gateway. + pub fn push(&self, state: &State, e: AuditLogEntry) { + let Some(guild) = e.guild_id else { return }; + let mut inner = self.inner.lock().unwrap(); + inner.live.insert(guild); + let dq = inner.recent.entry(guild).or_default(); + dq.push_back(e.clone()); + while dq.len() > 200 { + dq.pop_front(); + } + if is_merged(e.action_type) { + // A brand-new merged entry: credit it straight away (later growth is found by polling). + let bucket = (guild, e.action_type); + let now = now(); + let count = count_of(&e); + inner.activity.insert(bucket, now); + inner.counts.entry(bucket).or_default().insert(e.id.get(), count); + let (c, a) = merge_key(&e); + let actor = Actor::from_entry(&e, state.bot_id()); + let queue = inner.credits.entry((guild, e.action_type, c, a)).or_default(); + for _ in 0..count.min(50) { + queue.push_back((actor.clone(), now + CREDIT_TTL)); + } + } + let mut i = 0; + while i < inner.waiters.len() { + let hit = { + let w = &inner.waiters[i]; + w.guild == guild && w.tx.as_ref().is_some_and(|t| !t.is_closed()) && inner.matches(&w.query, w.since, &e) + }; + if hit { + let mut w = inner.waiters.remove(i); + if let Some(tx) = w.tx.take() { + let _ = tx.send(e.clone()); + } + } else { + i += 1; + } + } + } + + pub async fn find(&self, state: &State, guild: Id, q: Query) -> Option { + let e = self.find_entry(state, guild, q).await; + self.actor(state, e.as_ref()) + } + + /// Wait briefly for the audit entry explaining an event that just happened. + pub async fn find_entry(&self, state: &State, guild: Id, q: Query) -> Option { + if !Self::can_read(state, guild) { + return None; + } + let since = q.since.unwrap_or_else(now); + let rx = { + let mut inner = self.inner.lock().unwrap(); + let cutoff = now() - KEEP; + let found = inner + .recent + .get(&guild) + .and_then(|dq| dq.iter().rev().take_while(|e| entry_time(e) >= cutoff).find(|e| inner.matches(&q, since, e)).cloned()); + if let Some(e) = found { + inner.claim((q.consumer, e.id.get(), q.key_extra())); + return Some(e); + } + let (tx, rx) = oneshot::channel(); + inner.waiters.push(Waiter { guild, query: q.clone(), since, tx: Some(tx) }); + rx + }; + let mut found = tokio::time::timeout(Duration::from_secs_f64(q.timeout), rx).await.ok().and_then(Result::ok); + let live = { + let mut inner = self.inner.lock().unwrap(); + inner.waiters.retain(|w| w.tx.as_ref().is_some_and(|t| !t.is_closed())); + inner.live.contains(&guild) + }; + if found.is_none() && !live { + // Nothing pushed from this guild yet (maybe the gateway event isn't reaching us): ask once. + let mut req = state.http.audit_log(guild).limit(10); + if q.actions.len() == 1 { + req = req.action_type(q.actions[0]); + } + if let Ok(r) = req.await { + if let Ok(log) = r.model().await { + let inner = self.inner.lock().unwrap(); + found = log.entries.into_iter().find(|e| inner.matches(&q, since, e)); + } + } + } + if let Some(e) = &found { + self.inner.lock().unwrap().claim((q.consumer, e.id.get(), q.key_extra())); + } + found + } + + // ---- merged entries (message deletes, voice moves/disconnects) -------------------------- + + /// Who caused a merged action. + pub async fn merged(&self, state: &State, guild: Id, action: A, channel: Option, author: Option) -> Merged { + if !Self::can_read(state, guild) { + return Merged::Unreadable; + } + let key = (guild, action, channel, author); + tokio::time::sleep(Duration::from_millis(800)).await; // the audit entry is written around the same time as the event + if let Some(a) = self.take(&key) { + return Merged::By(a); + } + { + let inner = self.inner.lock().unwrap(); + let bucket = (guild, action); + if inner.counts.contains_key(&bucket) && inner.activity.get(&bucket).copied().unwrap_or(0.0) < now() - QUIET { + return Merged::Nobody; // no moderator has done this here lately; don't spend an API call + } + } + let lock = self.locks.lock().unwrap().entry(guild).or_default().clone(); + let _guard = lock.lock().await; + if let Some(a) = self.take(&key) { + return Merged::By(a); + } + self.refresh(state, guild, action, true).await; + match self.take(&key) { + Some(a) => Merged::By(a), + None => Merged::Nobody, + } + } + + pub async fn deleted_by(&self, state: &State, guild: Id, channel: u64, author: u64) -> Merged { + self.merged(state, guild, A::MessageDelete, Some(channel), Some(author)).await + } + + /// Remember the current counters so later increases can be attributed. + pub async fn prime(&self, state: &State, guild: Id, action: A) { + if !Self::can_read(state, guild) || self.inner.lock().unwrap().counts.contains_key(&(guild, action)) { + return; + } + let lock = self.locks.lock().unwrap().entry(guild).or_default().clone(); + let _guard = lock.lock().await; + self.refresh(state, guild, action, false).await; + } + + fn take(&self, key: &(Id, A, Option, Option)) -> Option { + let mut inner = self.inner.lock().unwrap(); + let now = now(); + let queue = inner.credits.get_mut(key)?; + while let Some((actor, expires)) = queue.pop_front() { + if expires >= now { + return Some(actor); + } + } + inner.credits.remove(key); + None + } + + async fn refresh(&self, state: &State, guild: Id, action: A, credit: bool) { + let bucket = (guild, action); + let Ok(r) = state.http.audit_log(guild).action_type(action).limit(25).await else { return }; + let Ok(log) = r.model().await else { return }; + let mut inner = self.inner.lock().unwrap(); + let known = inner.counts.get(&bucket).cloned(); + let last = inner.checked_at.get(&bucket).copied(); + let now = now(); + let mut fresh = HashMap::new(); + for e in &log.entries { + let count = count_of(e); + fresh.insert(e.id.get(), count); + let t = entry_time(e); + let act = inner.activity.entry(bucket).or_insert(0.0); + *act = act.max(t); + if !credit { + continue; + } + let delta = match known.as_ref().and_then(|k| k.get(&e.id.get())) { + Some(old) => count.saturating_sub(*old), + None if t >= last.unwrap_or(now) - 15.0 => count, + None => 0, + }; + if delta > 0 { + inner.activity.insert(bucket, now); + let (c, a) = merge_key(e); + let actor = Actor::from_entry(e, state.bot_id()); + let queue = inner.credits.entry((guild, action, c, a)).or_default(); + for _ in 0..delta.min(50) { + queue.push_back((actor.clone(), now + CREDIT_TTL)); + } + } + } + inner.counts.insert(bucket, fresh); + inner.checked_at.insert(bucket, now); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn via_bot_reason() { + let (id, r) = parse_via_bot("Bob (123456789012345678): being rude").unwrap(); + assert_eq!(id.get(), 123456789012345678); + assert_eq!(r.as_deref(), Some("being rude")); + let (_, r) = parse_via_bot("Bob (123456789012345678)").unwrap(); + assert!(r.is_none()); + let (id, r) = parse_via_bot("Bob (the builder) (123456789012345678): x (y)").unwrap(); + assert_eq!(id.get(), 123456789012345678); + assert_eq!(r.as_deref(), Some("x (y)")); + assert!(parse_via_bot("just a reason").is_none()); + assert!(parse_via_bot("Bob (12345): x").is_none()); + } + + #[test] + fn entry_times_come_from_ids() { + let e = AuditLogEntry { + action_type: A::MemberKick, + changes: vec![], + guild_id: Some(Id::new(1)), + id: Id::new((1_704_067_200_000 - 1_420_070_400_000) << 22), + options: None, + reason: None, + target_id: Some(Id::new(5)), + user_id: Some(Id::new(6)), + }; + assert_eq!(entry_time(&e), 1_704_067_200.0); + assert_eq!(target_id(&e), Some(5)); + } +} diff --git a/src/calc.rs b/src/calc.rs new file mode 100644 index 0000000..305c841 --- /dev/null +++ b/src/calc.rs @@ -0,0 +1,657 @@ +//! The calculator's brain: real expressions (`2^10`, `sqrt(16)`, `sin 30`, `5!`), plus the old +//! `calc 16 sqrt` / `calc 5 add 3` word style. Numbers are exact big integers until a division or a +//! function makes them decimals, like Python's. +use num_bigint::BigInt; +use num_traits::{Signed, ToPrimitive, Zero, One}; +use regex::Regex; +use std::fmt; +use std::sync::OnceLock; + +#[derive(Debug, Clone, PartialEq)] +pub struct CalcError(pub String); + +impl fmt::Display for CalcError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +fn err(s: &str) -> Result { + Err(CalcError(s.to_string())) +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Num { + Int(BigInt), + Float(f64), +} + +impl Num { + fn f(&self) -> f64 { + match self { + Num::Int(i) => i.to_f64().unwrap_or(f64::INFINITY * if i.is_negative() { -1.0 } else { 1.0 }), + Num::Float(f) => *f, + } + } +} + +// ---- normalising what people type ------------------------------------------------------------ + +const NUMBER: &str = r"-?\d+(?:\.\d+)?"; + +fn old_binary(op: &str) -> Option<&'static str> { + Some(match op { + "+" | "add" | "plus" | "addition" => "+", + "-" | "sub" | "subtract" | "minus" => "-", + "*" | "x" | "×" | "mult" | "multiply" | "times" => "*", + "/" | "÷" | "div" | "divide" => "/", + "%" | "mod" | "modulo" => "%", + "^" | "**" | "pow" | "power" | "exp" | "exponent" => "**", + _ => return None, + }) +} + +fn old_unary(op: &str) -> Option<&'static str> { + Some(match op { + "sqrt" | "√" => "sqrt", + "sin" | "sine" => "sin", + "cos" | "cosine" => "cos", + "tan" | "tangent" => "tan", + "abs" | "absolute" => "abs", + "round" => "round", + "ceil" | "ceiling" => "ceil", + "floor" => "floor", + "log" | "logarithm" => "log", + "ln" => "ln", + "factorial" | "!" => "factorial", + _ => return None, + }) +} + +struct Res { + number: Regex, + times: Regex, + root: Regex, + fact: Regex, + func: Regex, + implicit: Regex, + paren: Regex, + comma: Regex, +} + +fn res() -> &'static Res { + static R: OnceLock = OnceLock::new(); + R.get_or_init(|| Res { + number: Regex::new(&format!("^{NUMBER}$")).unwrap(), + times: Regex::new(r"([\d)])\s*x\s*([\d(])").unwrap(), + root: Regex::new(r"√\s*(\d+(?:\.\d+)?|\([^()]*\))").unwrap(), + fact: Regex::new(r"(\d+(?:\.\d+)?|\))\s*!").unwrap(), + func: Regex::new(r"\b(sin|cos|tan|sqrt|ln|log|abs)\s+(-?\d+(?:\.\d+)?)").unwrap(), + implicit: Regex::new(r"(\d)\s*(pi|π|tau|phi|\()").unwrap(), + paren: Regex::new(r"\)\s*(\(|\d)").unwrap(), + comma: Regex::new(r",\s*").unwrap(), + }) +} + +pub fn normalise(expr: &str) -> String { + let r = res(); + let text = expr.trim().trim_matches('`').to_lowercase(); + let words: Vec<&str> = text.split_whitespace().collect(); + if (2..=3).contains(&words.len()) && r.number.is_match(words[0]) { + let op = words[1]; + if words.len() == 2 { + if let Some(f) = old_unary(op) { + return format!("{f}({})", words[0]); + } + } else if r.number.is_match(words[2]) { + if op == "log" || op == "logarithm" { + return format!("log({}, {})", words[0], words[2]); + } + if let Some(b) = old_binary(op) { + return format!("{} {b} {}", words[0], words[2]); + } + } + } + let mut t = text.replace('×', "*").replace('÷', "/").replace('−', "-").replace('^', "**"); + t = r.comma.replace_all(&t, ", ").into_owned(); + t = r.times.replace_all(&t, "$1*$2").into_owned(); // 5 x 3 + t = r.root.replace_all(&t, "sqrt($1)").into_owned(); // √16, √(9+7) + t = r.fact.replace_all(&t, "factorial($1)").into_owned(); // 5! + t = r.func.replace_all(&t, "$1($2)").into_owned(); // sin 30 + t = r.implicit.replace_all(&t, "$1*$2").into_owned(); // 2pi, 3(4) + t = r.paren.replace_all(&t, ")*$1").into_owned(); // (2)(3) + t.replace('π', "pi") +} + +// ---- parsing and evaluating ------------------------------------------------------------------ + +#[derive(Debug, Clone, PartialEq)] +enum Tok { + Num(String), + Name(String), + Op(&'static str), + LParen, + RParen, + Comma, +} + +fn tokenize(s: &str) -> Result, CalcError> { + let c: Vec = s.chars().collect(); + let mut out = vec![]; + let mut i = 0; + while i < c.len() { + let ch = c[i]; + if ch.is_whitespace() { + i += 1; + } else if ch.is_ascii_digit() || (ch == '.' && c.get(i + 1).is_some_and(char::is_ascii_digit)) { + let start = i; + while i < c.len() && (c[i].is_ascii_digit() || c[i] == '.') { + i += 1; + } + if i < c.len() && (c[i] == 'e') && c.get(i + 1).is_some_and(|d| d.is_ascii_digit() || *d == '-' || *d == '+') { + i += 2; + while i < c.len() && c[i].is_ascii_digit() { + i += 1; + } + } + out.push(Tok::Num(c[start..i].iter().collect())); + } else if ch.is_alphabetic() || ch == '_' { + let start = i; + while i < c.len() && (c[i].is_alphanumeric() || c[i] == '_') { + i += 1; + } + out.push(Tok::Name(c[start..i].iter().collect())); + } else { + i += 1; + out.push(match ch { + '(' => Tok::LParen, + ')' => Tok::RParen, + ',' => Tok::Comma, + '+' => Tok::Op("+"), + '-' => Tok::Op("-"), + '%' => Tok::Op("%"), + '*' if c.get(i) == Some(&'*') => { + i += 1; + Tok::Op("**") + } + '*' => Tok::Op("*"), + '/' if c.get(i) == Some(&'/') => { + i += 1; + Tok::Op("//") + } + '/' => Tok::Op("/"), + _ => return err("only numbers, + - * / % ^ and math functions are allowed"), + }); + } + } + Ok(out) +} + +struct Parser { + toks: Vec, + pos: usize, + /// The first name that isn't a constant; reported only if the rest reads fine (like Python's SyntaxError first). + unknown: Option, +} + +impl Parser { + fn peek(&self) -> Option<&Tok> { + self.toks.get(self.pos) + } + fn next(&mut self) -> Option { + self.pos += 1; + self.toks.get(self.pos - 1).cloned() + } + + fn expr(&mut self) -> Result { + let mut left = self.term()?; + while let Some(Tok::Op(op @ ("+" | "-"))) = self.peek().cloned() { + self.pos += 1; + let right = self.term()?; + left = binary(op, left, right)?; + } + Ok(left) + } + + fn term(&mut self) -> Result { + let mut left = self.factor()?; + while let Some(Tok::Op(op @ ("*" | "/" | "//" | "%"))) = self.peek().cloned() { + self.pos += 1; + let right = self.factor()?; + left = binary(op, left, right)?; + } + Ok(left) + } + + fn factor(&mut self) -> Result { + match self.peek() { + Some(Tok::Op("-")) => { + self.pos += 1; + Ok(match self.factor()? { + Num::Int(i) => Num::Int(-i), + Num::Float(f) => Num::Float(-f), + }) + } + Some(Tok::Op("+")) => { + self.pos += 1; + self.factor() + } + _ => self.power(), + } + } + + fn power(&mut self) -> Result { + let base = self.atom()?; + if let Some(Tok::Op("**")) = self.peek() { + self.pos += 1; + let exp = self.factor()?; + return binary("**", base, exp); + } + Ok(base) + } + + fn atom(&mut self) -> Result { + match self.next() { + Some(Tok::Num(n)) => { + if n.chars().all(|c| c.is_ascii_digit()) { + Ok(Num::Int(n.parse().map_err(|_| CalcError("I couldn't read that expression".into()))?)) + } else { + n.parse::().map(Num::Float).map_err(|_| CalcError("I couldn't read that expression".into())) + } + } + Some(Tok::LParen) => { + let v = self.expr()?; + match self.next() { + Some(Tok::RParen) => Ok(v), + _ => err("I couldn't read that expression"), + } + } + Some(Tok::Name(name)) => { + if self.peek() == Some(&Tok::LParen) { + self.pos += 1; + let mut args = vec![]; + if self.peek() != Some(&Tok::RParen) { + loop { + args.push(self.expr()?); + match self.next() { + Some(Tok::Comma) => continue, + Some(Tok::RParen) => break, + _ => return err("I couldn't read that expression"), + } + } + } else { + self.pos += 1; + } + call(&name, args) + } else { + match name.as_str() { + "pi" => Ok(Num::Float(std::f64::consts::PI)), + "e" => Ok(Num::Float(std::f64::consts::E)), + "tau" => Ok(Num::Float(std::f64::consts::TAU)), + "phi" => Ok(Num::Float((1.0 + 5f64.sqrt()) / 2.0)), + _ => { + self.unknown.get_or_insert(name); + Ok(Num::Int(BigInt::zero())) + } + } + } + } + _ => err("I couldn't read that expression"), + } + } +} + +fn is_zero(n: &Num) -> bool { + match n { + Num::Int(i) => i.is_zero(), + Num::Float(f) => *f == 0.0, + } +} + +fn floor_div_mod(a: &BigInt, b: &BigInt) -> (BigInt, BigInt) { + let (mut q, mut r) = (a / b, a % b); + if !r.is_zero() && (r.is_negative() != b.is_negative()) { + q -= 1; + r += b; + } + (q, r) +} + +fn binary(op: &str, l: Num, r: Num) -> Result { + use Num::*; + if op == "**" { + let (lf, rf) = (l.f(), r.f()); + if rf.abs() > 10_000.0 || (lf.abs() > 1.0 && rf * lf.abs().log10() > 4000.0) { + return err("that number is too big"); + } + return Ok(match (&l, &r) { + (Int(a), Int(b)) if !b.is_negative() => Int(num_traits::pow::Pow::pow(a, b.to_u32().unwrap_or(0))), + _ => { + let v = lf.powf(rf); + if v.is_nan() { + return err("the answer isn't a real number"); + } + Float(v) + } + }); + } + if matches!(op, "/" | "//" | "%") && is_zero(&r) { + return err("can't divide by zero"); + } + Ok(match (op, l, r) { + ("+", Int(a), Int(b)) => Int(a + b), + ("-", Int(a), Int(b)) => Int(a - b), + ("*", Int(a), Int(b)) => Int(a * b), + ("//", Int(a), Int(b)) => Int(floor_div_mod(&a, &b).0), + ("%", Int(a), Int(b)) => Int(floor_div_mod(&a, &b).1), + ("/", a, b) => Float(a.f() / b.f()), + ("+", a, b) => Float(a.f() + b.f()), + ("-", a, b) => Float(a.f() - b.f()), + ("*", a, b) => Float(a.f() * b.f()), + ("//", a, b) => Float((a.f() / b.f()).floor()), + ("%", a, b) => { + let (x, y) = (a.f(), b.f()); + Float(x - y * (x / y).floor()) + } + _ => return err("only numbers, + - * / % ^ and math functions are allowed"), + }) +} + +fn log_base(x: f64, base: f64) -> Result { + if x <= 0.0 { + return err("log is only defined for positive numbers"); + } + if base <= 0.0 || base == 1.0 { + return err("the log base must be positive and not 1"); + } + Ok(x.ln() / base.ln()) +} + +/// Python's round(): halves go to the even neighbour. +fn round_half_even(x: f64, digits: i32) -> f64 { + let m = 10f64.powi(digits); + let y = x * m; + let r = y.round(); + let r = if (y - y.trunc()).abs() == 0.5 && r % 2.0 != 0.0 { r - y.signum() } else { r }; + r / m +} + +fn whole(n: &Num) -> Result { + match n { + Num::Int(i) => Ok(i.clone()), + Num::Float(f) if f.fract() == 0.0 => Ok(BigInt::from(*f as i128)), + _ => err("needs a whole number"), + } +} + +fn gcd(a: BigInt, b: BigInt) -> BigInt { + let (mut a, mut b) = (a.abs(), b.abs()); + while !b.is_zero() { + let t = &a % &b; + a = b; + b = t; + } + a +} + +fn call(name: &str, args: Vec) -> Result { + use Num::*; + let one = |args: &[Num]| -> Result { + match args { + [a] => Ok(a.f()), + _ => Err(CalcError(format!("`{name}` takes one number"))), + } + }; + let rad = f64::to_radians; + let float = |v: f64| -> Result { + if v.is_nan() { err("the answer isn't a real number") } else { Ok(Float(v)) } + }; + match name { + "sqrt" => { + let x = one(&args)?; + if x < 0.0 { err("can't take the square root of a negative number") } else { float(x.sqrt()) } + } + "cbrt" => float(one(&args)?.cbrt()), + "abs" => match args.as_slice() { + [Int(i)] => Ok(Int(i.abs())), + _ => float(one(&args)?.abs()), + }, + "log" => match args.as_slice() { + [x] => float(log_base(x.f(), 10.0)?), + [x, b] => float(log_base(x.f(), b.f())?), + _ => err("`log` takes a number and an optional base"), + }, + "ln" => float(log_base(one(&args)?, std::f64::consts::E)?), + "log2" => float(log_base(one(&args)?, 2.0)?), + "log10" => float(log_base(one(&args)?, 10.0)?), + "sin" => float(rad(one(&args)?).sin()), + "cos" => float(rad(one(&args)?).cos()), + "tan" => { + let x = one(&args)?; + if ((x.abs() % 180.0) - 90.0).abs() < 1e-9 { err("tan is undefined at that angle") } else { float(rad(x).tan()) } + } + "asin" => float(one(&args)?.asin().to_degrees()), + "acos" => float(one(&args)?.acos().to_degrees()), + "atan" => float(one(&args)?.atan().to_degrees()), + "round" => match args.as_slice() { + [x] => float(round_half_even(x.f(), 0)), + [x, n] => float(round_half_even(x.f(), n.f() as i32)), + _ => err("`round` takes a number and optional digits"), + }, + "ceil" => Ok(Int(BigInt::from(one(&args)?.ceil() as i128))), + "floor" => Ok(Int(BigInt::from(one(&args)?.floor() as i128))), + "factorial" | "fact" => { + let n = match args.as_slice() { + [a] => whole(a).map_err(|_| CalcError("factorial needs a whole number ≥ 0".into()))?, + _ => return err("`factorial` takes one number"), + }; + if n.is_negative() { + return err("factorial needs a whole number ≥ 0"); + } + if n > BigInt::from(3000) { + return err("that factorial is too big"); + } + let mut acc = BigInt::one(); + for i in 2..=n.to_u32().unwrap_or(0) { + acc *= i; + } + Ok(Int(acc)) + } + "exp" => float(one(&args)?.exp()), + "max" | "min" if !args.is_empty() => { + let pick = args.iter().cloned().reduce(|a, b| { + let less = a.f() < b.f(); + if (name == "max") == less { b } else { a } + }); + pick.ok_or_else(|| CalcError("needs at least one number".into())) + } + "hypot" => match args.as_slice() { + [a, b] => float(a.f().hypot(b.f())), + _ => err("`hypot` takes two numbers"), + }, + "gcd" | "lcm" => match args.as_slice() { + [a, b] => { + let (a, b) = (whole(a)?, whole(b)?); + let g = gcd(a.clone(), b.clone()); + Ok(Int(if name == "gcd" { g } else if g.is_zero() { BigInt::zero() } else { (&a * &b).abs() / g })) + } + _ => Err(CalcError(format!("`{name}` takes two numbers"))), + }, + "rad" => float(one(&args)?.to_radians()), + "deg" => float(one(&args)?.to_degrees()), + _ => Err(CalcError(format!("I don't know the function `{name}`"))), + } +} + +/// (normalised text, value) +pub fn evaluate(expr: &str) -> Result<(String, Num), CalcError> { + let text = normalise(expr); + if text.chars().count() > 300 { + return err("that expression is too long"); + } + let toks = tokenize(&text).map_err(|e| if e.0.starts_with("only") { e } else { CalcError("I couldn't read that expression".into()) })?; + let mut p = Parser { toks, pos: 0, unknown: None }; + let value = p.expr(); + if p.pos != p.toks.len() || (value.is_err() && p.unknown.is_some() && p.pos < p.toks.len()) { + return err("I couldn't read that expression"); + } + let value = value?; + if let Some(name) = p.unknown { + return Err(CalcError(format!("I don't know `{name}`"))); + } + if let Num::Float(f) = &value { + if f.is_infinite() { + return err("that number is too big"); + } + } + Ok((text, value)) +} + +// ---- showing numbers ------------------------------------------------------------------------- + +fn group(int_part: &str) -> String { + crate::converters::thousands(int_part.parse().unwrap_or(0)) +} + +/// Python's `f"{x:.10e}"`: 1.2345678900e+15 +fn sci(v: f64) -> String { + let s = format!("{v:.10e}"); + match s.split_once('e') { + Some((m, e)) => { + let n: i32 = e.parse().unwrap_or(0); + format!("{m}e{}{:02}", if n < 0 { '-' } else { '+' }, n.abs()) + } + None => s, + } +} + +pub fn fmt_number(v: &Num) -> String { + match v { + Num::Float(f) => { + if f.is_nan() { + return "nan".into(); + } + if f.is_infinite() { + return if *f < 0.0 { "-inf".into() } else { "inf".into() }; + } + if f.fract() == 0.0 && f.abs() < 1e15 { + let i = *f as i64; + return format!("{}{}", if i < 0 { "-" } else { "" }, group(&i.abs().to_string())); + } + if f.abs() >= 1e15 || (*f != 0.0 && f.abs() < 1e-6) { + return sci(*f); + } + let s = format!("{:.10}", f.abs()); + let (int, frac) = s.split_once('.').unwrap_or((&s, "")); + let frac = frac.trim_end_matches('0'); + format!("{}{}{}{}", if *f < 0.0 { "-" } else { "" }, group(int), if frac.is_empty() { "" } else { "." }, frac) + } + Num::Int(i) => { + let text = i.abs().to_string(); + let sign = if i.is_negative() { "-" } else { "" }; + if text.len() > 30 { + return format!("{sign}{}.{}e+{} ({} digits)", &text[..1], &text[1..11], text.len() - 1, crate::converters::thousands(text.len() as u64)); + } + // group with commas by hand (can exceed u64) + let mut out = String::new(); + for (n, c) in text.chars().enumerate() { + if n > 0 && (text.len() - n) % 3 == 0 { + out.push(','); + } + out.push(c); + } + format!("{sign}{out}") + } + } +} + +pub fn pretty(text: &str) -> String { + text.replace("**", "^").replace('*', "×").replace('/', "÷").replace("pi", "π") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn calc(s: &str) -> String { + match evaluate(s) { + Ok((_, v)) => fmt_number(&v), + Err(e) => format!("ERR {e}"), + } + } + + #[test] + fn arithmetic_and_precedence() { + assert_eq!(calc("5 * (3 + 2)"), "25"); + assert_eq!(calc("2+3*4"), "14"); + assert_eq!(calc("-2**2"), "-4"); + assert_eq!(calc("2**3**2"), "512"); + assert_eq!(calc("7 // 2"), "3"); + assert_eq!(calc("-7 // 2"), "-4"); + assert_eq!(calc("-7 % 3"), "2"); + assert_eq!(calc("10 / 4"), "2.5"); + assert_eq!(calc("1/3"), "0.3333333333"); + } + + #[test] + fn friendly_syntax() { + assert_eq!(calc("2^10"), "1,024"); + assert_eq!(calc("sqrt(16)"), "4"); + assert_eq!(calc("√16"), "4"); + assert_eq!(calc("sin 30"), "0.5"); + assert_eq!(calc("5!"), "120"); + assert_eq!(calc("5 x 3"), "15"); + assert_eq!(calc("2pi"), "6.2831853072"); + assert_eq!(calc("(2)(3)"), "6"); + assert_eq!(calc("3(4)"), "12"); + assert_eq!(calc("1,000 + 1"), "ERR I couldn't read that expression"); + } + + #[test] + fn old_word_style() { + assert_eq!(calc("16 sqrt"), "4"); + assert_eq!(calc("5 add 3"), "8"); + assert_eq!(calc("100 log 10"), "2"); + assert_eq!(calc("10 times 4"), "40"); + } + + #[test] + fn big_numbers_stay_exact() { + assert_eq!(calc("2^99"), "633,825,300,114,114,700,748,351,602,688"); + assert!(calc("2^200").contains("digits")); + assert_eq!(calc("2^100"), "1.2676506002e+30 (31 digits)"); + assert_eq!(calc("20!"), "2,432,902,008,176,640,000"); + } + + #[test] + fn errors_are_friendly() { + assert_eq!(calc("1/0"), "ERR can't divide by zero"); + assert_eq!(calc("sqrt(-1)"), "ERR can't take the square root of a negative number"); + assert_eq!(calc("log(0)"), "ERR log is only defined for positive numbers"); + assert_eq!(calc("foo"), "ERR I don't know `foo`"); + assert_eq!(calc("bar(1)"), "ERR I don't know the function `bar`"); + assert_eq!(calc("9^99999"), "ERR that number is too big"); + assert_eq!(calc("2 +"), "ERR I couldn't read that expression"); + assert_eq!(calc("import os"), "ERR I couldn't read that expression"); + assert_eq!(calc("tan(90)"), "ERR tan is undefined at that angle"); + } + + #[test] + fn functions() { + assert_eq!(calc("max(1, 5, 3)"), "5"); + assert_eq!(calc("gcd(12, 18)"), "6"); + assert_eq!(calc("lcm(4, 6)"), "12"); + assert_eq!(calc("round(2.5)"), "2"); + assert_eq!(calc("round(3.14159, 2)"), "3.14"); + assert_eq!(calc("floor(2.7)"), "2"); + assert_eq!(calc("abs(-3)"), "3"); + } + + #[test] + fn number_formats() { + assert_eq!(fmt_number(&Num::Float(1e20)), "1.0000000000e+20"); + assert_eq!(fmt_number(&Num::Float(0.0000001)), "1.0000000000e-07"); + assert_eq!(fmt_number(&Num::Float(-1234.5)), "-1,234.5"); + assert_eq!(pretty("2 ** 3 * 4 / 5"), "2 ^ 3 × 4 ÷ 5"); + } +} diff --git a/src/cdn.rs b/src/cdn.rs new file mode 100644 index 0000000..df9fe4e --- /dev/null +++ b/src/cdn.rs @@ -0,0 +1,105 @@ +//! Keep saved Discord attachment links working. +//! +//! Discord CDN links (cdn.discordapp.com/attachments/...) are signed and stop working about a day +//! after they were made (the `ex=` parameter). Configs that store one — a welcome GIF, an ad image — +//! would break. [`fresh_url`] renews the signature through Discord's `/attachments/refresh-urls` +//! endpoint, so nothing has to be re-uploaded, and caches the result until the new link expires. +use crate::state::State; +use reqwest::Url; +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock}; +use std::time::{SystemTime, UNIX_EPOCH}; + +fn cache() -> &'static Mutex> { + static C: OnceLock>> = OnceLock::new(); + C.get_or_init(Default::default) +} + +fn now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) +} + +pub fn is_discord_attachment(url: &str) -> bool { + Url::parse(url).is_ok_and(|u| { + matches!(u.host_str(), Some("cdn.discordapp.com" | "media.discordapp.net")) + && (u.path().starts_with("/attachments/") || u.path().starts_with("/ephemeral-attachments/")) + }) +} + +/// When a signed link stops working (unix time), or None if it isn't signed. +pub fn expires_at(url: &str) -> Option { + let u = Url::parse(url).ok()?; + let (_, ex) = u.query_pairs().find(|(k, _)| k == "ex")?; + u64::from_str_radix(&ex, 16).ok() +} + +fn base(url: &str) -> &str { + url.split('?').next().unwrap_or(url) +} + +/// The same link with a valid signature (or the original if it's fine / not a Discord link). +pub async fn fresh_url(state: &State, url: &str) -> String { + if !is_discord_attachment(url) { + return url.to_string(); + } + let now = now(); + if expires_at(url).is_some_and(|e| e > now + 3600) { + return url.to_string(); + } + if let Some((exp, fresh)) = cache().lock().unwrap().get(base(url)) { + if *exp > now + 3600 { + return fresh.clone(); + } + } + let response = state + .web + .post("https://discord.com/api/v10/attachments/refresh-urls") + .header("Authorization", format!("Bot {}", state.token)) + .json(&serde_json::json!({ "attachment_urls": [url] })) + .send() + .await; + let refreshed = match response { + Ok(r) if r.status().is_success() => r + .json::() + .await + .ok() + .and_then(|v| v["refreshed_urls"][0]["refreshed"].as_str().map(str::to_string)), + Ok(r) => { + tracing::debug!("couldn't refresh {url}: {}", r.status()); + None + } + Err(e) => { + tracing::debug!("couldn't refresh {url}: {e}"); + None + } + }; + let Some(fresh) = refreshed else { return url.to_string() }; + cache().lock().unwrap().insert(base(url).to_string(), (expires_at(&fresh).unwrap_or(now + 86400), fresh.clone())); + fresh +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn detects_and_reads_expiry() { + let u = "https://cdn.discordapp.com/attachments/1/2/a.gif?ex=68744043&is=6872eec3&hm=ab&"; + assert!(is_discord_attachment(u)); + assert_eq!(expires_at(u), Some(0x68744043)); + assert!(!is_discord_attachment("https://example.com/attachments/a.gif")); + assert_eq!(base(u), "https://cdn.discordapp.com/attachments/1/2/a.gif"); + } +} + +#[cfg(test)] +mod net_tests { + /// Run with `cargo test -- --ignored`: proves HTTPS works with the chosen crypto provider. + #[tokio::test] + #[ignore] + async fn https_works() { + rustls::crypto::ring::default_provider().install_default().ok(); + let r = reqwest::Client::new().get("https://example.com").send().await.expect("request"); + assert!(r.status().is_success()); + } +} diff --git a/src/cmd.rs b/src/cmd.rs new file mode 100644 index 0000000..24e0f4f --- /dev/null +++ b/src/cmd.rs @@ -0,0 +1,573 @@ +//! One command framework for both `D!name args` messages and `/name` slash commands. +//! +//! A command declares its options once; a prefix message fills them from the words after the +//! name (the last option takes the rest of the line), a slash command from the typed options. +//! Handlers then read [`Args`] and answer through [`Ctx`], which replies correctly either way. +use crate::converters::find_member; +use crate::error::UserError; +use crate::state::State; +use crate::ui::{self, Card}; +use anyhow::{Context as _, Result}; +use futures::future::BoxFuture; +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use twilight_model::channel::message::{AllowedMentions, Component, MessageFlags}; +use twilight_model::guild::Permissions; +use twilight_model::http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType}; +use twilight_model::id::marker::{ChannelMarker, GuildMarker, InteractionMarker, UserMarker}; +use twilight_model::id::Id; +use twilight_util::permission_calculator::PermissionCalculator; + +#[derive(Clone, Copy, PartialEq)] +pub enum OptKind { + String, + Integer, + Bool, + User, + Role, + Channel, + Attachment, +} + +pub struct Opt { + pub name: &'static str, + pub description: &'static str, + pub kind: OptKind, + pub required: bool, + /// Given as a word after `D!name` (some options only make sense as slash options, and vice versa). + pub in_prefix: bool, + pub in_slash: bool, + pub min: Option, + pub max: Option, + pub choices: &'static [&'static str], + /// Suggestions while typing (see `Command::autocomplete`). + pub autocomplete: bool, +} + +impl Opt { + fn make(name: &'static str, description: &'static str, kind: OptKind, required: bool) -> Self { + Self { name, description, kind, required, in_prefix: true, in_slash: true, min: None, max: None, choices: &[], autocomplete: false } + } + pub fn req(name: &'static str, description: &'static str, kind: OptKind) -> Self { + Self::make(name, description, kind, true) + } + pub fn opt(name: &'static str, description: &'static str, kind: OptKind) -> Self { + Self::make(name, description, kind, false) + } + pub fn slash_only(mut self) -> Self { + self.in_prefix = false; + self + } + pub fn prefix_only(mut self) -> Self { + self.in_slash = false; + self + } + pub fn autocomplete(mut self) -> Self { + self.autocomplete = true; + self + } + pub fn choices(mut self, c: &'static [&'static str]) -> Self { + self.choices = c; + self + } + pub fn range(mut self, min: i64, max: i64) -> Self { + self.min = Some(min); + self.max = Some(max); + self + } +} + +pub type Handler = fn(Arc) -> BoxFuture<'static, Result<()>>; + +/// Suggestions for an option being typed: (state, option name, text so far, who, where) -> (label, value) pairs. +pub type Suggest = fn(Arc, String, String, Option>, Id) -> BoxFuture<'static, Vec<(String, String)>>; + +pub struct Command { + pub name: &'static str, + pub aliases: &'static [&'static str], + pub description: &'static str, + pub category: &'static str, + pub usage: &'static str, + pub options: Vec, + pub slash: bool, + /// The slash command's name when it differs from the text command's (`D!fx` is `/image`). + pub slash_name: Option<&'static str>, + pub guild_only: bool, + /// Bot-owner tools: only listed in help for the owner. + pub hidden: bool, + /// Only the bot's owner may run it. + pub owner_only: bool, + /// Minimum time between two uses by the same person. + pub cooldown: Option, + /// A right-click "Apps" entry on a message instead of a text command. + pub message_menu: bool, + /// A right-click "Apps" entry on a user. + pub user_menu: bool, + /// What the person running it needs (checked for both forms; also hides the slash command from others). + pub perm: Option, + pub handler: Handler, + pub suggest: Option, +} + +impl Command { + pub fn new(name: &'static str, category: &'static str, description: &'static str, handler: Handler) -> Self { + Self { name, aliases: &[], description, category, usage: "", options: vec![], slash: true, slash_name: None, + guild_only: false, hidden: false, owner_only: false, cooldown: None, message_menu: false, user_menu: false, perm: None, handler, suggest: None } + } + pub fn aliases(mut self, a: &'static [&'static str]) -> Self { + self.aliases = a; + self + } + pub fn usage(mut self, u: &'static str) -> Self { + self.usage = u; + self + } + pub fn opt(mut self, o: Opt) -> Self { + self.options.push(o); + self + } + pub fn message_menu(mut self) -> Self { + self.message_menu = true; + self.slash = true; + self + } + pub fn user_menu(mut self) -> Self { + self.user_menu = true; + self.slash = true; + self + } + pub fn suggest(mut self, f: Suggest) -> Self { + self.suggest = Some(f); + self + } + pub fn owner_only(mut self) -> Self { + self.owner_only = true; + self.hidden = true; + self + } + pub fn cooldown(mut self, secs: u64) -> Self { + self.cooldown = Some(std::time::Duration::from_secs(secs)); + self + } + pub fn hidden(mut self) -> Self { + self.hidden = true; + self + } + pub fn prefix_only(mut self) -> Self { + self.slash = false; + self + } + pub fn slash_as(mut self, name: &'static str) -> Self { + self.slash_name = Some(name); + self + } + pub fn guild_only(mut self) -> Self { + self.guild_only = true; + self + } + pub fn perm(mut self, p: Permissions) -> Self { + self.perm = Some(p); + self.guild_only = true; + self + } +} + +/// Option values by name, always as text (parse with the helpers). +#[derive(Default, Clone)] +pub struct Args(pub HashMap); + +impl Args { + pub fn str(&self, name: &str) -> Option<&str> { + self.0.get(name).map(|s| s.trim()).filter(|s| !s.is_empty()) + } + pub fn int(&self, name: &str) -> Option { + self.str(name)?.parse().ok() + } + pub fn bool(&self, name: &str) -> Option { + match self.str(name)?.to_lowercase().as_str() { + "true" | "yes" | "y" | "on" | "1" => Some(true), + "false" | "no" | "n" | "off" | "0" => Some(false), + _ => None, + } + } + /// A role or channel given as `<@&id>`, `<#id>` or a raw id. + pub fn id(&self, name: &str) -> Option { + let s = self.str(name)?.trim_start_matches("<@&").trim_start_matches("<#").trim_end_matches('>'); + s.parse::().ok().filter(|&n| n > 0) + } + /// A user given as `<@id>`, `<@!id>` or a raw id. + pub fn user(&self, name: &str) -> Option> { + let s = self.str(name)?.trim_start_matches("<@").trim_start_matches('!').trim_end_matches('>'); + s.parse::().ok().and_then(Id::new_checked) + } +} + +/// Fill [`Args`] from the words of a prefix command. +pub fn parse_positional(options: &[Opt], rest: &str) -> Args { + let mut map = HashMap::new(); + let mut rest = rest.trim(); + let options: Vec<&Opt> = options.iter().filter(|o| o.in_prefix).collect(); + for (i, opt) in options.iter().enumerate() { + if rest.is_empty() { + break; + } + if i + 1 == options.len() { + map.insert(opt.name.to_string(), rest.to_string()); + break; + } + let (word, tail) = rest.split_once(char::is_whitespace).unwrap_or((rest, "")); + map.insert(opt.name.to_string(), word.to_string()); + rest = tail.trim_start(); + } + Args(map) +} + +pub enum Origin { + Message { channel_id: Id }, + Interaction { + id: Id, + token: String, + permissions: Option, + responded: AtomicBool, + deferred: AtomicBool, + }, +} + +pub struct Ctx { + pub state: Arc, + pub origin: Origin, + /// The name of the command that was run (matters for one handler serving many commands: `D!cat`, `D!hug`…). + pub invoked: &'static str, + pub args: Args, + pub user_id: Id, + pub user_name: String, + pub guild_id: Option>, + pub channel_id: Id, + /// Author of the message this prefix command replies to. + pub reply_to: Option>, + /// The message this prefix command replies to. + pub reply_msg: Option>, + /// The message that held the command (prefix commands). + pub message_id: Option>, + /// The message a right-click menu was used on. + pub target_message: Option, + /// The user a right-click menu was used on. + pub target_user: Option, + /// Files attached to the message (prefix) or given as an option (slash). + pub attachments: Vec, + /// The caller's Discord language, e.g. `es-ES` (slash commands). + pub locale: Option, +} + +/// How high a member's top role is: position first, then the older role wins ties. +pub use crate::state::Rank; + +impl Ctx { + /// A copy of this context with different option values (used when the words were typed in a + /// different order than usual). + pub fn with_args(&self, args: Args) -> Ctx { + Ctx { + state: self.state.clone(), + invoked: self.invoked, + origin: match &self.origin { + Origin::Message { channel_id } => Origin::Message { channel_id: *channel_id }, + Origin::Interaction { id, token, permissions, responded, deferred } => Origin::Interaction { + id: *id, + token: token.clone(), + permissions: *permissions, + responded: AtomicBool::new(responded.load(Ordering::SeqCst)), + deferred: AtomicBool::new(deferred.load(Ordering::SeqCst)), + }, + }, + args, + user_id: self.user_id, + user_name: self.user_name.clone(), + guild_id: self.guild_id, + channel_id: self.channel_id, + reply_to: self.reply_to, + reply_msg: self.reply_msg, + message_id: self.message_id, + target_message: self.target_message.clone(), + target_user: self.target_user.clone(), + attachments: self.attachments.clone(), + locale: self.locale.clone(), + } + } + + pub fn command_message_id(&self) -> Option> { + self.message_id + } + + pub fn is_slash(&self) -> bool { + matches!(self.origin, Origin::Interaction { .. }) + } + + pub fn guild(&self) -> Result> { + self.guild_id.ok_or_else(|| UserError::new("This command only works in servers.").into()) + } + + /// Answer a slash command with "thinking…" now (the work may take longer than Discord's 3 s). + pub async fn defer(&self) -> Result<()> { + if let Origin::Interaction { id, token, responded, deferred, .. } = &self.origin { + if !responded.swap(true, Ordering::SeqCst) { + let response = InteractionResponse { kind: InteractionResponseType::DeferredChannelMessageWithSource, data: None }; + self.state.http.interaction(self.state.app_id()).create_response(*id, token, &response).await?; + deferred.store(true, Ordering::SeqCst); + } + } + Ok(()) + } + + /// Answer a slash command with a private "thinking…" (only the caller sees what follows). + pub async fn defer_private(&self) -> Result<()> { + if let Origin::Interaction { id, token, responded, deferred, .. } = &self.origin { + if !responded.swap(true, Ordering::SeqCst) { + let data = InteractionResponseData { flags: Some(MessageFlags::EPHEMERAL), ..Default::default() }; + let response = InteractionResponse { kind: InteractionResponseType::DeferredChannelMessageWithSource, data: Some(data) }; + self.state.http.interaction(self.state.app_id()).create_response(*id, token, &response).await?; + deferred.store(false, Ordering::SeqCst); // already private: nothing to clear later + } + } + Ok(()) + } + + /// Send a card to wherever the command came from. + pub async fn reply(&self, card: Component) -> Result<()> { + self.send(card, false).await + } + + /// Like `reply`, but private: ephemeral for slash commands, removed after 20 s for messages. + pub async fn reply_private(&self, card: Component) -> Result<()> { + self.send(card, true).await + } + + /// Send a card that refers to an uploaded file as `attachment://`. + pub async fn reply_file(&self, card: Component, name: &str, bytes: Vec) -> Result<()> { + use twilight_model::http::attachment::Attachment; + let http = &self.state.http; + let files = [Attachment::from_bytes(name.to_string(), bytes, 1)]; + let no_pings = AllowedMentions::default(); + match &self.origin { + Origin::Message { channel_id } => { + http.create_message(*channel_id).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]) + .attachments(&files).allowed_mentions(Some(&no_pings)).await.context("sending a card with a file")?; + } + Origin::Interaction { token, .. } => { + self.defer().await?; // a no-op if we already answered + let client = http.interaction(self.state.app_id()); + client.create_followup(token).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]) + .attachments(&files).allowed_mentions(Some(&no_pings)).await.context("sending a follow-up with a file")?; + } + } + Ok(()) + } + + /// Send a card and give back the message (prefix commands only; slash commands answer `None`). + pub async fn reply_message(&self, card: Component) -> Result> { + match &self.origin { + Origin::Message { channel_id } => Ok(Some(self.state.http.create_message(*channel_id).flags(MessageFlags::IS_COMPONENTS_V2) + .components(&[card]).allowed_mentions(Some(&AllowedMentions::default())).await?.model().await?)), + Origin::Interaction { .. } => { + self.reply(card).await?; + Ok(None) + } + } + } + + pub async fn say(&self, text: &str) -> Result<()> { + self.reply(ui::notice(text, None)).await + } + + pub async fn fail(&self, text: &str) -> Result<()> { + self.reply_private(ui::notice(text, Some(ui::RED))).await + } + + async fn send(&self, card: Component, private: bool) -> Result<()> { + let http = &self.state.http; + let mut flags = MessageFlags::IS_COMPONENTS_V2; + let no_pings = AllowedMentions::default(); + match &self.origin { + Origin::Message { channel_id } => { + let sent = http + .create_message(*channel_id) + .flags(flags) + .components(&[card]) + .allowed_mentions(Some(&no_pings)) + .await + .context("sending a card")? + .model() + .await?; + if private { + let http = http.clone(); + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_secs(20)).await; + let _ = http.delete_message(sent.channel_id, sent.id).await; + }); + } + } + Origin::Interaction { id, token, responded, deferred, .. } => { + if private { + flags |= MessageFlags::EPHEMERAL; + } + let client = http.interaction(self.state.app_id()); + if !responded.swap(true, Ordering::SeqCst) { + let data = InteractionResponseData { + components: Some(vec![card]), + flags: Some(flags), + allowed_mentions: Some(no_pings), + ..Default::default() + }; + let response = InteractionResponse { kind: InteractionResponseType::ChannelMessageWithSource, data: Some(data) }; + client.create_response(*id, token, &response).await.context("answering the interaction")?; + } else { + // After a public "thinking…", Discord shows the first follow-up publicly whatever + // the flags say; remove the placeholder first so a private reply really is private. + if private && deferred.swap(false, Ordering::SeqCst) { + let _ = client.delete_response(token).await; + } + client + .create_followup(token) + .flags(flags) + .components(&[card]) + .allowed_mentions(Some(&no_pings)) + .await + .context("sending a follow-up")?; + } + } + } + Ok(()) + } + + // ---- people & permissions (from the cache) ----------------------------------------------- + + /// The person an option points at: the named option, else the replied-to author. + pub fn target(&self, option: &str) -> Result> { + let guild = self.guild()?; + match self.args.str(option) { + Some(text) => find_member(&self.state.cache, guild, text).ok_or_else(|| { + UserError::new(format!("I couldn't find a member called `{}` here.", ui::escape(text))).into() + }), + None => self.reply_to.ok_or_else(|| { + UserError::new("Who? Mention them, give their ID or name, or reply to one of their messages.").into() + }), + } + } + + pub fn is_owner(&self, guild: Id, user: Id) -> bool { + self.state.is_guild_owner(guild, user) + } + + pub fn rank(&self, guild: Id, user: Id) -> Rank { + self.state.rank(guild, user) + } + + /// The moderation safety rules: not yourself, not me, not the owner, roles below yours and mine. + pub fn check_hierarchy(&self, target: Id) -> Result<()> { + let guild = self.guild()?; + let mention = format!("<@{target}>"); + if target == self.user_id { + bail_user!("You can't do that to yourself."); + } + if target == self.state.bot_id() { + bail_user!("I can't do that to myself."); + } + if self.is_owner(guild, target) { + bail_user!("The server owner can't be moderated."); + } + if !self.is_owner(guild, self.user_id) && self.rank(guild, self.user_id) <= self.rank(guild, target) { + bail_user!("{mention} has a role equal to or above yours."); + } + if self.rank(guild, self.state.bot_id()) <= self.rank(guild, target) { + bail_user!("{mention} has a role equal to or above mine — move my role higher."); + } + Ok(()) + } + + /// Does the person who ran this have `needed` here? DMs: false. + pub fn has_permission(&self, needed: Permissions) -> bool { + if let Origin::Interaction { permissions: Some(p), .. } = &self.origin { + return p.contains(needed) || p.contains(Permissions::ADMINISTRATOR); + } + let Some(guild) = self.guild_id else { return false }; + if self.is_owner(guild, self.user_id) { + return true; + } + let cache = &self.state.cache; + let everyone = cache.role(guild.cast()).map_or(Permissions::empty(), |r| r.permissions); + let roles: Vec<_> = cache + .member(guild, self.user_id) + .map(|m| m.roles().iter().filter_map(|&id| cache.role(id).map(|r| (id, r.permissions))).collect()) + .unwrap_or_default(); + let perms = PermissionCalculator::new(guild, self.user_id, everyone, roles.as_slice()).root(); + perms.contains(needed) || perms.contains(Permissions::ADMINISTRATOR) + } + + /// Fail with a permission message unless the person has `needed`. + pub fn require(&self, needed: Permissions, label: &str) -> Result<()> { + if self.has_permission(needed) { + return Ok(()); + } + bail_user!("You are missing required permissions: `{label}`"); + } +} + +/// Name/alias lookup, case-insensitive. +pub struct Registry { + commands: Vec, + index: HashMap, + slash_index: HashMap, +} + +impl Registry { + pub fn new(commands: Vec) -> Self { + let mut index = HashMap::new(); + for (i, c) in commands.iter().enumerate() { + for name in std::iter::once(&c.name).chain(c.aliases.iter()) { + let old = index.insert(name.to_lowercase(), i); + assert!(old.is_none(), "duplicate command name {name}"); + } + } + let slash_index = commands.iter().enumerate().filter(|(_, c)| c.slash).map(|(i, c)| (c.slash_name.unwrap_or(c.name).to_lowercase(), i)).collect(); + Self { commands, index, slash_index } + } + pub fn find(&self, name: &str) -> Option<&Command> { + self.index.get(&name.to_lowercase()).map(|&i| &self.commands[i]) + } + /// The command behind a slash command / menu name Discord sent. + pub fn find_slash(&self, name: &str) -> Option<&Command> { + self.slash_index.get(&name.to_lowercase()).map(|&i| &self.commands[i]) + } + pub fn all(&self) -> &[Command] { + &self.commands + } +} + +pub fn error_card(text: &str) -> Component { + Card::new(Some(ui::RED)).text(text).build() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn opts() -> Vec { + vec![ + Opt::req("user", "", OptKind::User), + Opt::opt("reason", "", OptKind::String), + ] + } + + #[test] + fn last_option_takes_the_rest() { + let a = parse_positional(&opts(), " <@!123> being rude today "); + assert_eq!(a.user("user").map(|i| i.get()), Some(123)); + assert_eq!(a.str("reason"), Some("being rude today")); + } + + #[test] + fn missing_values_stay_unset() { + let a = parse_positional(&opts(), ""); + assert!(a.str("user").is_none()); + } +} diff --git a/src/colors.rs b/src/colors.rs new file mode 100644 index 0000000..b8a3010 --- /dev/null +++ b/src/colors.rs @@ -0,0 +1,272 @@ +//! Card colours taken from the picture a card shows: album covers, avatars, server icons, thumbnails. +//! +//! `accent(state, url, default)` downloads a tiny copy of the image (64 px where the host offers one — +//! the Chromebook's line is slow), picks its most characteristic colour and remembers it, so the same +//! cover or avatar never costs a second download. Anything that goes wrong (no image, timeout, a +//! format that can't be read) gives back `default`. +use crate::state::State; +use regex::Regex; +use std::collections::{HashMap, VecDeque}; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +const CACHE_SIZE: usize = 2000; +const MAX_BYTES: usize = 3 * 1024 * 1024; + +#[derive(Default)] +struct Cache { + map: HashMap>, + order: VecDeque, +} + +fn cache() -> &'static Mutex { + static C: OnceLock> = OnceLock::new(); + C.get_or_init(Default::default) +} + +fn remember(url: &str, colour: Option) { + let mut c = cache().lock().unwrap(); + if c.map.insert(url.to_string(), colour).is_none() { + c.order.push_back(url.to_string()); + } + while c.order.len() > CACHE_SIZE { + if let Some(old) = c.order.pop_front() { + c.map.remove(&old); + } + } +} + +/// The colour already worked out for `url` (no download), else `default`. +pub fn cached(url: Option<&str>, default: u32) -> u32 { + url.and_then(|u| cache().lock().unwrap().map.get(u).copied().flatten()).unwrap_or(default) +} + +/// The same picture at thumbnail size, for hosts that offer one. +pub fn small_variant(url: &str) -> String { + static RES: OnceLock<[Regex; 4]> = OnceLock::new(); + let res = RES.get_or_init(|| { + [ + Regex::new(r"/i/u/(?:\d+x\d+|\d+s|ar0|770x0)/").unwrap(), + Regex::new(r"^https://(cdn\.discordapp\.com|media\.discordapp\.net)/(avatars|icons|banners|guilds|embed)/").unwrap(), + Regex::new(r"(i\.ytimg\.com/vi(?:_webp)?/[^/]+/)\w+\.(jpg|webp)").unwrap(), + Regex::new(r"[?&]size=\d+").unwrap(), + ] + }); + // Last.fm covers: …/i/u/300x300/.jpg → …/i/u/64s/.jpg + let mut url = res[0].replace(url, "/i/u/64s/").into_owned(); + // Discord avatars, icons and banners take ?size= + if res[1].is_match(&url) { + url = if url.contains("size=") { + res[3].replace(&url, |c: ®ex::Captures| format!("{}size=64", &c[0][..1])).into_owned() + } else { + format!("{url}{}size=64", if url.contains('?') { "&" } else { "?" }) + }; + } + // YouTube thumbnails: …/hqdefault.jpg → …/default.jpg (120 px) + res[2].replace(&url, "${1}default.${2}").into_owned() +} + +/// Median cut into at most `n` boxes of pixels; returns (average colour, pixel count) per box. +fn median_cut(mut pixels: Vec<[u8; 3]>, n: usize) -> Vec<([u8; 3], usize)> { + let mut boxes = vec![std::mem::take(&mut pixels)]; + while boxes.len() < n { + // split the box with the widest colour range + let (idx, channel, range) = boxes + .iter() + .enumerate() + .filter(|(_, b)| b.len() > 1) + .map(|(i, b)| { + (0..3) + .map(|c| { + let (lo, hi) = b.iter().fold((255u8, 0u8), |(lo, hi), p| (lo.min(p[c]), hi.max(p[c]))); + (i, c, (hi - lo) as u32 * b.len() as u32) + }) + .max_by_key(|x| x.2) + .unwrap() + }) + .max_by_key(|x| x.2) + .unwrap_or((0, 0, 0)); + if range == 0 { + break; + } + let mut b = boxes.swap_remove(idx); + b.sort_by_key(|p| p[channel]); + let upper = b.split_off(b.len() / 2); + boxes.push(b); + boxes.push(upper); + } + boxes + .into_iter() + .filter(|b| !b.is_empty()) + .map(|b| { + let n = b.len(); + let sum = b.iter().fold([0usize; 3], |mut s, p| { + for c in 0..3 { + s[c] += p[c] as usize; + } + s + }); + ([(sum[0] / n) as u8, (sum[1] / n) as u8, (sum[2] / n) as u8], n) + }) + .collect() +} + +fn rgb_to_hls(r: f32, g: f32, b: f32) -> (f32, f32, f32) { + let (max, min) = (r.max(g).max(b), r.min(g).min(b)); + let l = (max + min) / 2.0; + if max == min { + return (0.0, l, 0.0); + } + let d = max - min; + let s = if l <= 0.5 { d / (max + min) } else { d / (2.0 - max - min) }; + let h = if max == r { (g - b) / d } else if max == g { 2.0 + (b - r) / d } else { 4.0 + (r - g) / d }; + ((h / 6.0).rem_euclid(1.0), l, s) +} + +fn hls_to_rgb(h: f32, l: f32, s: f32) -> (f32, f32, f32) { + if s == 0.0 { + return (l, l, l); + } + let m2 = if l <= 0.5 { l * (1.0 + s) } else { l + s - l * s }; + let m1 = 2.0 * l - m2; + let v = |mut hue: f32| { + hue = hue.rem_euclid(1.0); + if hue < 1.0 / 6.0 { + m1 + (m2 - m1) * hue * 6.0 + } else if hue < 0.5 { + m2 + } else if hue < 2.0 / 3.0 { + m1 + (m2 - m1) * (2.0 / 3.0 - hue) * 6.0 + } else { + m1 + } + }; + (v(h + 1.0 / 3.0), v(h), v(h - 1.0 / 3.0)) +} + +/// The colour that best represents an image: frequent *and* vivid, made readable on Discord. +pub fn pick(data: &[u8]) -> Option { + let img = image::load_from_memory(data).ok()?.thumbnail(64, 64).to_rgba8(); + let pixels: Vec<[u8; 3]> = img.pixels().filter(|p| p[3] > 128).map(|p| [p[0], p[1], p[2]]).collect(); + if pixels.is_empty() { + return None; + } + let total = pixels.len() as f32; + let mut best: Option<((f32, f32, f32), f32)> = None; + for (c, count) in median_cut(pixels, 8) { + let (h, light, sat) = rgb_to_hls(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0); + let mut share = count as f32 / total; + if !(0.1..=0.93).contains(&light) { + share *= 0.15; // near-black or near-white backgrounds rarely "are" the picture + } + let score = share * (0.15 + sat).powf(1.5); + if best.is_none_or(|(_, s)| score > s) { + best = Some(((h, light, sat), score)); + } + } + let ((h, light, sat), _) = best?; + let light = light.clamp(0.42, 0.68); // visible on both dark and light Discord themes + let (r, g, b) = hls_to_rgb(h, light, sat); + let colour = ((r * 255.0).round() as u32) << 16 | ((g * 255.0).round() as u32) << 8 | (b * 255.0).round() as u32; + Some(if colour == 0 { 0x010101 } else { colour }) // 0 would mean "no colour" +} + +/// The colour of the picture at `url` (remembered), or `default`. +pub async fn accent(state: &State, url: Option<&str>, default: u32) -> u32 { + let Some(url) = url else { return default }; + accent_from(state, url, None, MAX_BYTES).await.unwrap_or(default) +} + +/// Like [`accent`] but downloads `sample` (a smaller copy, e.g. a search engine's thumbnail) when given. +pub async fn accent_with_sample(state: &State, url: &str, sample: Option<&str>, default: u32) -> u32 { + accent_from(state, url, sample, MAX_BYTES).await.unwrap_or(default) +} + +async fn accent_from(state: &State, url: &str, sample: Option<&str>, max_bytes: usize) -> Option { + if !(url.starts_with("https://") || url.starts_with("http://")) { + return None; + } + if let Some(found) = cache().lock().unwrap().map.get(url).copied() { + return found; + } + let mut colour = None; + let fetch = async { + let target = sample.map_or_else(|| small_variant(url), str::to_string); + let r = state.web.get(target).timeout(Duration::from_secs(4)).send().await.ok()?; + if !r.status().is_success() || r.content_length().unwrap_or(0) as usize > max_bytes { + return None; + } + let bytes = r.bytes().await.ok()?; + if bytes.len() > max_bytes { + return None; + } + tokio::task::spawn_blocking(move || pick(&bytes)).await.ok().flatten() + }; + if let Ok(found) = tokio::time::timeout(Duration::from_secs(5), fetch).await { + colour = found; + } + remember(url, colour); + colour +} + +/// Work out colours in the background, two at a time, for cards that will be shown later. +/// Each item is a picture and, optionally, a smaller copy to download instead. +pub fn warm(state: &std::sync::Arc, pictures: Vec<(String, Option)>) { + static SLOTS: OnceLock> = OnceLock::new(); + let slots = SLOTS.get_or_init(|| std::sync::Arc::new(tokio::sync::Semaphore::new(2))).clone(); + for (url, sample) in pictures { + if cache().lock().unwrap().map.contains_key(&url) { + continue; + } + let (state, slots) = (state.clone(), slots.clone()); + tokio::spawn(async move { + let _permit = slots.acquire().await; + accent_from(&state, &url, sample.as_deref(), 1024 * 1024).await; + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn small_variants() { + assert_eq!(small_variant("https://lastfm.freetls.fastly.net/i/u/300x300/abc.jpg"), "https://lastfm.freetls.fastly.net/i/u/64s/abc.jpg"); + assert_eq!(small_variant("https://cdn.discordapp.com/avatars/1/x.png?size=1024"), "https://cdn.discordapp.com/avatars/1/x.png?size=64"); + assert_eq!(small_variant("https://cdn.discordapp.com/avatars/1/x.png"), "https://cdn.discordapp.com/avatars/1/x.png?size=64"); + assert_eq!(small_variant("https://i.ytimg.com/vi/abc/hqdefault.jpg"), "https://i.ytimg.com/vi/abc/default.jpg"); + assert_eq!(small_variant("https://example.com/a.png"), "https://example.com/a.png"); + } + + fn png(pixels: &[[u8; 3]], w: u32) -> Vec { + let mut img = image::RgbImage::new(w, pixels.len() as u32 / w); + for (i, p) in pixels.iter().enumerate() { + img.put_pixel(i as u32 % w, i as u32 / w, image::Rgb(*p)); + } + let mut out = std::io::Cursor::new(vec![]); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + } + + #[test] + fn picks_the_vivid_colour_not_the_background() { + // mostly white with a red logo: the red wins, and is made readable + let mut px = vec![[255, 255, 255]; 80]; + px.extend(vec![[220, 20, 20]; 20]); + let c = pick(&png(&px, 10)).unwrap(); + let (r, g, b) = ((c >> 16) as i32, ((c >> 8) & 255) as i32, (c & 255) as i32); + assert!(r > g + 60 && r > b + 60, "expected a red, got #{c:06x}"); + } + + #[test] + fn plain_black_never_returns_zero() { + let c = pick(&png(&vec![[0, 0, 0]; 16], 4)).unwrap(); + assert_ne!(c, 0); + } + + #[test] + fn garbage_gives_none() { + assert!(pick(b"not an image").is_none()); + } +} diff --git a/src/commands/channels.rs b/src/commands/channels.rs new file mode 100644 index 0000000..0669a5f --- /dev/null +++ b/src/commands/channels.rs @@ -0,0 +1,459 @@ +//! Channel tools: lock, media-only, Reddit-style voting, NSFW toggle, and pinning. +//! +//! * `/lock` · `D!lock` / `D!unlock` — only staff can talk; the exact permission overwrites from +//! before are saved and restored on unlock. +//! * `/media` · `D!media lock|unlock` — messages without an image, video, file or link are removed +//! (staff with Manage Messages are exempt). +//! * `/reddit` · `D!reddit` / `D!unreddit` — every message gets upvote/downvote reactions. +//! * `/setnsfw` · `D!nsfw` — toggle a channel's age-restricted flag. +//! * "Pin Message" (right-click a message → Apps) — pin with a card and an Unpin button that keeps +//! working after restarts. +//! +//! State: data/channels.json — {"media": {guild: [channel]}, "voting": {guild: channel}, +//! "locks": {"guild-channel": saved overwrites}}. +use crate::cmd::{Command, Ctx, Opt, OptKind}; +use crate::commands::moderation::audit_reason; +use crate::interact; +use crate::paths; +use crate::state::State; +use crate::storage::JsonStore; +use crate::ui::{button, escape, truncate, Card, BLURPLE, GOLD, GREEN, RED}; +use anyhow::Result; +use futures::FutureExt; +use serde_json::{json, Map, Value}; +use std::sync::{Arc, OnceLock}; +use twilight_http::request::AuditLogReason as _; +use twilight_http::request::channel::reaction::RequestReactionType; +use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_model::channel::message::component::ButtonStyle; +use twilight_model::channel::message::AllowedMentions; +use twilight_model::channel::permission_overwrite::{PermissionOverwrite, PermissionOverwriteType}; +use twilight_model::channel::{ChannelType, Message}; +use twilight_model::guild::Permissions; +use twilight_model::id::marker::{ChannelMarker, GuildMarker, MessageMarker, UserMarker}; +use twilight_model::id::Id; +use twilight_util::permission_calculator::PermissionCalculator; + +const PIN_ICON: &str = "https://media.discordapp.net/attachments/1354263867005599869/1385087466335375400/red-pin-in-pixel-art-style-vector.png"; +const UPVOTE: (u64, &str) = (1388182349820330077, "upvote"); +const DOWNVOTE: (u64, &str) = (1388182361878827049, "downvote"); +const TENOR_GUILD_ID: u64 = 1398984005990219906; // only this server hides Tenor GIFs from people without embed perms + +fn store() -> &'static Arc { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| JsonStore::open(paths::data(&["channels.json"]))) +} + +/// discord.py's permission names <-> the flags, so saved locks stay readable by the Python bot too. +const PERMISSION_NAMES: &[(&str, Permissions)] = &[ + ("create_instant_invite", Permissions::CREATE_INVITE), ("kick_members", Permissions::KICK_MEMBERS), + ("ban_members", Permissions::BAN_MEMBERS), ("administrator", Permissions::ADMINISTRATOR), + ("manage_channels", Permissions::MANAGE_CHANNELS), ("manage_guild", Permissions::MANAGE_GUILD), + ("add_reactions", Permissions::ADD_REACTIONS), ("view_audit_log", Permissions::VIEW_AUDIT_LOG), + ("priority_speaker", Permissions::PRIORITY_SPEAKER), ("stream", Permissions::STREAM), + ("read_messages", Permissions::VIEW_CHANNEL), ("view_channel", Permissions::VIEW_CHANNEL), + ("send_messages", Permissions::SEND_MESSAGES), ("send_tts_messages", Permissions::SEND_TTS_MESSAGES), + ("manage_messages", Permissions::MANAGE_MESSAGES), ("embed_links", Permissions::EMBED_LINKS), + ("attach_files", Permissions::ATTACH_FILES), ("read_message_history", Permissions::READ_MESSAGE_HISTORY), + ("mention_everyone", Permissions::MENTION_EVERYONE), ("external_emojis", Permissions::USE_EXTERNAL_EMOJIS), + ("use_external_emojis", Permissions::USE_EXTERNAL_EMOJIS), ("view_guild_insights", Permissions::VIEW_GUILD_INSIGHTS), + ("connect", Permissions::CONNECT), ("speak", Permissions::SPEAK), ("mute_members", Permissions::MUTE_MEMBERS), + ("deafen_members", Permissions::DEAFEN_MEMBERS), ("move_members", Permissions::MOVE_MEMBERS), + ("use_voice_activation", Permissions::USE_VAD), ("change_nickname", Permissions::CHANGE_NICKNAME), + ("manage_nicknames", Permissions::MANAGE_NICKNAMES), ("manage_roles", Permissions::MANAGE_ROLES), + ("manage_permissions", Permissions::MANAGE_ROLES), ("manage_webhooks", Permissions::MANAGE_WEBHOOKS), + ("manage_expressions", Permissions::MANAGE_GUILD_EXPRESSIONS), ("manage_emojis", Permissions::MANAGE_GUILD_EXPRESSIONS), + ("use_application_commands", Permissions::USE_SLASH_COMMANDS), ("request_to_speak", Permissions::REQUEST_TO_SPEAK), + ("manage_events", Permissions::MANAGE_EVENTS), ("manage_threads", Permissions::MANAGE_THREADS), + ("create_public_threads", Permissions::CREATE_PUBLIC_THREADS), ("create_private_threads", Permissions::CREATE_PRIVATE_THREADS), + ("external_stickers", Permissions::USE_EXTERNAL_STICKERS), ("send_messages_in_threads", Permissions::SEND_MESSAGES_IN_THREADS), + ("use_embedded_activities", Permissions::USE_EMBEDDED_ACTIVITIES), ("moderate_members", Permissions::MODERATE_MEMBERS), + ("use_soundboard", Permissions::USE_SOUNDBOARD), ("create_expressions", Permissions::CREATE_GUILD_EXPRESSIONS), + ("create_events", Permissions::CREATE_EVENTS), ("use_external_sounds", Permissions::USE_EXTERNAL_SOUNDS), + ("send_voice_messages", Permissions::SEND_VOICE_MESSAGES), ("send_polls", Permissions::SEND_POLLS), + ("use_external_apps", Permissions::USE_EXTERNAL_APPS), +]; + +/// {"send_messages": false, "connect": true} <- allow/deny bits (unset permissions are left out). +fn overwrite_to_json(allow: Permissions, deny: Permissions) -> Value { + let mut out = Map::new(); + let mut seen = Permissions::empty(); + for (name, flag) in PERMISSION_NAMES { + if seen.contains(*flag) { + continue; // an alias of one already written + } + if allow.contains(*flag) { + out.insert((*name).to_string(), json!(true)); + seen |= *flag; + } else if deny.contains(*flag) { + out.insert((*name).to_string(), json!(false)); + seen |= *flag; + } + } + Value::Object(out) +} + +fn overwrite_from_json(v: &Value) -> (Permissions, Permissions) { + let (mut allow, mut deny) = (Permissions::empty(), Permissions::empty()); + if let Some(o) = v.as_object() { + for (name, value) in o { + let Some((_, flag)) = PERMISSION_NAMES.iter().find(|(n, _)| n == name) else { continue }; + match value.as_bool() { + Some(true) => allow |= *flag, + Some(false) => deny |= *flag, + None => {} + } + } + } + (allow, deny) +} + +fn has_media(m: &Message) -> bool { + let c = m.content.to_lowercase(); + !m.attachments.is_empty() || !m.embeds.is_empty() || !m.sticker_items.is_empty() || c.contains("http://") || c.contains("https://") +} + +/// What a member can do in a channel (roles + that channel's overwrites). +pub async fn permissions_in(state: &State, guild: Id, channel: Id, user: Id, roles: &[Id]) -> Permissions { + if state.is_guild_owner(guild, user) { + return Permissions::all(); + } + let cache = &state.cache; + let everyone = cache.role(guild.cast()).map_or(Permissions::empty(), |r| r.permissions); + let member_roles: Vec<_> = roles.iter().filter_map(|&id| cache.role(id).map(|r| (id, r.permissions))).collect(); + let calc = PermissionCalculator::new(guild, user, everyone, member_roles.as_slice()); + let fetched = match state.http.channel(channel).await { + Ok(r) => r.model().await.ok(), + Err(_) => None, + }; + let overwrites = fetched.and_then(|c| c.permission_overwrites).unwrap_or_default(); + calc.in_channel(ChannelType::GuildText, &overwrites) +} + +// ---- message hooks ------------------------------------------------------------------------- + +pub async fn on_message(state: Arc, m: Message) { + let Some(guild) = m.guild_id else { return }; + if m.author.bot { + return; + } + let cfg = store().snapshot(); + let channel = m.channel_id; + let media_here = cfg.get("media").and_then(|v| v.get(guild.to_string())).and_then(Value::as_array).is_some_and(|a| a.iter().any(|c| c.as_u64() == Some(channel.get()))); + let vote_here = cfg.get("voting").and_then(|v| v.get(guild.to_string())).and_then(Value::as_u64) == Some(channel.get()); + let tenor = guild.get() == TENOR_GUILD_ID && m.content.to_lowercase().contains("tenor.com"); + if !(media_here || vote_here || tenor) { + return; + } + let roles = m.member.as_ref().map(|x| x.roles.clone()).unwrap_or_default(); + let perms = permissions_in(&state, guild, channel, m.author.id, &roles).await; + if media_here && !has_media(&m) && !perms.contains(Permissions::MANAGE_MESSAGES) { + if state.http.delete_message(channel, m.id).await.is_ok() { + let text = format!("<@{}> this channel is media-only — images, videos, files or links.", m.author.id); + if let Ok(sent) = state.http.create_message(channel).content(&text).allowed_mentions(Some(&AllowedMentions::default())).await { + if let Ok(sent) = sent.model().await { + let http = state.http.clone(); + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_secs(5)).await; + let _ = http.delete_message(sent.channel_id, sent.id).await; + }); + } + } + } + return; + } + use twilight_model::channel::message::MessageType; + if vote_here && matches!(m.kind, MessageType::Regular | MessageType::Reply) { + vote(&state, channel, m.id).await; + } + if tenor && !perms.contains(Permissions::EMBED_LINKS) { + if state.http.delete_message(channel, m.id).await.is_ok() { + let text = format!("**User:** <@{}>\n**GIF:** {}", m.author.id, m.content); + let _ = state.http.create_message(channel).content(&text).allowed_mentions(Some(&AllowedMentions::default())).await; + } + } +} + +async fn vote(state: &State, channel: Id, message: Id) { + for (id, name) in [UPVOTE, DOWNVOTE] { + let emoji = RequestReactionType::Custom { id: Id::new(id), name: Some(name) }; + if state.http.create_reaction(channel, message, &emoji).await.is_err() { + return; + } + } +} + +// ---- commands ------------------------------------------------------------------------------ + +pub fn commands() -> Vec { + vec![ + Command::new("media", "server", "Make a channel media-only (or back to normal)", |c| media(c).boxed()) + .usage(" [#channel]") + .opt(Opt::opt("action", "Lock to media-only, or unlock", OptKind::String).choices(&["lock", "unlock"])) + .opt(Opt::opt("channel", "Defaults to this channel", OptKind::Channel)) + .perm(Permissions::MANAGE_CHANNELS), + Command::new("reddit", "server", "Turn a channel into a Reddit-style voting channel", |c| reddit(c).boxed()) + .usage("[#channel]") + .opt(Opt::opt("channel", "Defaults to this channel", OptKind::Channel)) + .perm(Permissions::ADMINISTRATOR), + Command::new("unreddit", "server", "Turn Reddit-style voting off for this server.", |c| unreddit(c).boxed()) + .prefix_only() + .perm(Permissions::ADMINISTRATOR), + Command::new("setnsfw", "server", "Turn this channel's age-restricted (NSFW) flag on or off", |c| nsfw(c).boxed()) + .aliases(&["nsfw"]) + .perm(Permissions::MANAGE_CHANNELS), + Command::new("lock", "server", "Lock a channel so only staff can talk (or unlock it)", |c| lock(c, false).boxed()) + .usage("[#channel]") + .opt(Opt::opt("unlock", "Unlock instead of lock", OptKind::Bool).slash_only()) + .opt(Opt::opt("channel", "Defaults to this channel", OptKind::Channel)) + .perm(Permissions::MANAGE_CHANNELS), + Command::new("unlock", "server", "Unlock a channel locked with lock.", |c| lock(c, true).boxed()) + .usage("[#channel]") + .prefix_only() + .opt(Opt::opt("channel", "Defaults to this channel", OptKind::Channel)) + .perm(Permissions::MANAGE_CHANNELS), + Command::new("Pin Message", "apps", "Pin a message (needs Manage Messages); the confirmation card has an Unpin button.", |c| pin(c).boxed()) + .message_menu() + .perm(Permissions::MANAGE_MESSAGES), + ] +} + +fn channel_arg(ctx: &Ctx) -> Id { + ctx.args.id("channel").and_then(Id::new_checked).unwrap_or(ctx.channel_id) +} + +async fn media(ctx: Arc) -> Result<()> { + let guild = ctx.guild()?; + let channel = channel_arg(&ctx); + let action = ctx.args.str("action").unwrap_or("lock").to_lowercase(); + let key = guild.to_string(); + let text = match action.as_str() { + "lock" | "on" | "enable" => { + store().update(|s| { + let media = s.entry("media").or_insert_with(|| json!({})); + let list = media.as_object_mut().unwrap().entry(key.clone()).or_insert_with(|| json!([])); + if !list.as_array().unwrap().iter().any(|c| c.as_u64() == Some(channel.get())) { + list.as_array_mut().unwrap().push(json!(channel.get())); + } + }); + format!("🖼️ <#{channel}> is now **media-only** — images, videos, files and links.") + } + "unlock" | "off" | "disable" => { + let was = store().update(|s| { + let list = s.get_mut("media").and_then(|m| m.get_mut(&key)).and_then(Value::as_array_mut); + match list.and_then(|l| l.iter().position(|c| c.as_u64() == Some(channel.get())).map(|p| (l, p))) { + Some((l, p)) => { + l.remove(p); + true + } + None => false, + } + }); + if !was { + bail_user!("<#{channel}> isn't media-only."); + } + format!("💬 <#{channel}> is back to normal.") + } + _ => bail_user!("Use `lock` or `unlock`."), + }; + ctx.reply(Card::new(Some(BLURPLE)).text(&text).build()).await +} + +async fn reddit(ctx: Arc) -> Result<()> { + let guild = ctx.guild()?; + let channel = channel_arg(&ctx); + store().update(|s| { + let v = s.entry("voting").or_insert_with(|| json!({})); + v.as_object_mut().unwrap().insert(guild.to_string(), json!(channel.get())); + }); + ctx.reply(Card::new(Some(BLURPLE)).text(&format!("⬆️ Reddit voting is on in <#{channel}>.")).build()).await?; + let state = ctx.state.clone(); + tokio::spawn(async move { + // the last 50 messages get votes too + if let Ok(r) = state.http.channel_messages(channel).limit(50).await { + if let Ok(msgs) = r.models().await { + for m in msgs.into_iter().filter(|m| !m.author.bot) { + vote(&state, channel, m.id).await; + } + } + } + }); + Ok(()) +} + +async fn unreddit(ctx: Arc) -> Result<()> { + let guild = ctx.guild()?; + let was = store().update(|s| s.get_mut("voting").and_then(Value::as_object_mut).and_then(|v| v.shift_remove(&guild.to_string())).is_some()); + if !was { + bail_user!("Reddit voting isn't on in this server."); + } + ctx.say("✅ Reddit voting is off.").await +} + +async fn nsfw(ctx: Arc) -> Result<()> { + let channel = ctx.state.http.channel(ctx.channel_id).await?.model().await?; + if !matches!(channel.kind, ChannelType::GuildText | ChannelType::GuildAnnouncement | ChannelType::GuildForum | ChannelType::GuildVoice) { + bail_user!("This kind of channel can't be age-restricted."); + } + let now = !channel.nsfw.unwrap_or(false); + ctx.state.http.update_channel(channel.id).nsfw(now).reason(&audit_reason(&ctx, Some("toggle NSFW"))).await?; + ctx.say(&if now { format!("🔞 <#{}> is now **age-restricted**.", channel.id) } else { format!("✅ <#{}> is **no longer** age-restricted.", channel.id) }).await +} + +async fn lock(ctx: Arc, force_unlock: bool) -> Result<()> { + let guild = ctx.guild()?; + let unlock = force_unlock || ctx.args.bool("unlock").unwrap_or(false); + let channel = channel_arg(&ctx); + ctx.defer().await?; + let http = &ctx.state.http; + let key = format!("{guild}-{channel}"); + let reason = audit_reason(&ctx, Some(if unlock { "unlock" } else { "lock" })); + let current = http.channel(channel).await?.model().await?.permission_overwrites.unwrap_or_default(); + let bot = ctx.state.bot_id(); + let saved: Option = store().get_nested("locks", &key); + let card = if unlock { + let Some(saved) = saved else { bail_user!("<#{channel}> isn't locked (or was locked by something else).") }; + // role overwrites go back to exactly what was saved; member overwrites added while locked are + // kept, except the one the lock gave the bot + let mut out: Vec = current + .iter() + .filter(|o| o.kind == PermissionOverwriteType::Member && o.id.get() != bot.get()) + .cloned() + .collect(); + for (target, perms) in saved.as_object().into_iter().flatten() { + let (id, kind) = if target == "everyone" { + (guild.get(), PermissionOverwriteType::Role) + } else if let Some(r) = target.strip_prefix("role_") { + (r.parse().unwrap_or(0), PermissionOverwriteType::Role) + } else if let Some(m) = target.strip_prefix("member_") { + (m.parse().unwrap_or(0), PermissionOverwriteType::Member) + } else { + continue; + }; + if id == 0 { + continue; + } + let (allow, deny) = overwrite_from_json(perms); + out.retain(|o| !(o.id.get() == id && o.kind == kind)); + out.push(PermissionOverwrite { id: Id::new(id), kind, allow, deny }); + } + http.update_channel(channel).permission_overwrites(&out).reason(&reason).await?; + store().update(|s| { + if let Some(l) = s.get_mut("locks").and_then(Value::as_object_mut) { + l.shift_remove(&key); + } + }); + Card::new(Some(GREEN)).text(&format!("🔓 <#{channel}> is unlocked — permissions restored.")).build() + } else { + if saved.is_some() { + bail_user!("<#{channel}> is already locked."); + } + let mut backup = Map::new(); + for o in current.iter().filter(|o| !(o.allow.is_empty() && o.deny.is_empty())) { + let name = match o.kind { + PermissionOverwriteType::Role if o.id.get() == guild.get() => "everyone".to_string(), + PermissionOverwriteType::Role => format!("role_{}", o.id), + PermissionOverwriteType::Member => format!("member_{}", o.id), + _ => continue, + }; + backup.insert(name, overwrite_to_json(o.allow, o.deny)); + } + let mut out = current.clone(); + let lock_bits = Permissions::SEND_MESSAGES | Permissions::SEND_MESSAGES_IN_THREADS | Permissions::CREATE_PUBLIC_THREADS; + let cache = &ctx.state.cache; + let mut targets: Vec> = vec![guild.cast()]; + targets.extend(current.iter().filter(|o| o.kind == PermissionOverwriteType::Role && o.allow.contains(Permissions::SEND_MESSAGES)).map(|o| Id::new(o.id.get()))); + for role in targets { + let staff = cache.role(role).is_some_and(|r| r.permissions.contains(Permissions::ADMINISTRATOR) || r.permissions.contains(Permissions::MANAGE_MESSAGES)); + if staff { + continue; // staff roles keep talking + } + match out.iter_mut().find(|o| o.kind == PermissionOverwriteType::Role && o.id.get() == role.get()) { + Some(o) => { + o.allow.remove(lock_bits); + o.deny |= lock_bits; + } + None => out.push(PermissionOverwrite { id: Id::new(role.get()), kind: PermissionOverwriteType::Role, allow: Permissions::empty(), deny: lock_bits }), + } + } + match out.iter_mut().find(|o| o.kind == PermissionOverwriteType::Member && o.id.get() == bot.get()) { + Some(o) => { + o.allow |= Permissions::SEND_MESSAGES; + o.deny.remove(Permissions::SEND_MESSAGES); + } + None => out.push(PermissionOverwrite { id: Id::new(bot.get()), kind: PermissionOverwriteType::Member, allow: Permissions::SEND_MESSAGES, deny: Permissions::empty() }), + } + http.update_channel(channel).permission_overwrites(&out).reason(&reason).await?; + store().update(|s| { + let l = s.entry("locks").or_insert_with(|| json!({})); + l.as_object_mut().unwrap().insert(key.clone(), Value::Object(backup)); + }); + let prefix = if ctx.is_slash() { "D!".to_string() } else { ctx.state.prefix(Some(guild)) }; + Card::new(Some(GOLD)).text(&format!("🔒 <#{channel}> is locked — only staff can send messages.")).footer(&format!("Unlock with /lock unlock:True or {prefix}unlock")).build() + }; + ctx.reply(card).await +} + +async fn pin(ctx: Arc) -> Result<()> { + let Some(message) = ctx.target_message.clone() else { bail_user!("I couldn't see that message.") }; + ctx.require(Permissions::MANAGE_MESSAGES, "manage messages")?; + ctx.state.http.create_pin(message.channel_id, message.id).reason(&audit_reason(&ctx, Some("Pin Message"))).await?; + let preview = if message.content.is_empty() { "*attachment*".to_string() } else { escape(&truncate(&message.content, 500)) }; + let link = format!("https://discord.com/channels/{}/{}/{}", ctx.guild_id.map_or("@me".to_string(), |g| g.to_string()), message.channel_id, message.id); + let mut card = Card::new(Some(GOLD)).header( + &[&format!("### 📌 Message pinned\n{preview}"), &format!("-# By <@{}> · [Jump to message]({link}) · pinned by <@{}>", message.author.id, ctx.user_id)], + Some(PIN_ICON), + ); + let images: Vec<&str> = message.attachments.iter().filter(|a| a.content_type.as_deref().unwrap_or("").starts_with("image/")).map(|a| a.url.as_str()).take(4).collect(); + if !images.is_empty() { + card = card.gallery(&images); + } + let mut unpin = button(&format!("unpin:{}:{}", message.channel_id, message.id), "Unpin", ButtonStyle::Secondary); + unpin.emoji = Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "📌".into() }); + ctx.reply(card.row(vec![unpin]).build()).await +} + +/// The Unpin button on a pin card: `unpin::`. +pub async fn on_unpin(state: &Arc, i: &Interaction) { + let Some(InteractionData::MessageComponent(d)) = i.data.as_ref() else { return }; + let mut parts = d.custom_id.split(':').skip(1); + let (Some(c), Some(m)) = (parts.next().and_then(|s| s.parse::().ok()).and_then(Id::::new_checked), parts.next().and_then(|s| s.parse::().ok()).and_then(Id::::new_checked)) else { return }; + let Some(user) = i.author() else { return }; + if !interact::can(i, Permissions::MANAGE_MESSAGES) { + return interact::private_text(state, i, "❌ You need **Manage Messages** to unpin.").await; + } + let result = state.http.delete_pin(c, m).reason(&format!("{} ({}): Unpin button", user.name, user.id)).await; + if let Err(e) = result { + let not_found = matches!(e.kind(), twilight_http::error::ErrorType::Response { status, .. } if status.get() == 404); + if !not_found { + return interact::private_text(state, i, &format!("❌ Couldn't unpin: {e}")).await; + } + } + interact::update(state, i, Card::new(Some(RED)).text(&format!("📌 Unpinned by <@{}>.", user.id)).build()).await; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn overwrite_roundtrip_matches_python_format() { + let allow = Permissions::CONNECT; + let deny = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS; + let v = overwrite_to_json(allow, deny); + assert_eq!(v["connect"], json!(true)); + assert_eq!(v["send_messages"], json!(false)); + assert_eq!(overwrite_from_json(&v), (allow, deny)); + // the Python bot's own saved lock reads back correctly + let saved = json!({"send_messages_in_threads": false, "connect": false, "add_reactions": false, "send_messages": false}); + let (a, d) = overwrite_from_json(&saved); + assert!(a.is_empty()); + assert!(d.contains(Permissions::SEND_MESSAGES | Permissions::CONNECT | Permissions::SEND_MESSAGES_IN_THREADS | Permissions::ADD_REACTIONS)); + } + + #[test] + fn aliases_are_written_once() { + let v = overwrite_to_json(Permissions::VIEW_CHANNEL, Permissions::empty()); + assert_eq!(v.as_object().unwrap().len(), 1); + } +} diff --git a/src/commands/embeds.rs b/src/commands/embeds.rs new file mode 100644 index 0000000..d4d8c63 --- /dev/null +++ b/src/commands/embeds.rs @@ -0,0 +1,459 @@ +//! Embed builder: `/embed [channel]` and the **Edit Embed** message menu. +//! +//! The editor is one private message holding a live preview of the embed plus buttons for each part +//! (text, images, author, footer, fields). Every change re-draws the preview instantly. **Send** posts it +//! (or saves the edit), **JSON** shows the embed's JSON and **Import** loads JSON from another tool +//! (Discohook, other bots…). The preview embed *is* the draft, so editors keep working after restarts. +use crate::cmd::{Command, Ctx, Opt, OptKind}; +use crate::converters::parse_colour; +use crate::error::UserError; +use crate::interact; +use crate::state::State; +use crate::ui::{truncate}; +use anyhow::Result; +use futures::FutureExt; +use std::sync::Arc; +use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_model::channel::message::component::{ActionRow, Button, ButtonStyle, Component}; +use twilight_model::channel::message::embed::{Embed, EmbedAuthor, EmbedField, EmbedFooter, EmbedImage, EmbedThumbnail}; +use twilight_model::channel::message::{AllowedMentions, MessageFlags}; +use twilight_model::guild::Permissions; +use twilight_model::http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType}; +use twilight_model::id::marker::{ChannelMarker, MessageMarker}; +use twilight_model::id::Id; +use twilight_model::util::Timestamp; + +const EMPTY: &str = "\u{200b}"; // zero-width space: Discord rejects truly empty field values +const PLACEHOLDER: &str = "*Empty — add something with the buttons below.*"; + +fn clean_url(text: &str) -> Option { + let t = text.trim(); + ((t.starts_with("http://") || t.starts_with("https://")) && !t.contains(char::is_whitespace)).then(|| t.to_string()) +} + +fn blank() -> Embed { + Embed { author: None, color: None, description: None, fields: vec![], footer: None, image: None, kind: "rich".into(), provider: None, thumbnail: None, timestamp: None, title: None, url: None, video: None } +} + +fn is_empty(e: &Embed) -> bool { + e.title.is_none() && e.description.as_deref().is_none_or(|d| d == PLACEHOLDER) && e.fields.is_empty() && e.image.is_none() + && e.thumbnail.is_none() && e.author.is_none() && e.footer.is_none() +} + +fn size(e: &Embed) -> usize { + let c = |s: &Option| s.as_deref().map_or(0, |x| x.chars().count()); + c(&e.title) + c(&e.description) + e.author.as_ref().map_or(0, |a| a.name.chars().count()) + e.footer.as_ref().map_or(0, |f| f.text.chars().count()) + + e.fields.iter().map(|f| f.name.chars().count() + f.value.chars().count()).sum::() +} + +fn problems(e: &Embed) -> Vec { + if is_empty(e) { + return vec!["Add some content first.".into()]; + } + let n = size(e); + if n > 6000 { vec![format!("The embed is {n} characters — Discord allows 6000.")] } else { vec![] } +} + +fn now_ts() -> Timestamp { + let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64); + Timestamp::from_secs(secs).unwrap_or_else(|_| Timestamp::from_secs(0).unwrap()) +} + +/// The embed as it will be posted (`preview` shows a placeholder when empty). +fn build(draft: &Embed, preview: bool) -> Embed { + let mut e = draft.clone(); + e.kind = "rich".into(); + if e.timestamp.is_some() { + e.timestamp = Some(now_ts()); + } + if preview && is_empty(&e) { + e.description = Some(PLACEHOLDER.into()); + } + e +} + +/// Where Send goes: a channel, or an existing message to edit. Carried in the button ids. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Dest { + Channel(Id), + Message(Id, Id), +} + +impl Dest { + fn code(self) -> String { + match self { + Dest::Channel(c) => format!("c{c}"), + Dest::Message(c, m) => format!("m{c}.{m}"), + } + } + fn parse(s: &str) -> Option { + if let Some(c) = s.strip_prefix('c') { + return Some(Dest::Channel(Id::new_checked(c.parse().ok()?)?)); + } + let (c, m) = s.strip_prefix('m')?.split_once('.')?; + Some(Dest::Message(Id::new_checked(c.parse().ok()?)?, Id::new_checked(m.parse().ok()?)?)) + } +} + +fn button(owner: u64, dest: Dest, action: &str, label: &str, emoji: Option<&str>, style: ButtonStyle) -> Component { + Component::Button(Button { + id: None, + custom_id: Some(format!("emb:{owner}:{action}:{}", dest.code())), + disabled: false, + emoji: emoji.map(|e| twilight_model::channel::message::EmojiReactionType::Unicode { name: e.into() }), + label: Some(label.into()), + style, + url: None, + sku_id: None, + }) +} + +fn rows(owner: u64, dest: Dest) -> Vec { + let send_label = if matches!(dest, Dest::Message(..)) { "Save changes" } else { "Send" }; + vec![ + Component::ActionRow(ActionRow { id: None, components: vec![ + button(owner, dest, "basics", "Text", Some("📝"), ButtonStyle::Primary), + button(owner, dest, "media", "Images", Some("🖼️"), ButtonStyle::Primary), + button(owner, dest, "author", "Author", Some("👤"), ButtonStyle::Primary), + button(owner, dest, "footer", "Footer", Some("🔻"), ButtonStyle::Primary), + button(owner, dest, "fields", "Fields", Some("🧱"), ButtonStyle::Primary), + ] }), + Component::ActionRow(ActionRow { id: None, components: vec![ + button(owner, dest, "send", send_label, Some("📨"), ButtonStyle::Success), + button(owner, dest, "json", "JSON", Some("📋"), ButtonStyle::Secondary), + button(owner, dest, "import", "Import", Some("📥"), ButtonStyle::Secondary), + button(owner, dest, "cancel", "Cancel", None, ButtonStyle::Danger), + ] }), + ] +} + +fn header(dest: Dest, guild: Option>, note: Option<&str>, draft: &Embed) -> String { + let where_ = match dest { + Dest::Message(c, m) => format!("editing [this message](https://discord.com/channels/{}/{c}/{m})", guild.map_or("@me".into(), |g| g.to_string())), + Dest::Channel(c) => format!("for <#{c}>"), + }; + let mut lines = vec![format!("**Embed builder** — {where_}. Only you can see this.")]; + lines.extend(note.map(str::to_string)); + lines.extend(problems(draft).into_iter().map(|p| format!("⚠️ {p}"))); + lines.join("\n") +} + +fn response_data(owner: u64, dest: Dest, guild: Option>, draft: &Embed, note: Option<&str>) -> InteractionResponseData { + InteractionResponseData { + content: Some(header(dest, guild, note, draft)), + embeds: Some(vec![build(draft, true)]), + components: Some(rows(owner, dest)), + flags: Some(MessageFlags::EPHEMERAL), + allowed_mentions: Some(AllowedMentions::default()), + ..Default::default() + } +} + +async fn respond(state: &State, i: &Interaction, kind: InteractionResponseType, data: Option) { + let r = state.http.interaction(state.app_id()).create_response(i.id, &i.token, &InteractionResponse { kind, data }).await; + if let Err(e) = r { + tracing::warn!("embed builder response failed: {e}"); + } +} + +// ---- modals -------------------------------------------------------------------------------- + +fn tf(id: &str, label: &str, desc: Option<&str>, value: &str, max: u16, paragraph: bool, placeholder: Option<&str>) -> Component { + interact::text_field(id, label, desc, value, max, paragraph, placeholder) +} + +fn modal_fields(action: &str, e: &Embed) -> Option<(&'static str, Vec)> { + let o = |s: &Option| s.clone().unwrap_or_default(); + Some(match action { + "basics" => ("Title, text and colour", vec![ + tf("title", "Title", None, &o(&e.title), 256, false, None), + tf("url", "Title link", Some("Makes the title clickable"), &o(&e.url), 500, false, Some("https://…")), + tf("desc", "Description", Some("Markdown works: **bold**, [links](https://…), lists"), e.description.as_deref().filter(|d| *d != EMPTY && *d != PLACEHOLDER).unwrap_or(""), 4000, true, None), + tf("colour", "Colour", Some("Hex, a name like 'teal', or rgb(…); empty for none"), &e.color.map(|c| format!("#{c:06X}")).unwrap_or_default(), 30, false, Some("#5865F2, red, rgb(…)")), + ]), + "media" => ("Images", vec![ + tf("image", "Big image", Some("Shown under the text"), e.image.as_ref().map_or("", |i| &i.url), 1000, false, Some("https://…png")), + tf("thumb", "Thumbnail", Some("Small picture in the top-right corner"), e.thumbnail.as_ref().map_or("", |i| &i.url), 1000, false, Some("https://…png")), + ]), + "author" => ("Author line", vec![ + tf("name", "Name", Some("Small text above the title (empty removes it)"), e.author.as_ref().map_or("", |a| &a.name), 256, false, None), + tf("icon", "Icon", None, e.author.as_ref().and_then(|a| a.icon_url.as_deref()).unwrap_or(""), 1000, false, Some("https://…png")), + tf("link", "Link", None, e.author.as_ref().and_then(|a| a.url.as_deref()).unwrap_or(""), 1000, false, Some("https://…")), + ]), + "footer" => ("Footer", vec![ + tf("text", "Footer text", None, e.footer.as_ref().map_or("", |f| &f.text), 2048, false, None), + tf("icon", "Footer icon", None, e.footer.as_ref().and_then(|f| f.icon_url.as_deref()).unwrap_or(""), 1000, false, Some("https://…png")), + interact::select_field("time", "Timestamp", &[("No timestamp", "no"), ("Show when it was sent", "yes")], if e.timestamp.is_some() { "yes" } else { "no" }), + ]), + "fields" => ("Fields", { + let lines: Vec = e.fields.iter().map(|f| format!("{} | {} | {}", f.name, f.value.replace('\n', "\\n"), if f.inline { "inline" } else { "block" })).collect(); + vec![tf("fields", "One field per line", Some("name | value | inline or block — use \\n in a value for a new line (max 25)"), &lines.join("\n"), 4000, true, Some("Rules | Be nice | block\nLevel | 5 | inline"))] + }), + "import" => ("Import embed JSON", vec![ + tf("json", "Embed JSON", Some("An embed object, or a message with an \"embeds\" list"), "", 4000, true, Some("{\"title\": \"Hello\", \"description\": \"…\", \"color\": 5793266}")), + ]), + _ => return None, + }) +} + +/// Apply a submitted modal to the draft; Err = a note to show instead. +fn apply(action: &str, e: &mut Embed, v: &std::collections::HashMap) -> Result, String> { + let get = |k: &str| v.get(k).map(|s| s.trim().to_string()).unwrap_or_default(); + let opt = |k: &str| Some(get(k)).filter(|s| !s.is_empty()); + match action { + "basics" => { + e.title = opt("title"); + e.url = clean_url(&get("url")); + e.description = v.get("desc").map(|d| d.to_string()).filter(|d| !d.is_empty()); + let colour = get("colour"); + if !colour.is_empty() { + match parse_colour(&colour) { + Some(c) => e.color = Some(c), + None => return Err(format!("⚠️ `{colour}` isn't a colour I know — kept the old one.")), + } + } else { + e.color = None; + } + } + "media" => { + let bad = ["image", "thumb"].iter().any(|k| !get(k).is_empty() && clean_url(&get(k)).is_none()); + e.image = clean_url(&get("image")).map(|url| EmbedImage { height: None, proxy_url: None, url, width: None }); + e.thumbnail = clean_url(&get("thumb")).map(|url| EmbedThumbnail { height: None, proxy_url: None, url, width: None }); + if bad { + return Ok(Some("⚠️ Links must start with http:// or https://.".into())); + } + } + "author" => { + e.author = opt("name").map(|name| EmbedAuthor { icon_url: clean_url(&get("icon")), name, proxy_icon_url: None, url: clean_url(&get("link")) }); + } + "footer" => { + let text = get("text"); + e.footer = (!text.is_empty()).then(|| EmbedFooter { icon_url: clean_url(&get("icon")), proxy_icon_url: None, text }); + e.timestamp = (v.get("time").map(String::as_str) == Some("yes")).then(now_ts); + } + "fields" => { + e.fields.clear(); + for line in get("fields").lines().take(25) { + let mut parts: Vec = line.split('|').map(|p| p.trim().to_string()).collect(); + if parts.len() < 2 || parts[0].is_empty() { + continue; + } + let mut inline = false; + if parts.len() >= 3 { + let last = parts[parts.len() - 1].to_lowercase(); + if ["inline", "true", "yes", "i", "block", "false", "no", "b"].contains(&last.as_str()) { + inline = ["inline", "true", "yes", "i"].contains(&last.as_str()); + parts.pop(); + } + } + let value = parts[1..].join(" | ").replace("\\n", "\n"); + e.fields.push(EmbedField { inline, name: parts[0].chars().take(256).collect(), value: if value.is_empty() { EMPTY.into() } else { value.chars().take(1024).collect() } }); + } + } + "import" => { + let mut data: serde_json::Value = serde_json::from_str(&get("json")).map_err(|_| "⚠️ That isn't valid embed JSON.".to_string())?; + if let Some(first) = data.get("embeds").and_then(|a| a.as_array()).and_then(|a| a.first()).cloned() { + data = first; + } + let obj = data.as_object_mut().ok_or("⚠️ That isn't valid embed JSON.")?; + obj.entry("type").or_insert(serde_json::json!("rich")); + obj.entry("fields").or_insert(serde_json::json!([])); + *e = serde_json::from_value(data).map_err(|_| "⚠️ That isn't valid embed JSON.".to_string())?; + return Ok(Some("✅ Imported.".into())); + } + _ => {} + } + Ok(None) +} + +// ---- interactions -------------------------------------------------------------------------- + +pub async fn on_component(state: &Arc, i: &Interaction) { + let (custom_id, modal) = match i.data.as_ref() { + Some(InteractionData::MessageComponent(d)) => (d.custom_id.clone(), None), + Some(InteractionData::ModalSubmit(d)) => (d.custom_id.clone(), Some(interact::modal_values(d))), + _ => return, + }; + let mut p = custom_id.split(':').skip(1); + let (Some(owner), Some(action), Some(dest)) = (p.next().and_then(|s| s.parse::().ok()), p.next(), p.next().and_then(Dest::parse)) else { return }; + let Some(user) = i.author() else { return }; + if user.id.get() != owner { + return; + } + let Some(msg) = i.message.as_ref() else { return }; + let mut draft = msg.embeds.first().cloned().map(|mut e| { + if e.description.as_deref() == Some(PLACEHOLDER) { + e.description = None; + } + e + }).unwrap_or_else(blank); + + if let Some(values) = &modal { + let note = match apply(action, &mut draft, values) { + Ok(n) => n, + Err(n) => Some(n), + }; + let data = response_data(owner, dest, i.guild_id, &draft, note.as_deref()); + return respond(state, i, InteractionResponseType::UpdateMessage, Some(data)).await; + } + match action { + "basics" | "media" | "author" | "footer" | "fields" | "import" => { + if let Some((title, fields)) = modal_fields(action, &draft) { + interact::modal(state, i, &custom_id, title, fields).await; + } + } + "cancel" => { + let data = InteractionResponseData { content: Some("Embed builder closed.".into()), embeds: Some(vec![]), components: Some(vec![]), flags: Some(MessageFlags::EPHEMERAL), ..Default::default() }; + respond(state, i, InteractionResponseType::UpdateMessage, Some(data)).await; + } + "json" => { + let text = serde_json::to_string_pretty(&build(&draft, false)).unwrap_or_default(); + if text.chars().count() > 1900 { + // too long for a message: send it as a file + respond(state, i, InteractionResponseType::DeferredChannelMessageWithSource, Some(InteractionResponseData { flags: Some(MessageFlags::EPHEMERAL), ..Default::default() })).await; + let file = [twilight_model::http::attachment::Attachment::from_bytes("embed.json".into(), text.into_bytes(), 1)]; + let _ = state.http.interaction(state.app_id()).create_followup(&i.token).flags(MessageFlags::EPHEMERAL).attachments(&file).await; + } else { + let data = InteractionResponseData { content: Some(format!("```json\n{text}\n```")), flags: Some(MessageFlags::EPHEMERAL), ..Default::default() }; + respond(state, i, InteractionResponseType::ChannelMessageWithSource, Some(data)).await; + } + } + "send" => { + if !problems(&draft).is_empty() { + let data = response_data(owner, dest, i.guild_id, &draft, Some("Fix these first:")); + return respond(state, i, InteractionResponseType::UpdateMessage, Some(data)).await; + } + let embed = build(&draft, false); + let result = match dest { + Dest::Message(c, m) => state.http.update_message(c, m).embeds(Some(&[embed.clone()])).await.map(|_| format!("✅ Saved — [jump to it](https://discord.com/channels/{}/{c}/{m})", i.guild_id.map_or("@me".into(), |g| g.to_string()))), + Dest::Channel(c) => match state.http.create_message(c).embeds(&[embed.clone()]).await { + Ok(r) => match r.model().await { + Ok(m) => Ok(format!("✅ Sent — [jump to it](https://discord.com/channels/{}/{c}/{})", i.guild_id.map_or("@me".into(), |g| g.to_string()), m.id)), + Err(_) => Ok("✅ Sent.".to_string()), + }, + Err(e) => Err(e), + }, + }; + match result { + Ok(done) => { + let data = InteractionResponseData { content: Some(done), embeds: Some(vec![embed]), components: Some(vec![]), flags: Some(MessageFlags::EPHEMERAL), ..Default::default() }; + respond(state, i, InteractionResponseType::UpdateMessage, Some(data)).await; + } + Err(e) => { + let forbidden = matches!(e.kind(), twilight_http::error::ErrorType::Response { status, .. } if status.get() == 403); + let note = if forbidden { "❌ I can't send messages there.".to_string() } else { format!("❌ Discord refused it: {}", truncate(&e.to_string(), 300)) }; + let data = response_data(owner, dest, i.guild_id, &draft, Some(¬e)); + respond(state, i, InteractionResponseType::UpdateMessage, Some(data)).await; + } + } + } + _ => {} + } +} + +// ---- commands ------------------------------------------------------------------------------ + +async fn embed_cmd(ctx: Arc) -> Result<()> { + let target = ctx.args.id("channel").and_then(Id::new_checked).unwrap_or(ctx.channel_id); + if let Some(guild) = ctx.guild_id { + let roles = ctx.state.cache.member(guild, ctx.user_id).map(|m| m.roles().to_vec()).unwrap_or_default(); + let perms = super::channels::permissions_in(&ctx.state, guild, target, ctx.user_id, &roles).await; + if !(perms.contains(Permissions::SEND_MESSAGES) && perms.contains(Permissions::EMBED_LINKS)) { + return Err(UserError::new(format!("You can't post embeds in <#{target}>.")).into()); + } + } + let draft = blank(); + send_editor(&ctx, Dest::Channel(target), &draft).await +} + +async fn edit_menu(ctx: Arc) -> Result<()> { + let Some(m) = ctx.target_message.clone() else { return Err(UserError::new("I couldn't see that message.").into()) }; + if m.author.id != ctx.state.bot_id() || m.embeds.is_empty() { + return Err(UserError::new("I can only edit embeds that I posted.").into()); + } + ctx.require(Permissions::MANAGE_MESSAGES, "manage messages")?; + let draft = m.embeds[0].clone(); + send_editor(&ctx, Dest::Message(m.channel_id, m.id), &draft).await +} + +async fn send_editor(ctx: &Ctx, dest: Dest, draft: &Embed) -> Result<()> { + let crate::cmd::Origin::Interaction { id, token, responded, .. } = &ctx.origin else { + return Err(UserError::new("Use the slash command for this one.").into()); + }; + responded.store(true, std::sync::atomic::Ordering::SeqCst); + let data = response_data(ctx.user_id.get(), dest, ctx.guild_id, draft, None); + let response = InteractionResponse { kind: InteractionResponseType::ChannelMessageWithSource, data: Some(data) }; + ctx.state.http.interaction(ctx.state.app_id()).create_response(*id, token, &response).await?; + Ok(()) +} + +pub fn commands() -> Vec { + vec![ + Command::new("embed", "utility", "Build an embed with a live preview, then post it", |c| embed_cmd(c).boxed()) + .opt(Opt::opt("channel", "Where to post it (default: here)", OptKind::Channel)), + Command::new("Edit Embed", "apps", "Edit an embed Dezio posted, with the live-preview builder.", |c| edit_menu(c).boxed()) + .message_menu().perm(Permissions::MANAGE_MESSAGES), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + fn vals(pairs: &[(&str, &str)]) -> HashMap { + pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect() + } + + #[test] + fn destinations_round_trip() { + for d in [Dest::Channel(Id::new(123456789012345678)), Dest::Message(Id::new(111111111111111111), Id::new(222222222222222222))] { + assert_eq!(Dest::parse(&d.code()), Some(d)); + } + assert!(Dest::parse("x1").is_none()); + } + + #[test] + fn text_colour_and_empty_checks() { + let mut e = blank(); + assert!(is_empty(&e) && !problems(&e).is_empty()); + assert_eq!(apply("basics", &mut e, &vals(&[("title", "Hi"), ("desc", "Body"), ("colour", "teal"), ("url", "nope")])).unwrap(), None); + assert_eq!((e.title.as_deref(), e.color, e.url.clone()), (Some("Hi"), Some(0x008080), None)); + assert!(apply("basics", &mut e, &vals(&[("title", "Hi"), ("colour", "blorp")])).is_err()); + assert!(problems(&e).is_empty()); + } + + #[test] + fn fields_parse_like_python() { + let mut e = blank(); + apply("fields", &mut e, &vals(&[("fields", "Rules | Be nice | block\nLevel | 5 | inline\nSingle | a | b | c\nbroken\n | x")])).unwrap(); + let got: Vec<(&str, &str, bool)> = e.fields.iter().map(|f| (f.name.as_str(), f.value.as_str(), f.inline)).collect(); + assert_eq!(got, vec![("Rules", "Be nice", false), ("Level", "5", true), ("Single", "a | b | c", false)]); + } + + #[test] + fn footer_and_timestamp() { + let mut e = blank(); + apply("footer", &mut e, &vals(&[("text", "bye"), ("time", "yes")])).unwrap(); + assert!(e.footer.is_some() && e.timestamp.is_some()); + apply("footer", &mut e, &vals(&[("text", ""), ("time", "no")])).unwrap(); + assert!(e.footer.is_none() && e.timestamp.is_none()); + } + + #[test] + fn json_import_accepts_embeds_lists() { + let mut e = blank(); + let note = apply("import", &mut e, &vals(&[("json", r#"{"embeds": [{"title": "From Discohook", "color": 5793266, "fields": [{"name": "a", "value": "b"}]}]}"#)])).unwrap(); + assert_eq!(note.as_deref(), Some("✅ Imported.")); + assert_eq!((e.title.as_deref(), e.color, e.fields.len()), (Some("From Discohook"), Some(5793266), 1)); + assert!(apply("import", &mut e, &vals(&[("json", "[1,2]")])).is_err()); + assert!(apply("import", &mut e, &vals(&[("json", "not json")])).is_err()); + } + + #[test] + fn size_limit_is_checked() { + let mut e = blank(); + e.description = Some("x".repeat(6001)); + assert!(problems(&e)[0].contains("6000")); + } +} diff --git a/src/commands/fun/actions.rs b/src/commands/fun/actions.rs new file mode 100644 index 0000000..02036a9 --- /dev/null +++ b/src/commands/fun/actions.rs @@ -0,0 +1,484 @@ +//! Anime GIF actions: `D!hug @someone`, `/interact`, and the age-restricted `/erp` set. +//! +//! Every action is also its own text command (`D!pat`, `D!slap` …). The target can be a mention, a name, or +//! the author of the message you reply to. Actions aimed at someone get "do it back" and "Reject" buttons +//! that only they can press (Reject = turn it down with a slap, kick or punch GIF). GIFs come from +//! nekos.best (waifu.pics as a backup); the NSFW set only works in age-restricted channels. Text and +//! sources live in assets/data/actions.json. Actions with a `count` entry keep a running tally +//! ("Alice has hugged Bob 5 times · Bob has been hugged 23 times") in data/interactions.json. +use super::super::info::display_name_of; +use crate::cmd::{Command, Ctx, Opt, OptKind}; +use crate::converters::find_member; +use crate::state::State; +use crate::storage::JsonStore; +use crate::ui::{button, escape, Card}; +use crate::{colors, interact, paths}; +use anyhow::Result; +use futures::FutureExt; +use rand::RngExt as _; +use serde_json::{json, Value}; +use std::sync::{Arc, OnceLock}; +use std::time::Duration; +use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_model::channel::message::component::{ButtonStyle, Component}; +use twilight_model::channel::message::{AllowedMentions, MessageFlags}; +use twilight_model::id::marker::UserMarker; +use twilight_model::id::Id; + +const WAIFU_PICS_SFW: [&str; 22] = [ + "hug", "kiss", "pat", "cuddle", "slap", "bite", "blush", "smile", "wave", "highfive", "nom", "poke", "dance", "cry", "smug", "wink", "happy", "yeet", "kick", "handhold", "bonk", "lick", +]; +const REJECTIONS: [(&str, &str); 3] = [ + ("slap", "{target} rejects {user}'s {action} and slaps them away ¬_¬"), + ("kick", "{target} rejects {user}'s {action} and kicks them away >:3c"), + ("punch", "{target} rejects {user}'s {action} with a punch >-<"), +]; + +fn data() -> &'static Value { + static D: OnceLock = OnceLock::new(); + D.get_or_init(|| crate::storage::read_json(&paths::asset(&["data", "actions.json"])).unwrap_or(Value::Null)) +} + +fn set(nsfw: bool) -> &'static serde_json::Map { + static EMPTY: OnceLock> = OnceLock::new(); + data()[if nsfw { "nsfw" } else { "sfw" }].as_object().unwrap_or_else(|| EMPTY.get_or_init(Default::default)) +} + +fn tallies() -> &'static Arc { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| JsonStore::open(paths::data(&["interactions.json"]))) +} + +fn is_nsfw_channel(ctx: &Ctx) -> bool { + ctx.guild_id.is_none() || ctx.state.cache.channel(ctx.channel_id).is_some_and(|c| c.nsfw.unwrap_or(false)) +} + +// ---- GIFs -------------------------------------------------------------------------------------------------- + +async fn json_of(state: &State, url: &str) -> Option { + let r = state.web.get(url).timeout(Duration::from_secs(8)).send().await.ok()?; + if !r.status().is_success() { + return None; + } + r.json().await.ok() +} + +/// (gif url, anime name) +pub async fn gif(state: &State, action: &str, nsfw: bool) -> (Option, Option) { + let entry = &set(nsfw)[action]; + if nsfw { + for api in entry["apis"].as_array().into_iter().flatten().filter_map(Value::as_str) { + if let Some(d) = json_of(state, api).await { + if let Some(u) = ["link", "url", "message"].iter().find_map(|k| d[*k].as_str()) { + return (Some(u.to_string()), None); + } + } + } + return (None, None); + } + if let Some(gifs) = entry["gifs"].as_array().filter(|g| !g.is_empty()) { + return (gifs[rand::rng().random_range(0..gifs.len())].as_str().map(str::to_string), None); + } + if let Some(d) = json_of(state, &format!("https://nekos.best/api/v2/{action}")).await { + if let Some(r) = d["results"].get(0) { + return (r["url"].as_str().map(str::to_string), r["anime_name"].as_str().map(str::to_string)); + } + } + if WAIFU_PICS_SFW.contains(&action) { + if let Some(d) = json_of(state, &format!("https://api.waifu.pics/sfw/{action}")).await { + if let Some(u) = d["url"].as_str() { + return (Some(u.to_string()), None); + } + } + } + (None, None) +} + +// ---- tallies ----------------------------------------------------------------------------------------------------- + +fn times(n: u64) -> String { + match n { + 1 => "**once**".into(), + 2 => "**twice**".into(), + n => format!("**{}** times", crate::converters::thousands(n)), + } +} + +/// +1 in `bucket → action → key`. +fn bump(bucket: &str, action: &str, key: &str) -> u64 { + tallies().update(|all| { + let slot = all.entry(bucket.to_string()).or_insert_with(|| json!({})).as_object_mut().unwrap().entry(action.to_string()).or_insert_with(|| json!({})).as_object_mut().unwrap(); + let n = slot.get(key).and_then(Value::as_u64).unwrap_or(0) + 1; + slot.insert(key.to_string(), json!(n)); + n + }) +} + +fn count_of(bucket: &str, action: &str, key: &str) -> u64 { + tallies().get(bucket).and_then(|b| b[action][key].as_u64()).unwrap_or(0) +} + +/// Count this action and return the line shown under the card (None when it isn't counted). +fn tally(action: &str, nsfw: bool, user: (Id, &str), target: Option<(Id, &str)>) -> Option { + let rule = &set(nsfw)[action]["count"]; + if !rule.is_object() { + return None; + } + let target = target.filter(|t| t.0 != user.0); + let fill = |template: &str, n: u64| template.replace("{user}", &escape(user.1)).replace("{target}", &target.map(|t| escape(t.1)).unwrap_or_default()).replace("{n}", ×(n)); + let mut parts = Vec::new(); + if let (Some(t), Some(pair)) = (target, rule["pair"].as_str()) { + let mut ids = (user.0.get(), t.0.get()); + if rule["mutual"].as_bool() == Some(true) && ids.0 > ids.1 { + ids = (ids.1, ids.0); + } + parts.push(fill(pair, bump("pair", action, &format!("{}:{}", ids.0, ids.1)))); + bump("gave", action, &user.0.get().to_string()); + let got = bump("got", action, &t.0.get().to_string()); + if let (Some(total), true) = (rule["total"].as_str(), got > 1) { + parts.push(fill(total, got)); + } + } else if let (None, Some(solo)) = (target, rule["solo"].as_str()) { + parts.push(fill(solo, bump("solo", action, &user.0.get().to_string()))); + } + if parts.is_empty() { + return None; + } + Some(parts.join(" · ")) +} + +fn stats(user: u64, nsfw: bool) -> Vec<(String, u64, u64)> { + let uid = user.to_string(); + let mut out: Vec<_> = set(nsfw) + .iter() + .filter(|(_, e)| e["count"].is_object()) + .filter_map(|(a, _)| { + let given = count_of("gave", a, &uid) + count_of("solo", a, &uid); + let got = count_of("got", a, &uid); + (given > 0 || got > 0).then(|| (a.clone(), given, got)) + }) + .collect(); + out.sort_by_key(|(_, g, r)| std::cmp::Reverse(g + r)); + out +} + +fn top_partners(user: u64, nsfw: bool, limit: usize) -> Vec<(u64, u64)> { + let uid = user.to_string(); + let mut together: std::collections::HashMap = Default::default(); + if let Some(pairs) = tallies().get("pair") { + for (action, m) in pairs.as_object().into_iter().flatten() { + if !set(nsfw).contains_key(action) { + continue; + } + for (key, n) in m.as_object().into_iter().flatten() { + let Some((a, b)) = key.split_once(':') else { continue }; + if (a == uid || b == uid) && a != b { + let other: u64 = if a == uid { b } else { a }.parse().unwrap_or(0); + *together.entry(other).or_default() += n.as_u64().unwrap_or(0); + } + } + } + } + let mut v: Vec<_> = together.into_iter().collect(); + v.sort_by_key(|(_, n)| std::cmp::Reverse(*n)); + v.truncate(limit); + v +} + +fn rejections(user: u64) -> (u64, u64) { + let uid = user.to_string(); + let (mut gave, mut got) = (0, 0); + if let Some(r) = tallies().get("reject") { + for (key, n) in r["all"].as_object().into_iter().flatten() { + let Some((a, b)) = key.split_once(':') else { continue }; + let n = n.as_u64().unwrap_or(0); + if a == uid { + gave += n; + } + if b == uid { + got += n; + } + } + } + (gave, got) +} + +// ---- cards -------------------------------------------------------------------------------------------------------- + +async fn build(state: &State, action: &str, nsfw: bool, user: (Id, String), target: Option<(Id, String)>, bot_target: bool) -> Component { + let entry = &set(nsfw)[action]; + let template = entry["text"].as_str().unwrap_or(""); + let target_name = target.as_ref().map_or(if nsfw { "themselves" } else { "someone" }.to_string(), |t| t.1.clone()); + let text = template.replace("{user}", &user.1).replace("{target}", &target_name); + let (url, anime) = gif(state, action, nsfw).await; + let default = rand::rng().random_range(0..0xFFFFFFu32); + let accent = colors::accent(state, url.as_deref(), default).await; + let mut card = Card::new(Some(accent)).text(&format!("### {}", escape(&text))); + match &url { + Some(u) => card = card.gallery(&[u]), + None => card = card.footer("The GIF service is down right now — the text will have to do."), + } + if let Some(line) = tally(action, nsfw, (user.0, &user.1), target.as_ref().map(|t| (t.0, t.1.as_str()))) { + card = card.footer(&line); + } + if let Some(a) = anime { + card = card.footer(&format!("Anime: {}", escape(&a))); + } + if let Some(t) = &target { + if t.0 != user.0 && !bot_target && template.contains("{target}") { + let id = |k: &str| format!("act:{k}:{action}:{}:{}:{}", nsfw as u8, user.0, t.0); + let mut back = button(&id("back"), &format!("{action} back"), ButtonStyle::Primary); + back.emoji = Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "↩️".into() }); + let mut reject = button(&id("rej"), "Reject", ButtonStyle::Danger); + reject.emoji = Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "✋".into() }); + card = card.row(vec![back, reject]); + } + } + card.build() +} + +async fn build_reject(state: &State, action: &str, rejecter: (Id, String), user: (Id, String)) -> Component { + let (hit, wording) = REJECTIONS[rand::rng().random_range(0..REJECTIONS.len())]; + let text = wording.replace("{target}", &rejecter.1).replace("{user}", &user.1).replace("{action}", action); + let (url, anime) = gif(state, hit, false).await; + let accent = colors::accent(state, url.as_deref(), 0xE03131).await; + let mut card = Card::new(Some(accent)).text(&format!("### {}", escape(&text))); + match &url { + Some(u) => card = card.gallery(&[u]), + None => card = card.footer("The GIF service is down right now — the text will have to do."), + } + let n = bump("reject", "all", &format!("{}:{}", rejecter.0, user.0)); + card = card.footer(&format!("{} has rejected {} {}", escape(&rejecter.1), escape(&user.1), times(n))); + if let Some(a) = anime { + card = card.footer(&format!("Anime: {}", escape(&a))); + } + card.build() +} + +async fn stats_card(state: &State, user: Id, name: &str, nsfw: bool) -> Component { + let avatar = super::super::media::avatar(state, user, 128).await; + let accent = colors::accent(state, Some(&avatar), 0xF47FFF).await; + let mut card = Card::new(Some(accent)).header(&[&format!("### {}Interactions · {}", if nsfw { "🔞 " } else { "" }, escape(name))], Some(&avatar)); + let data = stats(user.get(), nsfw); + let (rej, was) = if nsfw { (0, 0) } else { rejections(user.get()) }; + if data.is_empty() && rej == 0 && was == 0 { + return card.text("Nothing counted yet — try `D!hug @someone`.").build(); + } + let mut lines: Vec = data.iter().map(|(a, g, r)| format!("`{a:<9}` given **{}** · received **{}**", crate::converters::thousands(*g), crate::converters::thousands(*r))).collect(); + if rej > 0 || was > 0 { + lines.push(format!("`{:<9}` rejected others **{rej}** · got rejected **{was}**", "✋ reject")); + } + card = card.text(&lines.join("\n")); + let partners = top_partners(user.get(), nsfw, 3); + if !partners.is_empty() { + card = card.footer(&format!("Most with: {}", partners.iter().map(|(u, n)| format!("<@{u}> ({n})")).collect::>().join(" · "))); + } + card.build() +} + +// ---- commands --------------------------------------------------------------------------------------------------------- + +async fn resolve_target(ctx: &Ctx, option: &str) -> Option> { + if ctx.is_slash() { + return ctx.args.user(option); + } + let who = ctx.args.str(option).unwrap_or(""); + if !who.is_empty() { + if let Some(g) = ctx.guild_id { + if let Some(u) = find_member(&ctx.state.cache, g, who) { + return Some(u); + } + } + if let Some(u) = ctx.args.user(option) { + return Some(u); + } + } + ctx.reply_to +} + +async fn perform(ctx: &Arc, action: &str, nsfw: bool, who_option: &str) -> Result<()> { + if nsfw && !is_nsfw_channel(ctx) { + return ctx.fail("🔞 That only works in age-restricted channels.").await; + } + ctx.defer().await?; + let state = &ctx.state; + let me = (ctx.user_id, display_name_of(state, ctx.guild_id, ctx.user_id).await); + let target = match resolve_target(ctx, who_option).await { + Some(t) => Some((t, display_name_of(state, ctx.guild_id, t).await)), + None => None, + }; + let bot_target = match &target { + Some((t, _)) => state.cache.user(*t).map(|u| u.bot).unwrap_or(false), + None => false, + }; + ctx.reply(build(state, action, nsfw, me, target, bot_target).await).await +} + +async fn prefix_action(ctx: Arc) -> Result<()> { + let nsfw = !set(false).contains_key(ctx.invoked); + perform(&ctx, ctx.invoked, nsfw, "who").await +} + +async fn interact_slash(ctx: Arc) -> Result<()> { + let action = ctx.args.str("action").unwrap_or("").to_lowercase(); + if !set(false).contains_key(&action) { + return ctx.fail("❌ Pick an action from the list.").await; + } + perform(&ctx, &action, false, "user").await +} + +async fn erp_slash(ctx: Arc) -> Result<()> { + let action = ctx.args.str("action").unwrap_or("").to_lowercase(); + if !set(true).contains_key(&action) { + return ctx.fail("❌ Pick an action from the list.").await; + } + perform(&ctx, &action, true, "user").await +} + +async fn stats_cmd(ctx: Arc) -> Result<()> { + let mut who = ctx.args.str("user").unwrap_or("").to_string(); + let mut nsfw = ctx.args.bool("nsfw").unwrap_or(false); + if !ctx.is_slash() && who.to_lowercase().split_whitespace().last() == Some("nsfw") { + nsfw = true; + who = who.rsplit_once(char::is_whitespace).map(|(a, _)| a.to_string()).unwrap_or_default(); + } + if nsfw && !is_nsfw_channel(&ctx) { + return ctx.fail("🔞 That only works in age-restricted channels.").await; + } + let user = if ctx.is_slash() { + ctx.args.user("user").unwrap_or(ctx.user_id) + } else if who.trim().is_empty() { + ctx.reply_to.unwrap_or(ctx.user_id) + } else { + ctx.guild_id.and_then(|g| find_member(&ctx.state.cache, g, who.trim())).or_else(|| crate::converters::parse_id(who.trim()).and_then(Id::new_checked)).unwrap_or(ctx.user_id) + }; + ctx.defer().await?; + let name = display_name_of(&ctx.state, ctx.guild_id, user).await; + ctx.reply(stats_card(&ctx.state, user, &name, nsfw).await).await +} + +fn suggest_actions(_: Arc, _focused: String, current: String, _: Option>, _: Id) -> futures::future::BoxFuture<'static, Vec<(String, String)>> { + async move { + let current = current.trim().to_lowercase(); + let mut names: Vec<&String> = set(false).keys().collect(); + names.sort(); + let starts: Vec<&&String> = names.iter().filter(|n| n.starts_with(¤t)).collect(); + let contains: Vec<&&String> = names.iter().filter(|n| !n.starts_with(¤t) && n.contains(¤t)).collect(); + starts.into_iter().chain(contains).take(25).map(|n| ((**n).clone(), (**n).clone())).collect() + } + .boxed() +} + +pub fn commands() -> Vec { + let nsfw_names: &'static [&'static str] = Box::leak(set(true).keys().map(|k| &*Box::leak(k.clone().into_boxed_str())).collect::>().into_boxed_slice()); + let mut v = vec![ + Command::new("interact", "actions", "Anime GIF actions: hug, pat, slap, dance and 40 more", |c| interact_slash(c).boxed()) + .usage(" [@user]") + .opt(Opt::req("action", "What to do", OptKind::String).autocomplete()) + .opt(Opt::opt("user", "Who to do it to", OptKind::User)) + .suggest(suggest_actions) + , + Command::new("erp", "nsfw", "🔞 Adult roleplay GIF actions (age-restricted channels only)", |c| erp_slash(c).boxed()) + .usage(" [@user]") + .opt(Opt::req("action", "What to do", OptKind::String).choices(nsfw_names)) + .opt(Opt::opt("user", "Who to do it to", OptKind::User)), + Command::new("interactions", "actions", "How many hugs, kisses, pats … someone has given and received.", |c| stats_cmd(c).boxed()) + .aliases(&["istats", "actionstats", "hugstats"]) + .slash_as("interactstats") + .usage("[@user] [nsfw]") + .opt(Opt::opt("user", "Whose tallies (defaults to you)", OptKind::User)) + .opt(Opt::opt("nsfw", "Show the 🔞 set (age-restricted channels only)", OptKind::Bool).slash_only()), + ]; + for (nsfw, names) in [(false, set(false)), (true, set(true))] { + for (action, entry) in names { + if entry["slash_only"].as_bool() == Some(true) { + continue; + } + let name: &'static str = Box::leak(action.clone().into_boxed_str()); + let text = entry["text"].as_str().unwrap_or("").replace("{user}", "You").replace("{target}", "someone"); + let help: &'static str = Box::leak(format!("{}{text}", if nsfw { "🔞 " } else { "" }).into_boxed_str()); + let cat = if nsfw { "nsfw" } else { "actions" }; + let mut c = Command::new(name, cat, help, |c| prefix_action(c).boxed()).prefix_only().opt(Opt::opt("who", "Who to do it to", OptKind::User)); + if entry["text"].as_str().is_some_and(|t| t.contains("{target}")) { + c = c.usage("[@someone]"); + } + v.push(c); + } + } + v +} + +// ---- buttons ---------------------------------------------------------------------------------------------------------- + +/// A copy of the card with every button switched off. +fn disabled(c: &Component) -> Component { + let mut v = serde_json::to_value(c).unwrap_or(Value::Null); + fn walk(v: &mut Value) { + match v { + Value::Object(o) => { + if o.get("type").and_then(Value::as_u64) == Some(2) { + o.insert("disabled".into(), json!(true)); + } + o.values_mut().for_each(walk); + } + Value::Array(a) => a.iter_mut().for_each(walk), + _ => {} + } + } + walk(&mut v); + serde_json::from_value(v).unwrap_or_else(|_| c.clone()) +} + +pub async fn on_component(state: &Arc, i: &Interaction) { + let Some(InteractionData::MessageComponent(d)) = i.data.as_ref() else { return }; + let p: Vec<&str> = d.custom_id.split(':').collect(); + let [_, kind, action, nsfw, user, target] = p[..] else { return }; + let (Some(user), Some(target)) = (user.parse::().ok().and_then(Id::::new_checked), target.parse::().ok().and_then(Id::::new_checked)) else { return }; + let nsfw = nsfw == "1"; + if !set(nsfw).contains_key(action) { + return; + } + let Some(clicker) = i.author() else { return }; + if clicker.id != target { + return interact::private_text(state, i, "This button is for the person it was aimed at.").await; + } + let Some(msg) = i.message.as_ref() else { return }; + if let Some(card) = msg.components.first() { + interact::update(state, i, disabled(card)).await; + } + let (a, b) = (display_name_of(state, i.guild_id, target).await, display_name_of(state, i.guild_id, user).await); + let card = if kind == "back" { + let bot_target = state.cache.user(user).map(|u| u.bot).unwrap_or(false); + build(state, action, nsfw, (target, a), Some((user, b)), bot_target).await + } else { + build_reject(state, action, (target, a), (user, b)).await + }; + let r = state.http.interaction(state.app_id()).create_followup(&i.token).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]).allowed_mentions(Some(&AllowedMentions::default())).await; + if let Err(e) = r { + tracing::warn!("action follow-up failed: {e}"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_data_file_loads() { + assert!(set(false).len() >= 40 && set(true).len() >= 10); + assert!(set(false)["hug"]["text"].as_str().unwrap().contains("{target}")); + } + + #[test] + fn wording() { + assert_eq!((times(1), times(2), times(1234)), ("**once**".to_string(), "**twice**".to_string(), "**1,234** times".to_string())); + } + + #[test] + fn buttons_get_disabled() { + let card = Card::new(None).text("x").row(vec![button("a:b", "A", ButtonStyle::Primary)]).build(); + let off = disabled(&card); + assert!(serde_json::to_string(&off).unwrap().contains("\"disabled\":true")); + assert!(!serde_json::to_string(&card).unwrap().contains("\"disabled\":true")); + } +} diff --git a/src/commands/fun/ai.rs b/src/commands/fun/ai.rs new file mode 100644 index 0000000..de4a69e --- /dev/null +++ b/src/commands/fun/ai.rs @@ -0,0 +1,432 @@ +//! AI chat: mention the bot (or reply to one of its answers) to talk; `/ask` works too. +//! +//! Models come from OpenRouter. The default is `openrouter/free`, which routes to whichever free model is up, +//! with the current free chat models (fetched from OpenRouter) as fallbacks, so it doesn't break when a model is +//! retired. `AI_MODEL` in .env or `D!setmodel` (owner) can pin one. Each channel remembers the last few +//! messages for 20 minutes. +//! +//! Server admins: `D!persona` (show / edit / add / reset the personality), `D!lockai #channel` / `D!unlockai` +//! (only answer in one channel). Also on the dashboard. +//! +//! State: data/ai.json {"personas": {guild: text}, "locks": {guild: channel}, "answers": [message ids], "model": id}. +use super::super::info::display_name_of; +use crate::cmd::{Command, Ctx, Opt, OptKind}; +use crate::state::State; +use crate::storage::JsonStore; +use crate::ui::{escape, truncate, Card, BLURPLE, RED}; +use crate::{bail_user, paths}; +use anyhow::Result; +use futures::FutureExt; +use serde_json::{json, Value}; +use std::collections::{HashMap, VecDeque}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; +use twilight_model::channel::message::{AllowedMentions, Component, MessageFlags}; +use twilight_model::channel::Message; +use twilight_model::guild::Permissions; +use twilight_model::id::marker::{ChannelMarker, GuildMarker, MessageMarker}; +use twilight_model::id::Id; + +const API: &str = "https://openrouter.ai/api/v1"; +const DEFAULT_MODEL: &str = "openrouter/free"; +const SKIP_WORDS: [&str; 10] = ["lyria", "content-safety", "guard", "code", "embed", "whisper", "tts", "image", "audio", "vision"]; +const RATE_LIMIT: Duration = Duration::from_secs(2); +const MEMORY: Duration = Duration::from_secs(20 * 60); +pub const DEFAULT_PERSONA: &str = "You're Dezio, a friendly Discord bot chatting in a server with several people. Messages arrive as 'Name: message'. Answer naturally and concisely (a few sentences unless asked for more), use Discord markdown when it helps, and never prefix your answer with a name."; + +fn store() -> &'static Arc { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| JsonStore::open(paths::data(&["ai.json"]))) +} + +#[derive(Default)] +struct Mem { + /// channel → (messages, last used) + memory: HashMap, Instant)>, + last_request: HashMap, + fallbacks: Vec, +} + +fn mem() -> std::sync::MutexGuard<'static, Mem> { + static M: OnceLock> = OnceLock::new(); + M.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner()) +} + +fn key() -> Option { + std::env::var("OPENROUTER_KEY").ok().filter(|k| !k.is_empty()) +} + +/// The model pinned with `setmodel` (saved), else AI_MODEL from .env, else the default. +fn model() -> String { + store().get("model").and_then(|v| v.as_str().map(str::to_string)).or_else(|| std::env::var("AI_MODEL").ok().filter(|m| !m.is_empty())).unwrap_or_else(|| DEFAULT_MODEL.into()) +} + +pub fn persona(guild: Option) -> String { + guild.and_then(|g| store().get("personas").and_then(|p| p[g.to_string()].as_str().map(str::to_string))).unwrap_or_else(|| DEFAULT_PERSONA.into()) +} + +pub fn locked_to(guild: Option) -> Option { + store().get("locks").and_then(|l| l[guild?.to_string()].as_u64()) +} + +pub fn set_nested(bucket: &str, key: &str, value: Option) { + store().update(|all| { + let slot = all.entry(bucket.to_string()).or_insert_with(|| json!({})).as_object_mut().unwrap(); + match value { + Some(v) => { + slot.insert(key.to_string(), v); + } + None => { + slot.shift_remove(key); + } + } + }); +} + +fn rate_limited(user: u64) -> bool { + let mut m = mem(); + if m.last_request.get(&user).is_some_and(|t| t.elapsed() < RATE_LIMIT) { + return true; + } + m.last_request.insert(user, Instant::now()); + false +} + +// ---- OpenRouter --------------------------------------------------------------------------------------------- + +fn auth(state: &State, req: reqwest::RequestBuilder, key: &str) -> reqwest::RequestBuilder { + let _ = state; + req.bearer_auth(key).header("HTTP-Referer", "https://dombot.netlify.app").header("X-Title", "Dezio") +} + +/// Keep a list of free chat models to fall back on. +pub async fn refresh_models(state: &State) { + let Some(k) = key() else { return }; + let Ok(r) = auth(state, state.web.get(format!("{API}/models")), &k).send().await else { return }; + let Ok(d) = r.json::().await else { return }; + let mut free: Vec<(&str, u64)> = d["data"].as_array().into_iter().flatten().filter_map(|m| Some((m["id"].as_str()?, m["context_length"].as_u64().unwrap_or(0)))).filter(|(id, _)| id.ends_with(":free") && !SKIP_WORDS.iter().any(|w| id.contains(w))).collect(); + free.sort_by_key(|(_, c)| std::cmp::Reverse(*c)); + let list: Vec = free.iter().take(6).map(|(id, _)| id.to_string()).collect(); + tracing::info!("AI: {}, fallbacks: {}", model(), if list.is_empty() { "none".into() } else { list.join(", ") }); + mem().fallbacks = list; +} + +/// (answer, model used). Tries `first` (default: the main model), then the free fallbacks. +async fn complete(state: &State, messages: &[Value], first: Option<&str>) -> Result<(String, String), String> { + let Some(k) = key() else { return Err("the AI isn't set up (OPENROUTER_KEY is missing from .env)".into()) }; + let mut candidates: Vec = vec![first.map(str::to_string).unwrap_or_else(model)]; + candidates.extend(mem().fallbacks.iter().take(3).cloned()); + let mut seen = std::collections::HashSet::new(); + candidates.retain(|m| seen.insert(m.clone())); + let mut last = "no model answered".to_string(); + for m in candidates { + let payload = json!({"model": m, "messages": messages, "max_tokens": 900, "temperature": 0.8, "reasoning": {"exclude": true, "effort": "low"}}); + let resp = auth(state, state.web.post(format!("{API}/chat/completions")).json(&payload).timeout(Duration::from_secs(60)), &k).send().await; + let r = match resp { + Ok(r) => r, + Err(e) => { + last = format!("{m}: {}", if e.is_timeout() { "timeout" } else { "connection error" }); + continue; + } + }; + let status = r.status(); + let Ok(d) = r.json::().await else { + last = format!("{m}: unreadable answer"); + continue; + }; + if !status.is_success() || d.get("choices").is_none() { + last = format!("{m}: {}", d["error"]["message"].as_str().map_or(status.as_u16().to_string(), str::to_string)); + continue; + } + let content = d["choices"][0]["message"]["content"].as_str().unwrap_or("").trim().to_string(); + if !content.is_empty() { + return Ok((content, d["model"].as_str().unwrap_or(&m).to_string())); + } + last = format!("{m}: empty answer"); + } + Err(last) +} + +// ---- conversation ------------------------------------------------------------------------------------------- + +async fn answer(state: &State, guild: Option>, channel: Id, author_name: &str, prompt: &str) -> Component { + let line = format!("{author_name}: {prompt}"); + let mut messages = vec![json!({"role": "system", "content": persona(guild.map(|g| g.get()))})]; + { + let m = mem(); + if let Some((hist, _)) = m.memory.get(&channel.get()) { + messages.extend(hist.iter().map(|(role, text)| json!({"role": role, "content": text}))); + } + } + messages.push(json!({"role": "user", "content": line})); + match complete(state, &messages, None).await { + Err(e) => Card::new(Some(RED)).text(&format!("⚠️ The AI couldn't answer right now ({}). Try again in a bit.", escape(&e))).build(), + Ok((text, used)) => { + { + let mut m = mem(); + let entry = m.memory.entry(channel.get()).or_insert_with(|| (VecDeque::new(), Instant::now())); + entry.0.push_back(("user".into(), line)); + entry.0.push_back(("assistant".into(), text.clone())); + while entry.0.len() > 10 { + entry.0.pop_front(); + } + entry.1 = Instant::now(); + } + Card::new(Some(BLURPLE)).text(&truncate(&text, 3800)).footer(&format!("{} · {}", escape(&truncate(prompt, 80)), used.rsplit('/').next().unwrap_or(&used))).build() + } + } +} + +fn remember_answer(id: Id) { + store().update(|all| { + let list = all.entry("answers".to_string()).or_insert_with(|| json!([])).as_array_mut().unwrap(); + list.push(json!(id.get())); + while list.len() > 500 { + list.remove(0); + } + }); +} + +fn is_ours(id: Id) -> bool { + store().get("answers").and_then(|a| a.as_array().map(|l| l.iter().any(|x| x.as_u64() == Some(id.get())))).unwrap_or(false) +} + +/// Forget channels nobody has talked in for 20 minutes. Started once. +pub fn start(state: Arc) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tokio::spawn(async move { + refresh_models(&state).await; + loop { + tokio::time::sleep(Duration::from_secs(300)).await; + mem().memory.retain(|_, (_, at)| at.elapsed() < MEMORY); + } + }); + }); +} + +pub async fn on_message(state: Arc, m: Message) { + if m.author.bot { + return; + } + let me = state.bot_id(); + // Only a real @Dezio in the text counts: replying to any bot message (a /download result …) also puts the bot + // in `mentions` through the reply ping, and that shouldn't start a chat. + let mentioned = m.content.contains(&format!("<@{me}>")) || m.content.contains(&format!("<@!{me}>")); + let replying = m.reference.as_ref().and_then(|r| r.message_id).is_some_and(is_ours); + if !(mentioned || replying) { + return; + } + let prompt = m.content.replace(&format!("<@{me}>"), "").replace(&format!("<@!{me}>"), "").trim().to_string(); + let react = |emoji: &'static str| { + let (state, m) = (state.clone(), m.clone()); + async move { + let _ = state.http.create_reaction(m.channel_id, m.id, &twilight_http::request::channel::reaction::RequestReactionType::Unicode { name: emoji }).await; + } + }; + if prompt.is_empty() { + return react("👋").await; + } + if let Some(locked) = locked_to(m.guild_id.map(|g| g.get())).filter(|l| *l != m.channel_id.get()) { + let sent = state.http.create_message(m.channel_id).reply(m.id).content(&format!("🤖 I only chat in <#{locked}> here.")).allowed_mentions(Some(&AllowedMentions::default())).await; + if let Ok(s) = sent { + if let Ok(s) = s.model().await { + tokio::time::sleep(Duration::from_secs(8)).await; + let _ = state.http.delete_message(s.channel_id, s.id).await; + } + } + return; + } + if rate_limited(m.author.id.get()) { + return react("⏳").await; + } + let _ = state.http.create_typing_trigger(m.channel_id).await; + let name = display_name_of(&state, m.guild_id, m.author.id).await; + let card = answer(&state, m.guild_id, m.channel_id, &name, &prompt).await; + let sent = state.http.create_message(m.channel_id).reply(m.id).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]).allowed_mentions(Some(&AllowedMentions::default())).await; + if let Ok(r) = sent { + if let Ok(s) = r.model().await { + remember_answer(s.id); + } + } +} + +// ---- commands --------------------------------------------------------------------------------------------------- + +fn is_admin(ctx: &Ctx) -> bool { + ctx.state.is_owner(ctx.user_id) || ctx.has_permission(Permissions::ADMINISTRATOR) +} + +async fn ask(ctx: Arc) -> Result<()> { + let Some(question) = ctx.args.str("question").map(str::to_string) else { bail_user!("Ask me something.") }; + let guild = ctx.guild_id; + if let Some(l) = locked_to(guild.map(|g| g.get())).filter(|l| *l != ctx.channel_id.get()) { + return ctx.fail(&format!("🤖 The AI only chats in <#{l}> here.")).await; + } + if rate_limited(ctx.user_id.get()) { + return ctx.fail("⏳ One question every couple of seconds, please.").await; + } + ctx.defer().await?; + let name = display_name_of(&ctx.state, guild, ctx.user_id).await; + let card = answer(&ctx.state, guild, ctx.channel_id, &name, &question).await; + match &ctx.origin { + crate::cmd::Origin::Interaction { token, .. } => { + let sent = ctx.state.http.interaction(ctx.state.app_id()).create_followup(token).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]).allowed_mentions(Some(&AllowedMentions::default())).await?; + if let Ok(m) = sent.model().await { + remember_answer(m.id); + } + } + _ => { + if let Some(m) = ctx.reply_message(card).await? { + remember_answer(m.id); + } + } + } + Ok(()) +} + +async fn setmodel(ctx: Arc) -> Result<()> { + let wanted = ctx.args.str("model").unwrap_or("").to_string(); + if wanted.is_empty() { + refresh_models(&ctx.state).await; + let list = mem().fallbacks.iter().map(|m| format!("• `{m}`")).collect::>().join("\n"); + return ctx.say(&format!("**Model:** `{}`\n**Free fallbacks:**\n{}", model(), if list.is_empty() { "*couldn't load the list*".into() } else { list })).await; + } + let wanted = if matches!(wanted.to_lowercase().as_str(), "default" | "auto" | "reset") { DEFAULT_MODEL.to_string() } else { wanted }; + ctx.defer().await?; + match complete(&ctx.state, &[json!({"role": "user", "content": "Reply with the word OK."})], Some(&wanted)).await { + Err(e) => ctx.say(&format!("❌ `{wanted}` didn't answer: {}", escape(&e))).await, + Ok((_, used)) => { + if wanted == DEFAULT_MODEL { + store().pop("model"); + } else { + store().set("model", json!(wanted)); + } + ctx.say(&format!("✅ Using `{wanted}` (answered via `{used}`).")).await + } + } +} + +async fn persona_cmd(ctx: Arc) -> Result<()> { + let guild = ctx.guild()?; + if !is_admin(&ctx) { + bail_user!("You need the **Administrator** permission for that."); + } + let raw = ctx.args.str("args").unwrap_or("").to_string(); + let (sub, text) = raw.split_once(char::is_whitespace).map_or((raw.as_str(), ""), |(a, b)| (a, b.trim())); + let g = guild.get(); + let p = ctx.state.prefix(Some(guild)); + match sub.to_lowercase().as_str() { + "" | "show" => { + let card = Card::new(Some(BLURPLE)).text(&format!("### 🤖 AI personality\n{}", escape(&truncate(&persona(Some(g)), 3000)))).footer(&format!("{p}persona edit · {p}persona add · {p}persona reset")).build(); + ctx.reply(card).await + } + "edit" | "set" => { + if text.chars().count() < 20 { + bail_user!("Give it at least a sentence (20+ characters)."); + } + set_nested("personas", &g.to_string(), Some(json!(text.chars().take(4000).collect::()))); + mem().memory.remove(&ctx.channel_id.get()); + ctx.defer().await?; + let name = display_name_of(&ctx.state, ctx.guild_id, ctx.user_id).await; + let card = answer(&ctx.state, ctx.guild_id, ctx.channel_id, &name, "Introduce yourself in one sentence.").await; + ctx.say("✅ Personality saved. Here's how it sounds:").await?; + ctx.reply(card).await + } + "add" => { + if text.is_empty() { + bail_user!("Add what? `{p}persona add `"); + } + set_nested("personas", &g.to_string(), Some(json!(format!("{}\n{text}", persona(Some(g))).chars().take(4000).collect::()))); + ctx.say("✅ Added to the personality.").await + } + "reset" => { + if store().get("personas").is_none_or(|p| p.get(g.to_string()).is_none()) { + return ctx.say("ℹ️ This server already uses the default personality.").await; + } + set_nested("personas", &g.to_string(), None); + ctx.say("✅ Personality reset to the default.").await + } + _ => bail_user!("Use `{p}persona [show | edit | add | reset]`."), + } +} + +async fn lockai(ctx: Arc) -> Result<()> { + let guild = ctx.guild()?; + if !is_admin(&ctx) { + bail_user!("You need the **Administrator** permission for that."); + } + let Some(channel) = ctx.args.id("channel") else { + return ctx.say(&match locked_to(Some(guild.get())) { + Some(c) => format!("🔒 The AI only chats in <#{c}>."), + None => "🔓 The AI chats in every channel.".into(), + }) + .await; + }; + set_nested("locks", &guild.get().to_string(), Some(json!(channel))); + ctx.say(&format!("🔒 The AI now only chats in <#{channel}>.")).await +} + +async fn unlockai(ctx: Arc) -> Result<()> { + let guild = ctx.guild()?; + if !is_admin(&ctx) { + bail_user!("You need the **Administrator** permission for that."); + } + if locked_to(Some(guild.get())).is_none() { + return ctx.say("🔓 The AI wasn't locked to a channel.").await; + } + set_nested("locks", &guild.get().to_string(), None); + ctx.say("🔓 The AI chats in every channel again.").await +} + +pub fn commands() -> Vec { + vec![ + Command::new("ask", "ai", "Ask the AI anything", |c| ask(c).boxed()).usage("").opt(Opt::req("question", "Your question", OptKind::String)), + Command::new("setmodel", "owner", "Owner: pin the AI model (any OpenRouter id), `default` for automatic, or no argument to see them.", |c| setmodel(c).boxed()) + .usage("[model id | default]") + .opt(Opt::opt("model", "Model id", OptKind::String)) + .owner_only() + .prefix_only(), + Command::new("persona", "ai", "Admins: see or change how the AI behaves in this server.", |c| persona_cmd(c).boxed()) + .usage("[show | edit | add | reset]") + .opt(Opt::opt("args", "show, edit , add or reset", OptKind::String)) + .guild_only() + .prefix_only(), + Command::new("lockai", "ai", "Admins: only answer AI questions in one channel (no channel shows the current lock).", |c| lockai(c).boxed()) + .usage("[#channel]") + .opt(Opt::opt("channel", "The channel", OptKind::Channel)) + .guild_only() + .prefix_only(), + Command::new("unlockai", "ai", "Admins: let the AI chat in every channel again.", |c| unlockai(c).boxed()).guild_only().prefix_only(), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rate_limit_allows_one_every_two_seconds() { + assert!(!rate_limited(424242)); + assert!(rate_limited(424242)); + assert!(!rate_limited(424243)); + } + + #[test] + fn defaults_without_saved_state() { + assert!(persona(None).starts_with("You're Dezio")); + assert_eq!(locked_to(None), None); + assert!(!is_ours(Id::new(1))); + } + + #[test] + fn answers_are_remembered() { + remember_answer(Id::new(777_000_111)); + assert!(is_ours(Id::new(777_000_111))); + } +} + +/// Saved personality (None = the default) — the dashboard's write path. +pub fn saved_persona(guild: u64) -> Option { + store().get("personas").and_then(|p| p[guild.to_string()].as_str().map(str::to_string)) +} diff --git a/src/commands/fun/animals.rs b/src/commands/fun/animals.rs new file mode 100644 index 0000000..41cc8a8 --- /dev/null +++ b/src/commands/fun/animals.rs @@ -0,0 +1,116 @@ +//! Animal pictures and facts: `/animal` or `D!` (`D!cat`, `D!axo` …). +//! +//! Cats, dogs, foxes and ducks come from live APIs (endless pictures); everything else, and any API that's +//! down, uses the saved pictures in assets/data/animals.json. +use crate::cmd::{Command, Ctx, Opt, OptKind}; +use crate::colors; +use crate::paths; +use crate::state::State; +use crate::ui::Card; +use anyhow::Result; +use futures::FutureExt; +use rand::RngExt as _; +use serde_json::Value; +use std::sync::{Arc, OnceLock}; +use std::time::Duration; + +fn data() -> &'static Value { + static D: OnceLock = OnceLock::new(); + D.get_or_init(|| crate::storage::read_json(&paths::asset(&["data", "animals.json"])).unwrap_or(Value::Null)) +} + +fn names() -> Vec<&'static str> { + data().as_object().map(|o| o.keys().map(String::as_str).collect()).unwrap_or_default() +} + +fn emoji(animal: &str) -> &'static str { + match animal { + "axolotl" => "🦎", "cat" => "🐱", "bear" => "🐻", "dog" => "🐶", "duck" => "🦆", "fox" => "🦊", "elephant" => "🐘", "giraffe" => "🦒", + "lion" => "🦁", "monkey" => "🐵", "penguin" => "🐧", "tiger" => "🐯", "rabbit" => "🐰", "horse" => "🐴", "panda" => "🐼", "zebra" => "🦓", + _ => "🐾", + } +} + +fn aliases(animal: &str) -> &'static [&'static str] { + match animal { + "axolotl" => &["axo"], "cat" => &["kitty", "meow"], "dog" => &["doggo", "puppy"], "rabbit" => &["bunny"], _ => &[], + } +} + +fn title(s: &str) -> String { + let mut c = s.chars(); + c.next().map(|f| f.to_uppercase().collect::() + c.as_str()).unwrap_or_default() +} + +/// (api url, JSON pointer to the picture) +fn live(animal: &str) -> Option<(&'static str, &'static str)> { + Some(match animal { + "cat" => ("https://api.thecatapi.com/v1/images/search", "/0/url"), + "dog" => ("https://dog.ceo/api/breeds/image/random", "/message"), + "fox" => ("https://randomfox.ca/floof/", "/image"), + "duck" => ("https://random-d.uk/api/v2/random", "/url"), + _ => return None, + }) +} + +async fn picture(state: &State, animal: &str) -> String { + if let Some((url, pointer)) = live(animal) { + if let Ok(r) = state.web.get(url).timeout(Duration::from_secs(6)).send().await { + if r.status().is_success() { + if let Some(p) = r.json::().await.ok().and_then(|d| d.pointer(pointer).and_then(Value::as_str).map(|s| s.replace("http://", "https://"))) { + return p; + } + } + } + } + let images = data()[animal]["images"].as_array().cloned().unwrap_or_default(); + images.get(rand::rng().random_range(0..images.len().max(1))).and_then(Value::as_str).unwrap_or("").to_string() +} + +async fn send(ctx: &Arc, animal: &str) -> Result<()> { + ctx.defer().await?; + let pic = picture(&ctx.state, animal).await; + let facts = data()[animal]["facts"].as_array().cloned().unwrap_or_default(); + let fact = facts.get(rand::rng().random_range(0..facts.len().max(1))).and_then(Value::as_str).unwrap_or("").to_string(); + let default = rand::rng().random_range(0..0xFFFFFFu32); + let accent = colors::accent(&ctx.state, Some(&pic), default).await; + let who = crate::commands::info::display_name_of(&ctx.state, ctx.guild_id, ctx.user_id).await; + ctx.reply(Card::new(Some(accent)).text(&format!("### {} {}\n{fact}", emoji(animal), title(animal))).gallery(&[&pic]).footer(&format!("Requested by {who}")).build()).await +} + +async fn slash(ctx: Arc) -> Result<()> { + let wanted = ctx.args.str("animal").unwrap_or("cat").to_lowercase(); + let Some(animal) = names().into_iter().find(|n| *n == wanted) else { crate::bail_user!("I don't know that animal.") }; + send(&ctx, animal).await +} + +async fn prefix(ctx: Arc) -> Result<()> { + send(&ctx, ctx.invoked).await +} + +pub fn commands() -> Vec { + let list: &'static [&'static str] = Box::leak(names().into_boxed_slice()); + let mut v = vec![Command::new("animal", "animals", "A random animal picture and fact", |c| slash(c).boxed()) + .usage("") + .opt(Opt::req("animal", "Which animal", OptKind::String).choices(list))]; + for &a in list { + let help: &'static str = Box::leak(format!("A random {a} picture and fact.").into_boxed_str()); + v.push(Command::new(a, "animals", help, |c| prefix(c).boxed()).aliases(aliases(a)).prefix_only()); + } + v +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_animal_has_pictures_and_facts() { + let n = names(); + assert!(n.len() >= 16); + for a in n { + assert!(!data()[a]["images"].as_array().unwrap().is_empty() && !data()[a]["facts"].as_array().unwrap().is_empty(), "{a}"); + } + assert_eq!(title("axolotl"), "Axolotl"); + } +} diff --git a/src/commands/fun/confessions.rs b/src/commands/fun/confessions.rs new file mode 100644 index 0000000..30d84cb --- /dev/null +++ b/src/commands/fun/confessions.rs @@ -0,0 +1,292 @@ +//! Anonymous confessions: `/confess` or the **Confess** button. +//! +//! `D!configconfess #channel` (admins) makes a channel the confession box: members can't type there, a +//! starter card has the Confess button, and every confession is posted through a "DezioConfess" webhook so +//! nobody can see who sent it. Without a box, `/confess` posts in the current channel. Confessions are +//! numbered per server and can include a picture (uploaded in the form). The buttons keep working after +//! restarts (the custom id is `confess:open`, same as before). +//! +//! State: data/confessions.json {guild: {"webhook_url", "channel_id", "count"}}. +use super::super::media::fetch_limited; +use crate::bail_user; +use crate::cmd::{Command, Ctx, Opt, OptKind}; +use crate::state::State; +use crate::storage::JsonStore; +use crate::ui::{button, escape, Card, GREEN, RED}; +use crate::{interact, paths}; +use anyhow::Result; +use base64::Engine as _; +use futures::FutureExt; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; +use twilight_http::request::AuditLogReason as _; +use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_model::channel::message::component::{ButtonStyle, Component, FileUpload, Label}; +use twilight_model::channel::message::{AllowedMentions, MessageFlags}; +use twilight_model::channel::permission_overwrite::{PermissionOverwrite, PermissionOverwriteType}; +use twilight_model::guild::Permissions; +use twilight_model::http::attachment::Attachment; +use twilight_model::id::marker::{ChannelMarker, GuildMarker, UserMarker}; +use twilight_model::id::Id; + +const WEBHOOK_NAME: &str = "DezioConfess"; +const ACCENT: u32 = 0x2B2D31; +const COOLDOWN: Duration = Duration::from_secs(60); + +fn store() -> &'static Arc { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| JsonStore::open(paths::data(&["confessions.json"]))) +} + +fn last() -> &'static Mutex> { + static L: OnceLock>> = OnceLock::new(); + L.get_or_init(Default::default) +} + +fn avatar_uri() -> Option { + let bytes = std::fs::read(paths::asset(&["images", "confessions.png"])).ok()?; + Some(format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))) +} + +/// The card with its Confess button (the button works for any message with this custom id). +fn with_button(card: Card) -> Component { + let mut b = button("confess:open", "Confess", ButtonStyle::Primary); + b.emoji = Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "💌".into() }); + card.row(vec![b]).build() +} + +/// Hours of the cooldown left for this person (0 = go ahead). +fn wait_left(user: u64) -> u64 { + let l = last().lock().unwrap_or_else(|e| e.into_inner()); + l.get(&user).map_or(0, |t| COOLDOWN.saturating_sub(t.elapsed()).as_secs()) +} + +fn form() -> Vec { + let text = interact::text_field("text", "Your confession", None, "", 2000, true, Some("Nobody will know it was you…")); + let upload = Component::Label(Label { + id: None, + label: "Picture (optional)".into(), + description: Some("Images only — they're posted with your confession".into()), + component: Box::new(Component::FileUpload(FileUpload { id: None, custom_id: "file".into(), max_values: Some(1), min_values: Some(0), required: Some(false) })), + }); + vec![text, upload] +} + +async fn open_form(state: &State, i: &Interaction) { + if i.guild_id.is_none() { + return interact::private_text(state, i, "Confessions only work in servers.").await; + } + let Some(user) = i.author() else { return }; + let wait = wait_left(user.id.get()); + if wait > 0 { + return interact::private_text(state, i, &format!("⏳ You can confess again in {wait}s.")).await; + } + interact::modal(state, i, "confess:form", "Anonymous confession", form()).await; +} + +/// The channel's "DezioConfess" webhook (id, token), made if it isn't there. +async fn webhook(state: &State, channel: Id) -> Option<(Id, String)> { + let existing = state.http.channel_webhooks(channel).await.ok()?.models().await.ok()?; + if let Some(h) = existing.into_iter().find(|w| w.name.as_deref() == Some(WEBHOOK_NAME) && w.user.as_ref().is_some_and(|u| u.id == state.bot_id())) { + return Some((h.id, h.token?)); + } + let uri = avatar_uri(); + let mut req = state.http.create_webhook(channel, WEBHOOK_NAME); + if let Some(u) = uri.as_deref() { + req = req.avatar(u); + } + let h = req.await.ok()?.model().await.ok()?; + Some((h.id, h.token?)) +} + +fn parse_hook(url: &str) -> Option<(Id, String)> { + let rest = url.split("/webhooks/").nth(1)?; + let (id, token) = rest.split_once('/')?; + Some((Id::new_checked(id.parse().ok()?)?, token.split('?').next()?.to_string())) +} + +async fn post(state: &Arc, guild: Id, here: Id, user: Id, text: &str, image: Option<(String, String)>) -> Component { + let fail = |t: &str| Card::new(Some(RED)).text(t).build(); + let mut cfg = store().get(guild.get()).unwrap_or_else(|| json!({})); + let channel: Id = cfg["channel_id"].as_u64().and_then(Id::new_checked).unwrap_or(here); + if state.cache.channel(channel).is_none() && cfg["channel_id"].as_u64().is_some() { + return fail("❌ The confession channel is gone — an admin should run `D!configconfess`."); + } + let mut hook = cfg["webhook_url"].as_str().and_then(parse_hook); + if hook.is_none() || (cfg["channel_id"].as_u64().is_some_and(|c| c != channel.get())) { + hook = webhook(state, channel).await; + } + let Some((hook_id, token)) = hook else { return fail("❌ I need **Manage Webhooks** in that channel to post confessions.") }; + + let number = cfg["count"].as_u64().unwrap_or(0) + 1; + let mut card = Card::new(Some(ACCENT)).text(&format!("### 💌 Confession #{number}\n{}", escape(text))); + let mut files = Vec::new(); + if let Some((url, name)) = image { + let name = crate::ui::file_name(&name); + if let Some(bytes) = fetch_limited(state, &url, 10 * 1024 * 1024).await { + card = card.gallery(&[&format!("attachment://{name}")]); + files.push(Attachment::from_bytes(name, bytes, 1)); + } + } + card = card.footer(&crate::ui::timestamp(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64), 'f')); + let components = [with_button(card)]; + let thread = state.cache.channel(channel).is_some_and(|c| c.kind.is_thread()); + let parent = state.cache.channel(channel).and_then(|c| if c.kind.is_thread() { c.parent_id } else { None }); + let no_pings = AllowedMentions::default(); + let _ = parent; + let mut req = state.http.execute_webhook(hook_id, &token).username(WEBHOOK_NAME).components(&components).flags(MessageFlags::IS_COMPONENTS_V2).allowed_mentions(Some(&no_pings)); + if thread { + req = req.thread_id(channel); + } + if !files.is_empty() { + req = req.attachments(&files); + } + let sent = match req.wait().await { + Ok(r) => match r.model().await { + Ok(m) => m, + Err(_) => return fail("❌ It posted, but I couldn't read the answer."), + }, + Err(e) => { + if matches!(e.kind(), twilight_http::error::ErrorType::Response { status, .. } if status.get() == 404) { + if let Some(o) = cfg.as_object_mut() { + o.remove("webhook_url"); + } + store().set(guild.get(), cfg); + return fail("❌ The confession webhook was deleted — try again."); + } + return fail(&format!("❌ Couldn't post it: {}", e.to_string().chars().take(200).collect::())); + } + }; + cfg["count"] = json!(number); + if cfg["channel_id"].as_u64().is_some() { + cfg["webhook_url"] = json!(format!("https://discord.com/api/webhooks/{hook_id}/{token}")); + } + store().set(guild.get(), cfg); + last().lock().unwrap_or_else(|e| e.into_inner()).insert(user.get(), Instant::now()); + let link = format!("https://discord.com/channels/{guild}/{}/{}", sent.channel_id, sent.id); + with_button(Card::new(Some(GREEN)).text(&format!("✅ [Confession #{number}]({link}) posted anonymously."))) +} + +pub async fn on_component(state: &Arc, i: &Interaction) { + match i.data.as_ref() { + Some(InteractionData::MessageComponent(_)) => open_form(state, i).await, + Some(InteractionData::ModalSubmit(d)) => { + let (Some(guild), Some(user)) = (i.guild_id, i.author()) else { return }; + let fields = interact::modal_values(d); + let text = fields.get("text").map(|t| t.trim().to_string()).unwrap_or_default(); + if text.is_empty() { + return interact::private_text(state, i, "Write something to confess first.").await; + } + interact::defer_private(state, i).await; + let image = fields.get("file").and_then(|id| id.parse::().ok()).and_then(|id| { + let a = d.resolved.as_ref()?.attachments.get(&Id::new_checked(id)?)?; + a.content_type.as_deref().is_some_and(|t| t.starts_with("image/")).then(|| { + let ext = a.filename.rsplit_once('.').map_or("png", |(_, e)| e).to_lowercase(); + (a.url.clone(), format!("confession.{ext}")) + }) + }); + let channel = i.channel.as_ref().map(|c| c.id).unwrap_or(Id::new(1)); + let card = post(state, guild, channel, user.id, &text, image).await; + let r = state.http.interaction(state.app_id()).create_followup(&i.token).flags(MessageFlags::IS_COMPONENTS_V2 | MessageFlags::EPHEMERAL).components(&[card]).allowed_mentions(Some(&AllowedMentions::default())).await; + if let Err(e) = r { + tracing::warn!("confession answer failed: {e}"); + } + } + _ => {} + } +} + +async fn confess(ctx: Arc) -> Result<()> { + // slash only: show the form (a modal must be the first answer, so this can't go through ctx.reply) + let crate::cmd::Origin::Interaction { id, token, responded, .. } = &ctx.origin else { bail_user!("Use `/confess` for that.") }; + ctx.guild()?; + let wait = wait_left(ctx.user_id.get()); + if wait > 0 { + return ctx.fail(&format!("⏳ You can confess again in {wait}s.")).await; + } + responded.store(true, std::sync::atomic::Ordering::SeqCst); + use twilight_model::http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType}; + let data = InteractionResponseData { custom_id: Some("confess:form".into()), title: Some("Anonymous confession".into()), components: Some(form()), ..Default::default() }; + let r = InteractionResponse { kind: InteractionResponseType::Modal, data: Some(data) }; + ctx.state.http.interaction(ctx.state.app_id()).create_response(*id, token, &r).await?; + Ok(()) +} + +async fn configconfess(ctx: Arc) -> Result<()> { + let guild = ctx.guild()?; + let target = ctx.args.str("target").unwrap_or("").trim().to_string(); + if matches!(target.to_lowercase().as_str(), "off" | "disable" | "none" | "reset") { + store().pop(guild.get()); + return ctx.say("✅ Confessions now post in whatever channel `/confess` is used in.").await; + } + let Some(channel) = ctx.args.id("target").and_then(Id::::new_checked) else { bail_user!("Which channel? `configconfess #channel`, or `configconfess off`.") }; + ctx.defer().await?; + let state = &ctx.state; + let Some(hook) = webhook(state, channel).await else { bail_user!("I need **Manage Webhooks** in that channel.") }; + let reason = crate::commands::moderation::audit_reason(&ctx, Some("confession channel")); + let existing: Vec = state.cache.channel(channel).and_then(|c| c.permission_overwrites.clone()).unwrap_or_default(); + let edit = |id: u64, kind: PermissionOverwriteType, allow: Permissions, deny: Permissions| { + let mut o = existing.iter().find(|o| o.id.get() == id && o.kind == kind).cloned().unwrap_or(PermissionOverwrite { id: Id::new(id), kind, allow: Permissions::empty(), deny: Permissions::empty() }); + o.allow.remove(deny); + o.deny.remove(allow); + o.allow |= allow; + o.deny |= deny; + o + }; + let everyone = edit(guild.get(), PermissionOverwriteType::Role, Permissions::empty(), Permissions::SEND_MESSAGES); + let me = edit(state.bot_id().get(), PermissionOverwriteType::Member, Permissions::SEND_MESSAGES, Permissions::empty()); + for o in [&everyone, &me] { + let wire = twilight_model::http::permission_overwrite::PermissionOverwrite { + allow: Some(o.allow), + deny: Some(o.deny), + id: Id::new(o.id.get()), + kind: match o.kind { + PermissionOverwriteType::Member => twilight_model::http::permission_overwrite::PermissionOverwriteType::Member, + _ => twilight_model::http::permission_overwrite::PermissionOverwriteType::Role, + }, + }; + if state.http.update_channel_permission(channel, &wire).reason(&reason).await.is_err() { + bail_user!("I need **Manage Channels** to lock the confession channel."); + } + } + let mut cfg = store().get(guild.get()).unwrap_or_else(|| json!({})); + cfg["webhook_url"] = json!(format!("https://discord.com/api/webhooks/{}/{}", hook.0, hook.1)); + cfg["channel_id"] = json!(channel.get()); + store().set(guild.get(), cfg); + let starter = with_button(Card::new(Some(ACCENT)).text("### 🔒 Confession box\nPress **Confess** to post anonymously. Your name is never shown.")); + state.http.create_message(channel).flags(MessageFlags::IS_COMPONENTS_V2).components(&[starter]).allowed_mentions(Some(&AllowedMentions::default())).await?; + ctx.say(&format!("✅ <#{channel}> is now the confession box.")).await +} + +pub fn commands() -> Vec { + vec![ + Command::new("confess", "fun", "Post an anonymous confession (you can add a picture)", |c| confess(c).boxed()).guild_only(), + Command::new("configconfess", "server", "Make a channel the confession box (members can't type there; a Confess button is posted). `configconfess off` goes back to confessing in any channel.", |c| configconfess(c).boxed()) + .aliases(&["confessions"]) + .usage("<#channel | off>") + .opt(Opt::req("target", "The confession channel, or 'off'", OptKind::String)) + .perm(Permissions::ADMINISTRATOR) + .prefix_only(), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn webhook_urls_parse() { + let (id, token) = parse_hook("https://discord.com/api/webhooks/123456/abc-DEF_1?wait=true").unwrap(); + assert_eq!((id.get(), token.as_str()), (123456, "abc-DEF_1")); + assert!(parse_hook("https://example.com/").is_none()); + } + + #[test] + fn the_form_has_a_text_box_and_an_upload() { + let f = form(); + assert_eq!(f.len(), 2); + assert!(serde_json::to_string(&f[1]).unwrap().contains("\"custom_id\":\"file\"")); + } +} diff --git a/src/commands/fun/mod.rs b/src/commands/fun/mod.rs new file mode 100644 index 0000000..68d3eb7 --- /dev/null +++ b/src/commands/fun/mod.rs @@ -0,0 +1,33 @@ +//! Fun: animals, anime GIF actions, confessions, phone calls and AI chat. +use crate::cmd::Command; +use std::collections::HashSet; + +pub mod actions; +pub mod ai; +pub mod animals; +pub mod confessions; +pub mod phone; + +pub fn commands() -> Vec { + let mut v = Vec::new(); + v.extend(confessions::commands()); + v.extend(phone::commands()); + v.extend(ai::commands()); + v +} + +/// Commands named after data (one per animal, one per action). They never take a name another command +/// already has, like the Python bot (`D!kick` stays the moderation command, not the kick GIF). +pub fn late_commands(taken: &mut HashSet) -> Vec { + let mut out = Vec::new(); + for c in animals::commands().into_iter().chain(actions::commands()) { + let names: Vec = std::iter::once(c.name).chain(c.aliases.iter().copied()).map(str::to_lowercase).collect(); + if names.iter().any(|n| taken.contains(n)) { + tracing::debug!("skipping D!{}: that name is taken", c.name); + continue; + } + taken.extend(names); + out.push(c); + } + out +} diff --git a/src/commands/fun/phone.rs b/src/commands/fun/phone.rs new file mode 100644 index 0000000..a589482 --- /dev/null +++ b/src/commands/fun/phone.rs @@ -0,0 +1,364 @@ +//! Phone calls: `D!call` / `/call` connects this channel to a random channel (another server if possible) +//! that's also calling; `D!hangup` / `/hangup` ends it. +//! +//! Messages are relayed through a "Dezio Phone" webhook showing the sender's name and avatar. Edits, deletes, +//! replies, stickers, attachments and reactions carry over. Calls end after 2 minutes of silence; waiting +//! for someone to pick up times out after 2 minutes too. Everything lives in memory (calls don't survive a restart). +use super::super::info::display_name_of; +use crate::cmd::{Command, Ctx}; +use crate::state::State; +use crate::ui::{escape, truncate}; +use anyhow::Result; +use futures::FutureExt; +use rand::RngExt as _; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; +use twilight_http::request::channel::reaction::RequestReactionType; +use twilight_model::channel::message::{AllowedMentions, EmojiReactionType}; +use twilight_model::channel::{ChannelType, Message}; +use twilight_model::gateway::payload::incoming::MessageUpdate; +use twilight_model::id::marker::{ChannelMarker, MessageMarker, WebhookMarker}; +use twilight_model::id::Id; + +const WEBHOOK_NAME: &str = "Dezio Phone"; +const RING_TIMEOUT: Duration = Duration::from_secs(120); +const IDLE_TIMEOUT: Duration = Duration::from_secs(120); + +type Channel = Id; +type Hook = (Id, String); + +struct Call { + a: Channel, + b: Channel, + started: Instant, + last: Instant, + /// original message → (other channel, relayed message, the text we sent) + relayed: HashMap, String)>, + /// relayed message → original message + reverse: HashMap, +} + +impl Call { + fn other(&self, c: Channel) -> Channel { + if c == self.a { self.b } else { self.a } + } +} + +#[derive(Default)] +struct Phone { + calls: HashMap>>, + waiting: HashMap, + hooks: HashMap, +} + +fn phone() -> &'static Mutex { + static P: OnceLock> = OnceLock::new(); + P.get_or_init(Default::default) +} + +fn lock() -> std::sync::MutexGuard<'static, Phone> { + phone().lock().unwrap_or_else(|e| e.into_inner()) +} + +fn call_of(c: Channel) -> Option>> { + lock().calls.get(&c.get()).cloned() +} + +async fn say(state: &State, channel: Channel, text: &str) { + let _ = state.http.create_message(channel).content(text).allowed_mentions(Some(&AllowedMentions::default())).await; +} + +fn describe(state: &State, c: Channel) -> String { + match state.cache.channel(c) { + Some(ch) => { + let guild = ch.guild_id.and_then(|g| state.cache.guild(g).map(|g| g.name().to_string())).unwrap_or_else(|| "a server".into()); + format!("**{}** · #{}", escape(&guild), escape(ch.name.as_deref().unwrap_or("channel"))) + } + None => "another server".into(), + } +} + +async fn hook_for(state: &State, channel: Channel) -> Option { + if let Some(h) = lock().hooks.get(&channel.get()).cloned() { + return Some(h); + } + let existing = state.http.channel_webhooks(channel).await.ok()?.models().await.ok()?; + let found = existing.into_iter().find(|w| w.name.as_deref() == Some(WEBHOOK_NAME) && w.user.as_ref().is_some_and(|u| u.id == state.bot_id())); + let hook = match found { + Some(h) => h, + None => state.http.create_webhook(channel, WEBHOOK_NAME).await.ok()?.model().await.ok()?, + }; + let pair = (hook.id, hook.token?); + lock().hooks.insert(channel.get(), pair.clone()); + Some(pair) +} + +async fn end(state: &State, call: &Arc>, reason: &str) { + let (a, b, secs) = { + let c = call.lock().unwrap_or_else(|e| e.into_inner()); + (c.a, c.b, c.started.elapsed().as_secs()) + }; + { + let mut p = lock(); + for c in [a, b] { + if p.calls.get(&c.get()).is_some_and(|x| Arc::ptr_eq(x, call)) { + p.calls.remove(&c.get()); + } + } + } + for c in [a, b] { + say(state, c, &format!("📞 {reason} (call lasted {}m {}s)", secs / 60, secs % 60)).await; + } +} + +async fn dial(state: &State, channel: Channel) -> String { + let Some(ch) = state.cache.channel(channel) else { return "📞 I can't see this channel.".into() }; + if ch.kind != ChannelType::GuildText { + return "📞 Calls only work in normal text channels.".into(); + } + let guild = ch.guild_id; + if let Some(call) = call_of(channel) { + let (other, mins) = { + let c = call.lock().unwrap_or_else(|e| e.into_inner()); + (c.other(channel), c.started.elapsed().as_secs() / 60) + }; + return format!("📞 Already connected to {} for {mins}m.", describe(state, other)); + } + if lock().waiting.contains_key(&channel.get()) { + return "📞 Still ringing… (`hangup` to stop)".into(); + } + if hook_for(state, channel).await.is_none() { + return "❌ I need **Manage Webhooks** here to make calls.".into(); + } + let others: Vec = lock().waiting.keys().filter(|c| **c != channel.get()).filter_map(|c| Id::new_checked(*c)).filter(|c| state.cache.channel(*c).is_some()).collect(); + // prefer another server; two channels of the same server can still call each other + let elsewhere: Vec = others.iter().copied().filter(|c| state.cache.channel(*c).and_then(|x| x.guild_id) != guild).collect(); + let pool = if elsewhere.is_empty() { others } else { elsewhere }; + if !pool.is_empty() { + let other = pool[rand::rng().random_range(0..pool.len())]; + let call = Arc::new(Mutex::new(Call { a: other, b: channel, started: Instant::now(), last: Instant::now(), relayed: Default::default(), reverse: Default::default() })); + { + let mut p = lock(); + p.waiting.remove(&other.get()); + p.calls.insert(other.get(), call.clone()); + p.calls.insert(channel.get(), call); + } + say(state, other, &format!("📞 Connected to {} — say hi! (`hangup` to end)", describe(state, channel))).await; + return format!("📞 Connected to {} — say hi! (`hangup` to end)", describe(state, other)); + } + lock().waiting.insert(channel.get(), Instant::now()); + "📞 Ringing… waiting for another server to pick up (2 minutes).".into() +} + +async fn hang_up(state: &State, channel: Channel, who: &str) -> Option { + if lock().waiting.remove(&channel.get()).is_some() { + return Some("📞 Stopped ringing.".into()); + } + let Some(call) = call_of(channel) else { return Some("📞 This channel isn't in a call.".into()) }; + end(state, &call, &format!("{who} hung up.")).await; + None +} + +/// Check for rings nobody answered and calls gone quiet. Started once. +pub fn start_watch(state: Arc) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tokio::spawn(async move { + loop { + tokio::time::sleep(Duration::from_secs(20)).await; + let timed_out: Vec = lock().waiting.iter().filter(|(_, t)| t.elapsed() > RING_TIMEOUT).map(|(c, _)| *c).collect(); + for c in timed_out { + lock().waiting.remove(&c); + if let Some(id) = Id::new_checked(c) { + say(&state, id, "📞 Nobody picked up. Try again later!").await; + } + } + let mut quiet: Vec>> = Vec::new(); + for call in lock().calls.values() { + if call.lock().unwrap_or_else(|e| e.into_inner()).last.elapsed() > IDLE_TIMEOUT && !quiet.iter().any(|q| Arc::ptr_eq(q, call)) { + quiet.push(call.clone()); + } + } + for call in quiet { + end(&state, &call, "Call ended — nobody said anything for 2 minutes.").await; + } + } + }); + }); +} + +async fn call_cmd(ctx: Arc) -> Result<()> { + ctx.defer().await?; + let text = dial(&ctx.state, ctx.channel_id).await; + ctx.say(&text).await +} + +async fn hangup_cmd(ctx: Arc) -> Result<()> { + match hang_up(&ctx.state, ctx.channel_id, &ctx.user_name).await { + Some(t) => ctx.say(&t).await, + None if ctx.is_slash() => ctx.fail("📞 Hung up.").await, + None => Ok(()), + } +} + +// ---- relaying ----------------------------------------------------------------------------------------------- + +fn content_of(m: &Message) -> String { + let mut parts: Vec = Vec::new(); + if !m.content.is_empty() { + parts.push(m.content.clone()); + } + parts.extend(m.attachments.iter().map(|a| a.url.clone())); + parts.extend(m.sticker_items.iter().map(|s| format!("https://media.discordapp.net/stickers/{}.png", s.id))); + parts.join("\n").chars().take(2000).collect() +} + +pub async fn on_message(state: Arc, m: Message) { + let Some(call) = call_of(m.channel_id) else { return }; + if m.author.bot || m.webhook_id.is_some() { + return; + } + let prefix = state.prefix(m.guild_id); + if m.content.get(..prefix.len()).is_some_and(|h| h.eq_ignore_ascii_case(&prefix)) { + return; + } + let target = { + let mut c = call.lock().unwrap_or_else(|e| e.into_inner()); + c.last = Instant::now(); + c.other(m.channel_id) + }; + let Some((hook_id, token)) = hook_for(&state, target).await else { return }; + let mut content = content_of(&m); + if let Some(r) = m.referenced_message.as_deref() { + let who = display_name_of(&state, m.guild_id, r.author.id).await; + content = format!("-# ↪ {}: {}\n{content}", escape(&who), escape(&truncate(if r.content.is_empty() { "…" } else { &r.content }, 80))); + } + if content.trim().is_empty() { + return; + } + let name: String = display_name_of(&state, m.guild_id, m.author.id).await.chars().take(80).collect(); + let avatar = super::super::media::avatar(&state, m.author.id, 128).await; + let no_pings = AllowedMentions::default(); + let sent = state.http.execute_webhook(hook_id, &token).content(&content).username(&name).avatar_url(&avatar).allowed_mentions(Some(&no_pings)).wait().await; + match sent { + Ok(r) => { + let Ok(sent) = r.model().await else { return }; + let mut c = call.lock().unwrap_or_else(|e| e.into_inner()); + c.relayed.insert(m.id.get(), (target, sent.id, content)); + c.reverse.insert(sent.id.get(), m.id.get()); + } + Err(e) => { + if matches!(e.kind(), twilight_http::error::ErrorType::Response { status, .. } if status.get() == 404) { + lock().hooks.remove(&target.get()); + } + } + } +} + +pub async fn on_edit(state: Arc, u: MessageUpdate) { + let Some(call) = call_of(u.channel_id) else { return }; + let new = content_of(&u.0); + let (target, relayed) = { + let mut c = call.lock().unwrap_or_else(|e| e.into_inner()); + let Some(entry) = c.relayed.get_mut(&u.id.get()) else { return }; + if entry.2 == new || u.author.bot { + return; + } + entry.2 = new.clone(); + (entry.0, entry.1) + }; + let Some((hook_id, token)) = lock().hooks.get(&target.get()).cloned() else { return }; + let text = if new.is_empty() { "*(empty)*".to_string() } else { new }; + let no_pings = AllowedMentions::default(); + let _ = state.http.update_webhook_message(hook_id, &token, relayed).content(Some(&text)).allowed_mentions(Some(&no_pings)).await; +} + +pub async fn on_delete(state: Arc, channel: Channel, message: Id) { + let Some(call) = call_of(channel) else { return }; + let (target, relayed) = { + let mut c = call.lock().unwrap_or_else(|e| e.into_inner()); + let Some((t, r, _)) = c.relayed.remove(&message.get()) else { return }; + c.reverse.remove(&r.get()); + (t, r) + }; + let Some((hook_id, token)) = lock().hooks.get(&target.get()).cloned() else { return }; + let _ = state.http.delete_webhook_message(hook_id, &token, relayed).await; +} + +/// (channel, message) of the copy of this message on the other end. +fn counterpart(channel: Channel, message: Id) -> Option<(Channel, Id)> { + let call = call_of(channel)?; + let c = call.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((t, r, _)) = c.relayed.get(&message.get()) { + return Some((*t, *r)); + } + let original = c.reverse.get(&message.get())?; + Id::new_checked(*original).map(|o| (c.other(channel), o)) +} + +fn as_request(e: &EmojiReactionType) -> RequestReactionType<'_> { + match e { + EmojiReactionType::Custom { id, name, .. } => RequestReactionType::Custom { id: *id, name: name.as_deref() }, + EmojiReactionType::Unicode { name } => RequestReactionType::Unicode { name }, + } +} + +pub async fn on_reaction(state: Arc, channel: Channel, message: Id, user: Id, emoji: EmojiReactionType, added: bool) { + if user == state.bot_id() || state.cache.user(user).is_some_and(|u| u.bot) { + return; + } + let Some((target, copy)) = counterpart(channel, message) else { return }; + if added { + let _ = state.http.create_reaction(target, copy, &as_request(&emoji)).await; + return; + } + // only take ours away once nobody else has the reaction left on this side + let Ok(m) = state.http.message(channel, message).await else { return }; + let Ok(m) = m.model().await else { return }; + let others = m.reactions.iter().find(|r| r.emoji == emoji).map_or(0, |r| r.count.saturating_sub(u64::from(r.me))); + if others == 0 { + let _ = state.http.delete_current_user_reaction(target, copy, &as_request(&emoji)).await; + } +} + +pub fn commands() -> Vec { + vec![ + Command::new("call", "fun", "Phone a random channel in another server", |c| call_cmd(c).boxed()).guild_only().cooldown(5), + Command::new("hangup", "fun", "End this channel's phone call", |c| hangup_cmd(c).boxed()).aliases(&["endcall"]).guild_only(), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ch(n: u64) -> Channel { + Id::new(n) + } + + #[test] + fn a_call_knows_the_other_end() { + let c = Call { a: ch(1), b: ch(2), started: Instant::now(), last: Instant::now(), relayed: Default::default(), reverse: Default::default() }; + assert_eq!((c.other(ch(1)), c.other(ch(2))), (ch(2), ch(1))); + } + + #[test] + fn messages_map_both_ways() { + let call = Arc::new(Mutex::new(Call { a: ch(901), b: ch(902), started: Instant::now(), last: Instant::now(), relayed: Default::default(), reverse: Default::default() })); + { + let mut c = call.lock().unwrap(); + c.relayed.insert(10, (ch(902), Id::new(20), "hi".into())); + c.reverse.insert(20, 10); + } + { + let mut p = lock(); + p.calls.insert(901, call.clone()); + p.calls.insert(902, call); + } + assert_eq!(counterpart(ch(901), Id::new(10)), Some((ch(902), Id::new(20)))); + assert_eq!(counterpart(ch(902), Id::new(20)), Some((ch(901), Id::new(10)))); + assert_eq!(counterpart(ch(903), Id::new(10)), None); + lock().calls.clear(); + } +} diff --git a/src/commands/gameboy.rs b/src/commands/gameboy.rs new file mode 100644 index 0000000..9f8523d --- /dev/null +++ b/src/commands/gameboy.rs @@ -0,0 +1,85 @@ +//! Game Boy: `/gameboy` opens the Dezio Game Boy Discord Activity — a real emulator (binjgb) that runs inside Discord +//! with keyboard, controller and touch controls, sound, and per-account cloud saves. +//! +//! The Activity's page and API live in web/activity/ and src/web/activity.rs (served by the dashboard's web server). The +//! same page also works in a normal browser (DASHBOARD_URL/activity/, signed in with the dashboard's Discord login), which +//! is what `/gameboy` offers when the Activity can't be launched. `D!gameboy` posts a card with a Play button that launches +//! it (works after restarts). +//! +//! Owner setup, once, in the Developer Portal (app → Activities): +//! 1. Settings → enable Activities. +//! 2. URL Mappings → prefix `/` → target `/activity`. +use crate::cmd::{Command, Ctx, Origin}; +use crate::state::State; +use crate::ui::{button, Card}; +use anyhow::Result; +use futures::FutureExt; +use std::sync::Arc; +use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_model::channel::message::component::{Button, ButtonStyle}; +use twilight_model::id::marker::InteractionMarker; +use twilight_model::id::Id; + +const ACCENT: u32 = 0x8BD450; + +fn browser_url() -> Option { + let base = std::env::var("DASHBOARD_URL").unwrap_or_default(); + let base = base.trim_end_matches('/'); + base.starts_with("https://").then(|| format!("{base}/activity/")) +} + +fn link(label: &str, url: &str) -> Button { + Button { id: None, custom_id: None, disabled: false, emoji: Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "🌐".into() }), label: Some(label.into()), style: ButtonStyle::Link, url: Some(url.into()), sku_id: None } +} + +fn fallback_card(reason: &str) -> twilight_model::channel::message::Component { + let mut card = Card::new(Some(ACCENT)).text(&format!("### 🎮 Dezio Game Boy\n{reason}")); + if let Some(url) = browser_url() { + card = card.text("You can play in your browser instead — same games, same saves (sign in with Discord).").row(vec![link("Play in browser", &url)]); + } + card.build() +} + +/// Answer an interaction with "launch the Activity". Err = Discord said no (Activities off, or not allowed here). +async fn launch(state: &State, id: Id, token: &str) -> Result<(), String> { + let r = state.web.post(format!("https://discord.com/api/v10/interactions/{id}/{token}/callback")).json(&serde_json::json!({"type": 12})).send().await.map_err(|e| e.to_string())?; + if r.status().is_success() { + return Ok(()); + } + let body: serde_json::Value = r.json().await.unwrap_or_default(); + tracing::info!("Couldn't launch the Game Boy Activity: {body}"); + Err(if body["code"].as_u64() == Some(50234) { "The in-Discord Activity isn't switched on yet (the bot's owner has to enable Activities).".into() } else { "Discord couldn't open the Activity here.".into() }) +} + +async fn gameboy(ctx: Arc) -> Result<()> { + if let Origin::Interaction { id, token, responded, .. } = &ctx.origin { + responded.store(true, std::sync::atomic::Ordering::SeqCst); + return match launch(&ctx.state, *id, token).await { + Ok(()) => Ok(()), + Err(reason) => { + responded.store(false, std::sync::atomic::Ordering::SeqCst); + ctx.reply_private(fallback_card(&reason)).await + } + }; + } + let mut buttons = vec![{ + let mut b = button("gameboy:play", "Play Game Boy", ButtonStyle::Success); + b.emoji = Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "🎮".into() }); + b + }]; + if let Some(url) = browser_url() { + buttons.push(link("Play in browser", &url)); + } + ctx.reply(Card::new(Some(ACCENT)).text("### 🎮 Dezio Game Boy\nPokémon, Zelda, Mario, Kirby and more — playing right here in Discord.\n-# Keyboard, controllers and touch all work · your saves follow your account").row(buttons).build()).await +} + +pub async fn on_component(state: &Arc, i: &Interaction) { + let Some(InteractionData::MessageComponent(_)) = i.data.as_ref() else { return }; + if let Err(reason) = launch(state, i.id, &i.token).await { + crate::interact::private_card(state, i, fallback_card(&reason)).await; + } +} + +pub fn commands() -> Vec { + vec![Command::new("gameboy", "games", "Play Game Boy games (Pokémon, Zelda, Mario, Kirby…) right in Discord", |c| gameboy(c).boxed()).aliases(&["gb", "pokemon"])] +} diff --git a/src/commands/games/aki.rs b/src/commands/games/aki.rs new file mode 100644 index 0000000..541daf3 --- /dev/null +++ b/src/commands/games/aki.rs @@ -0,0 +1,340 @@ +//! Akinator: think of a character, animal or object and answer its questions. +//! +//! The old `akinator` libraries no longer work with Akinator's site, so this talks to the site directly (the same +//! requests its own web page makes). Outside age-restricted channels the game runs in child mode. +use super::*; +use crate::ui::Card; +use regex::Regex; +use std::sync::Mutex as StdMutex; + +const UA: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36"; +const BASE: &str = "https://en.akinator.com"; +pub const THEMES: [(&str, &str); 3] = [("characters", "1"), ("objects", "2"), ("animals", "14")]; +const ANSWERS: [(&str, &str); 5] = [("Yes", "✅"), ("No", "❌"), ("Don't know", "🤷"), ("Probably", "👍"), ("Probably not", "👎")]; + +fn akitude(face: &str) -> String { + format!("{BASE}/assets/img/akitudes_670x1096/{face}.png") +} + +#[derive(Clone, Copy, PartialEq)] +enum St { + Question, + Guess, + Won, + Lost, +} + +struct Sh { + jar: std::path::PathBuf, + sid: String, + cm: bool, + session: String, + step: String, + progression: String, + last_proposition: String, + question: Option, + guess: Option, + number: u32, + state: St, + note: Option, + over: bool, +} + +type Shared = Arc>; + +impl Drop for Sh { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.jar); + } +} + +fn sh(s: &Shared) -> std::sync::MutexGuard<'_, Sh> { + s.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// One request to the site. Akinator sits behind Cloudflare, which turns away Rust's TLS fingerprint, so the +/// requests go through the `curl` tool (with a cookie jar for the session). +async fn fetch(jar: &std::path::Path, path: &str, form: &[(&str, String)]) -> Result { + let mut cmd = tokio::process::Command::new("curl"); + cmd.args(["-sS", "-m", "15", "-A", UA, "-H", "X-Requested-With: XMLHttpRequest", "-H", &format!("Referer: {BASE}/game"), "-b"]).arg(jar).arg("-c").arg(jar); + for (k, v) in form { + cmd.arg("--data-urlencode").arg(format!("{k}={v}")); + } + cmd.arg(format!("{BASE}{path}")).stdin(std::process::Stdio::null()).kill_on_drop(true); + let out = cmd.output().await.map_err(|_| "Akinator needs the `curl` tool on the bot's host.".to_string())?; + if !out.status.success() { + return Err("Akinator is not answering — try again.".into()); + } + Ok(String::from_utf8_lossy(&out.stdout).into_owned()) +} + +async fn post(s: &Shared, path: &str, mut data: Vec<(&str, String)>) -> Result { + let (jar, session) = { + let g = sh(s); + (g.jar.clone(), g.session.clone()) + }; + data.push(("session", session)); + let text = fetch(&jar, path, &data).await?; + let v: Value = serde_json::from_str(&text).map_err(|_| "Akinator didn't understand that.".to_string())?; + match v["completion"].as_str() { + None | Some("OK") | Some("SOUNDLIKE") => Ok(v), + _ => Err("Akinator lost track of the game.".into()), + } +} + +fn read(s: &Shared, data: &Value) { + let mut g = sh(s); + if let Some(step) = data["step"].as_str().map(str::to_string).or_else(|| data["step"].as_u64().map(|n| n.to_string())) { + g.step = step; + } + if let Some(p) = data["progression"].as_str().map(str::to_string).or_else(|| data["progression"].as_f64().map(|n| n.to_string())) { + g.progression = p; + } + if data["name_proposition"].as_str().is_some_and(|n| !n.is_empty()) { + g.guess = Some(data.clone()); + g.question = None; + } else if let Some(q) = data["question"].as_str() { + g.guess = None; + g.question = Some(q.to_string()); + } +} + +async fn answer(s: &Shared, index: usize) -> Result<(), String> { + let (step, progression, sid, cm, last) = { + let g = sh(s); + (g.step.clone(), g.progression.clone(), g.sid.clone(), g.cm.to_string(), g.last_proposition.clone()) + }; + let d = post(s, "/answer", vec![("step", step), ("progression", progression), ("sid", sid), ("cm", cm), ("answer", index.to_string()), ("step_last_proposition", last)]).await?; + read(s, &d); + sh(s).number += 1; + Ok(()) +} + +async fn back(s: &Shared) -> Result<(), String> { + let (step, progression, sid, cm) = { + let g = sh(s); + (g.step.clone(), g.progression.clone(), g.sid.clone(), g.cm.to_string()) + }; + let d = post(s, "/cancel_answer", vec![("step", step), ("progression", progression), ("sid", sid), ("cm", cm)]).await?; + read(s, &d); + let mut g = sh(s); + g.number = g.number.saturating_sub(1).max(1); + Ok(()) +} + +/// The guess was wrong: carry on asking. +async fn keep_going(s: &Shared) -> Result<(), String> { + let (step, progression, sid, cm) = { + let mut g = sh(s); + g.last_proposition = g.step.clone(); + (g.step.clone(), g.progression.clone(), g.sid.clone(), g.cm.to_string()) + }; + let d = post(s, "/exclude", vec![("step", step), ("sid", sid), ("cm", cm), ("progression", progression), ("forward_answer", "1".into())]).await?; + read(s, &d); + Ok(()) +} + +pub async fn start(_state: &State, player: P, theme: Option, child_mode: bool) -> Result, String> { + let theme = theme.filter(|t| THEMES.iter().any(|x| x.0 == t)).unwrap_or_else(|| "characters".into()); + Ok(Box::new(Akinator::begin(player, &theme, child_mode).await?)) +} + +pub struct Akinator { + player: P, + theme: String, + s: Shared, +} + +impl Akinator { + async fn begin(player: P, theme: &str, child_mode: bool) -> Result { + let jar = std::env::temp_dir().join(format!("dezio-aki-{:016x}.jar", rand::random::())); + let sid = THEMES.iter().find(|t| t.0 == theme).map_or("1", |t| t.1).to_string(); + let page = fetch(&jar, "/game", &[("sid", sid.clone()), ("cm", child_mode.to_string())]).await?; + let session = Regex::new(r"localStorage\.setItem\('session', '([^']+)'").unwrap().captures(&page).map(|c| c[1].to_string()); + let step = Regex::new(r"localStorage\.setItem\('step', '([^']+)'").unwrap().captures(&page).map(|c| c[1].to_string()); + let question = Regex::new(r#"(?s)id="question-label"[^>]*>(.*?)<"#).unwrap().captures(&page).map(|c| c[1].trim().to_string()); + let (Some(session), Some(question)) = (session, question) else { + tracing::warn!("akinator start failed; the page began with: {}", page.chars().take(200).collect::().replace('\n', " ")); + let _ = std::fs::remove_file(&jar); + return Err("Akinator's site changed — the game can't start right now.".into()); + }; + let s = Arc::new(StdMutex::new(Sh { jar, sid, cm: child_mode, session, step: step.unwrap_or_else(|| "1".into()), progression: "0".into(), last_proposition: String::new(), question: Some(question), guess: None, number: 1, state: St::Question, note: None, over: false })); + Ok(Self { player, theme: theme.to_string(), s }) + } + + fn face(&self) -> String { + let g = sh(&self.s); + match g.state { + St::Won => akitude("triomphe"), + St::Lost => akitude("deception"), + St::Guess => akitude("confiant"), + St::Question => { + let progress: f64 = g.progression.parse().unwrap_or(0.0); + let face = [(15.0, "serein_2"), (40.0, "inspiration_legere"), (70.0, "concentration_intense"), (90.0, "inspiration_forte")].iter().find(|(l, _)| progress < *l).map_or("etonnement", |x| x.1); + akitude(face) + } + } + } +} + +impl Game for Akinator { + fn players(&self) -> Vec { + vec![self.player.id] + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(600) + } + + fn render(&self, t: u32) -> Rendered { + let face = self.face(); + let g = sh(&self.s); + let guess_name = g.guess.as_ref().and_then(|x| x["name_proposition"].as_str()).unwrap_or("").to_string(); + let mut card = match g.state { + St::Won => { + let mut c = Card::new(Some(WIN)).header(&[&format!("### 🧞 I knew it!\nIt's **{}**!", escape(&guess_name))], Some(&face)); + if let Some(p) = g.guess.as_ref().and_then(|x| x["photo"].as_str()).filter(|p| p.starts_with("http")) { + c = c.gallery(&[p]); + } + c + } + St::Lost => Card::new(Some(LOSE)).header(&[&format!("### 🧞 You beat me!\nI couldn't guess your {}. Well played.", self.theme.trim_end_matches('s'))], Some(&face)), + St::Guess => { + let desc = g.guess.as_ref().and_then(|x| x["description_proposition"].as_str()).unwrap_or("").to_string(); + let mut c = Card::new(Some(DRAW)).header(&[&format!("### 🧞 Is it…\n## {}", escape(&guess_name)), &escape(&desc)], Some(&face)); + if let Some(p) = g.guess.as_ref().and_then(|x| x["photo"].as_str()).filter(|p| p.starts_with("http")) { + c = c.gallery(&[p]); + } + c.row(vec![btn(t, "yes", "Yes!", "✅", ButtonStyle::Success, false), btn(t, "no", "No", "❌", ButtonStyle::Danger, false)]) + } + St::Question => { + let progress: f64 = g.progression.parse().unwrap_or(0.0); + let filled = ((progress / 10.0) as usize).min(10); + let bar = format!("{}{}", "▰".repeat(filled), "▱".repeat(10 - filled)); + let mut c = Card::new(Some(BLURPLE)).header(&[&format!("### 🧞 Question {}\n**{}**", g.number, escape(g.question.as_deref().unwrap_or("…"))), &format!("-# {bar} {progress:.0}% sure")], Some(&face)); + c = c.row(ANSWERS.iter().enumerate().map(|(i, (l, e))| btn(t, &format!("a{i}"), l, e, if i < 2 { ButtonStyle::Primary } else { ButtonStyle::Secondary }, g.over)).collect()); + c.row(vec![btn(t, "back", "Back", "↩️", ButtonStyle::Secondary, g.number <= 1 || g.over), btn(t, "stop", "Stop", "⏹️", ButtonStyle::Danger, g.over)]) + } + }; + if let Some(n) = &g.note { + card = card.footer(n); + } + card = card.footer(&format!("Thinking of: {} · playing: {}", self.theme, self.player.name())); + if g.over { + card = card.row(vec![again(t, "Play again")]); + } + card.into() + } + + fn click(&mut self, _: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + let s = self.s.clone(); + let finish = |s: &Shared, result: Result<(), String>| { + let mut g = sh(s); + g.note = result.err().map(|e| format!("⚠️ {e}")); + if g.guess.is_some() && g.state == St::Question { + g.state = St::Guess; + } + }; + match action { + a if a.starts_with('a') && a.len() == 2 => { + let Some(i) = a[1..].parse::().ok().filter(|i| *i < 5) else { return Reply::Ignore }; + if sh(&s).over || sh(&s).state != St::Question { + return Reply::Ignore; + } + Reply::Defer(async move { + let r = answer(&s, i).await; + finish(&s, r); + Reply::Update + }.boxed()) + } + "back" => Reply::Defer(async move { + let r = back(&s).await; + finish(&s, r); + Reply::Update + }.boxed()), + "yes" => { + let mut g = sh(&s); + g.state = St::Won; + g.over = true; + Reply::Update + } + "no" => { + let hopeless = sh(&s).guess.as_ref().is_some_and(|g| g["no_question"].as_str() == Some("1") || g["no_question"].as_u64() == Some(1)); + if hopeless { + let mut g = sh(&s); + g.state = St::Lost; + g.over = true; + return Reply::Update; + } + sh(&s).state = St::Question; + Reply::Defer(async move { + let r = keep_going(&s).await; + finish(&s, r); + Reply::Update + }.boxed()) + } + "stop" => { + let mut g = sh(&s); + g.state = St::Lost; + g.over = true; + Reply::Update + } + "again" => { + let (player, theme, cm) = (self.player.clone(), self.theme.clone(), sh(&s).cm); + Reply::Defer(async move { + match Akinator::begin(player, &theme, cm).await { + Ok(g) => Reply::Replace(Box::new(g)), + Err(e) => Reply::Private(format!("⚠️ {e}")), + } + }.boxed()) + } + _ => Reply::Ignore, + } + } + + fn is_over(&self) -> bool { + sh(&self.s).over + } + + fn abandon(&mut self) { + let mut g = sh(&self.s); + g.state = St::Lost; + g.over = true; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `cargo test aki_live -- --ignored --nocapture` — plays a few questions against the real site. + #[tokio::test] + #[ignore = "needs the internet"] + async fn aki_live_asks_questions() { + let p = P { id: 1, name: "me".into(), bot: false }; + let mut g = Akinator::begin(p, "characters", true).await.expect("start"); + let first = { sh(&g.s).question.clone() }; + println!("first question: {first:?}"); + assert!(first.is_some_and(|q| q.len() > 5)); + for i in 0..3 { + let r = answer(&g.s, i % 2).await; + assert!(r.is_ok(), "{r:?}"); + let now = sh(&g.s); + println!("q{}: {:?} ({}%)", now.number, now.question, now.progression); + } + back(&g.s).await.unwrap(); + g.abandon(); + assert!(g.is_over()); + } + + #[test] + fn the_card_has_the_five_answers() { + let s: Shared = Arc::new(StdMutex::new(Sh { jar: std::path::PathBuf::new(), sid: "1".into(), cm: true, session: "x".into(), step: "1".into(), progression: "35.5".into(), last_proposition: String::new(), question: Some("Is your character real?".into()), guess: None, number: 2, state: St::Question, note: None, over: false })); + let g = Akinator { player: P { id: 1, name: "me".into(), bot: false }, theme: "characters".into(), s }; + let json = serde_json::to_string(&g.render(3).card.build()).unwrap(); + for i in 0..5 { + assert!(json.contains(&format!("gm:3:a{i}")), "a{i}"); + } + assert!(json.contains("Is your character real?") && json.contains("inspiration_legere") && json.contains("gm:3:back")); + } +} diff --git a/src/commands/games/casino.rs b/src/commands/games/casino.rs new file mode 100644 index 0000000..71aca51 --- /dev/null +++ b/src/commands/games/casino.rs @@ -0,0 +1,991 @@ +//! Casino: play-money coins and four games. +//! +//! * `D!bal` · `/balance` — your coins and stats (or someone else's). `D!richest` — leaderboard. +//! * `D!give @user 50` · `/donate`, `D!loan` · `/loan` (100 coins when you're broke, hourly). +//! * `D!cf 50 heads` · `D!bj 100` · `D!slots 20` · `D!rl 50 red` · `/gamble` — bets accept `all`, `half`, `25%`, `10k`, `1.5m`. +//! +//! The bet leaves your wallet when the game starts and the winnings come back when it ends, so you can't bet coins +//! you don't have (even with several games open). Every game has a **Play again** button. +//! State: data/casino.json {"players": {id: {money, stats…}}, "loans": {id: time}}. +use super::*; +use crate::converters::thousands; +use crate::storage::JsonStore; +use crate::ui::{Card, GOLD, GREEN, RED}; +use crate::{pager, paths}; +use rand::RngExt as _; +use std::time::{SystemTime, UNIX_EPOCH}; + +const STARTING: i64 = 100; +const LOAN_AMOUNT: i64 = 100; +const LOAN_COOLDOWN: f64 = 3600.0; +const CASINO: u32 = 0x9B59B6; + +pub fn fmt(coins: i64) -> String { + format!("{} 🪙", thousands(coins.max(0) as u64)) +} + +fn now() -> f64 { + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64()) +} + +/// `50`, `all`, `half`, `25%`, `10k`, `1.5m`… +pub fn parse_bet(text: &str, balance: i64) -> Result { + let word = text.trim().to_lowercase().replace([',', '_'], ""); + if word.is_empty() { + return Err("How much? e.g. `50`, `all`, `half`, `25%` or `10k`.".into()); + } + let amount = if matches!(word.as_str(), "all" | "max" | "allin" | "all-in" | "everything") { + balance + } else if word == "half" { + balance / 2 + } else if let Some(p) = word.strip_suffix('%').and_then(|n| n.parse::().ok()) { + (balance as f64 * p.min(100.0) / 100.0) as i64 + } else { + let (num, mult) = match word.chars().last() { + Some('k') => (&word[..word.len() - 1], 1e3), + Some('m') => (&word[..word.len() - 1], 1e6), + Some('b') => (&word[..word.len() - 1], 1e9), + _ => (word.as_str(), 1.0), + }; + match num.parse::() { + Ok(n) if n >= 0.0 && n.is_finite() && !num.starts_with('+') => (n * mult) as i64, + _ => return Err(format!("`{text}` isn't an amount — try `50`, `all`, `half`, `25%` or `10k`.")), + } + }; + if amount < 1 { + return Err(if balance > 0 { "You need to bet at least 1 coin.".into() } else { "You're broke — grab a `loan` first!".into() }); + } + Ok(amount) +} + +// ---- the wallet --------------------------------------------------------------------------------------------- + +fn store() -> &'static Arc { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| JsonStore::open(paths::data(&["casino.json"]))) +} + +fn with_player(user: u64, f: impl FnOnce(&mut serde_json::Map) -> R) -> R { + store().update(|all| { + let players = all.entry("players".to_string()).or_insert_with(|| json!({})).as_object_mut().unwrap(); + let p = players.entry(user.to_string()).or_insert_with(|| json!({"money": STARTING})).as_object_mut().unwrap(); + f(p) + }) +} + +pub fn balance(user: u64) -> i64 { + store().get("players").and_then(|p| p[user.to_string()]["money"].as_i64()).unwrap_or(STARTING) +} + +pub fn add(user: u64, amount: i64) -> i64 { + with_player(user, |p| { + let m = (p.get("money").and_then(Value::as_i64).unwrap_or(STARTING) + amount).max(0); + p.insert("money".into(), json!(m)); + m + }) +} + +/// Take `amount` out of the wallet. False if it isn't there. +pub fn take(user: u64, amount: i64) -> bool { + if amount < 1 || balance(user) < amount { + return false; + } + add(user, -amount); + true +} + +fn record(user: u64, bet: i64, payout: i64) { + with_player(user, |p| { + let n = |p: &serde_json::Map, k: &str| p.get(k).and_then(Value::as_i64).unwrap_or(0); + p.insert("games".into(), json!(n(p, "games") + 1)); + p.insert("wagered".into(), json!(n(p, "wagered") + bet)); + if payout - bet > 0 { + p.insert("wins".into(), json!(n(p, "wins") + 1)); + p.insert("best".into(), json!(n(p, "best").max(payout - bet))); + } + }); +} + +fn top(ids: Option<&HashSet>, limit: usize) -> Vec<(u64, i64)> { + let mut rows: Vec<(u64, i64)> = store().get("players").and_then(|p| p.as_object().cloned()).unwrap_or_default().iter().filter_map(|(k, v)| Some((k.parse().ok()?, v["money"].as_i64().unwrap_or(0)))).filter(|(u, _)| ids.is_none_or(|s| s.contains(u))).collect(); + rows.sort_by_key(|(_, m)| std::cmp::Reverse(*m)); + rows.truncate(limit); + rows +} + +// ---- shared game plumbing ----------------------------------------------------------------------------------- + +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Coin, + Blackjack, + Slots, + Roulette, +} + +/// What every bet needs: who, how much, and settling it exactly once. +struct Core { + player: P, + bet: i64, + done: bool, + payout: i64, + final_balance: Option, + replayed: bool, + /// When the spinning animation ends (None = not animating). + reveal_at: Option, +} + +impl Core { + fn new(player: P, bet: i64) -> Self { + Self { player, bet, done: false, payout: 0, final_balance: None, replayed: false, reveal_at: None } + } + + fn finish(&mut self, payout: i64) { + if self.done { + return; + } + self.done = true; + self.payout = payout; + if payout > 0 { + add(self.player.id, payout); + } + record(self.player.id, self.bet, payout); + self.final_balance = Some(balance(self.player.id)); + } + + fn animate(&mut self, seconds: f64) { + self.reveal_at = Some(Instant::now() + Duration::from_secs_f64(seconds)); + } + + fn spinning(&self) -> bool { + self.reveal_at.is_some() + } + + fn result_line(&self) -> String { + let net = self.payout - self.bet; + let change = if net > 0 { format!("+{}", thousands(net as u64)) } else if net < 0 { format!("-{}", thousands((-net) as u64)) } else { "±0".to_string() }; + format!("{change} coins · balance {}", fmt(self.final_balance.unwrap_or_else(|| balance(self.player.id)))) + } + + /// The footer and the Play-again button once the game is settled (and not mid-animation). + fn finish_card(&self, card: Card, t: u32) -> Card { + if !self.done || self.spinning() { + return card; + } + card.footer(&self.result_line()).row(vec![btn(t, "again", &format!("Play again ({})", thousands(self.bet as u64)), "🔁", ButtonStyle::Success, self.replayed)]) + } + + /// "Play again": take the bet, then a new game starts in a fresh message. + fn again(&mut self, make: impl FnOnce(P, i64) -> Box) -> Reply { + if self.replayed { + return Reply::Ignore; + } + if balance(self.player.id) < self.bet { + return Reply::Private(format!("❌ You only have {}.", fmt(balance(self.player.id)))); + } + if !take(self.player.id, self.bet) { + return Reply::Private(format!("❌ You only have {}.", fmt(balance(self.player.id)))); + } + self.replayed = true; + Reply::Spawn(make(self.player.clone(), self.bet)) + } + + fn allowed(&self, who: u64) -> Result<(), String> { + if who == self.player.id { Ok(()) } else { Err("This isn't your game — start your own with `/gamble`.".into()) } + } +} + +// ---- coin flip --------------------------------------------------------------------------------------------------------- + +pub struct CoinFlip { + c: Core, + side: Option<&'static str>, + result: Option<&'static str>, +} + +impl CoinFlip { + fn new(player: P, bet: i64, side: Option<&'static str>) -> Self { + let mut g = Self { c: Core::new(player, bet), side, result: None }; + if g.side.is_some() { + g.flip(); + } + g + } + + fn flip(&mut self) { + let r = if rand::rng().random_bool(0.5) { "heads" } else { "tails" }; + self.result = Some(r); + self.c.finish(if Some(r) == self.side { self.c.bet * 2 } else { 0 }); + self.c.animate(1.2); + } +} + +impl Game for CoinFlip { + fn players(&self) -> Vec { + vec![self.c.player.id] + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(120) + } + + fn deadline(&self) -> Option { + self.c.reveal_at + } + + fn on_deadline(&mut self) { + self.c.reveal_at = None; + } + + fn render(&self, t: u32) -> Rendered { + let title = format!("### 🪙 Coin flip · {}", fmt(self.c.bet)); + if self.c.spinning() { + return Card::new(Some(GOLD)).text(&format!("{title}\n{} picked **{}**…\n# 🪙 *flipping…*", self.c.player.name(), self.side.unwrap_or("?"))).into(); + } + let Some(result) = self.result else { + return Card::new(Some(CASINO)).text(&format!("{title}\nHeads or tails? Win pays **2×**.")).row(vec![btn(t, "heads", "Heads", "👑", ButtonStyle::Primary, false), btn(t, "tails", "Tails", "🦅", ButtonStyle::Primary, false)]).into(); + }; + let won = Some(result) == self.side; + let card = Card::new(Some(if won { GREEN } else { RED })).text(&format!("{title}\nYou picked **{}** — it landed **{result}** {}\n{}", self.side.unwrap_or("?"), if result == "heads" { "👑" } else { "🦅" }, if won { "🎉 **You win!**" } else { "😢 **You lose.**" })); + self.c.finish_card(card, t).into() + } + + fn click(&mut self, who: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + match action { + "heads" | "tails" => { + if self.result.is_some() { + return Reply::Ignore; + } + self.side = Some(if action == "heads" { "heads" } else { "tails" }); + self.flip(); + Reply::Update + } + "again" => { + let side = self.side; + self.c.again(|p, b| Box::new(CoinFlip::new(p, b, side))) + } + _ => { + let _ = who; + Reply::Ignore + } + } + } + + fn allowed(&self, who: u64, _: &str) -> Result<(), String> { + self.c.allowed(who) + } + + fn is_over(&self) -> bool { + self.c.done && !self.c.spinning() + } + + fn abandon(&mut self) { + if !self.c.done { + self.c.finish(self.c.bet); // nothing played: refund + } + } + + fn discard(&mut self) { + if !self.c.done { + add(self.c.player.id, self.c.bet); + self.c.done = true; + } + } +} + +// ---- blackjack ------------------------------------------------------------------------------------------------------------- + +const SUITS: [&str; 4] = ["♠", "♥", "♦", "♣"]; +const RANKS: [&str; 13] = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]; +type CardT = (&'static str, &'static str); + +fn hand_value(hand: &[CardT]) -> i32 { + let mut v: i32 = hand.iter().map(|(r, _)| match *r { "A" => 11, "J" | "Q" | "K" | "10" => 10, n => n.parse().unwrap_or(0) }).sum(); + let mut aces = hand.iter().filter(|(r, _)| *r == "A").count(); + while v > 21 && aces > 0 { + v -= 10; + aces -= 1; + } + v +} + +fn show(hand: &[CardT], hide_second: bool) -> String { + hand.iter().enumerate().map(|(i, (r, s))| if hide_second && i == 1 { "`??`".to_string() } else { format!("`{r}{s}`") }).collect::>().join(" ") +} + +pub struct Blackjack { + c: Core, + deck: Vec, + hand: Vec, + dealer: Vec, + outcome: Option<&'static str>, + doubled: bool, +} + +impl Blackjack { + fn new(player: P, bet: i64) -> Self { + use rand::seq::SliceRandom; + let mut deck: Vec = (0..4).flat_map(|_| SUITS.iter().flat_map(|s| RANKS.iter().map(move |r| (*r, *s)))).collect(); + deck.shuffle(&mut rand::rng()); + let hand = vec![deck.pop().unwrap(), deck.pop().unwrap()]; + let dealer = vec![deck.pop().unwrap(), deck.pop().unwrap()]; + let mut g = Self { c: Core::new(player, bet), deck, hand, dealer, outcome: None, doubled: false }; + if hand_value(&g.hand) == 21 { + g.settle(); + } + g + } + + fn settle(&mut self) { + let player = hand_value(&self.hand); + let natural = player == 21 && self.hand.len() == 2; + let (outcome, payout) = if player > 21 { + ("bust", 0) + } else { + while hand_value(&self.dealer) < 17 { + let c = self.deck.pop().unwrap(); + self.dealer.push(c); + } + let dealer = hand_value(&self.dealer); + let dealer_natural = dealer == 21 && self.dealer.len() == 2; + if natural && !dealer_natural { + ("blackjack", self.c.bet * 5 / 2) + } else if dealer > 21 { + ("dealer bust", self.c.bet * 2) + } else if player > dealer { + ("win", self.c.bet * 2) + } else if player == dealer { + ("push", self.c.bet) + } else { + ("lose", 0) + } + }; + self.outcome = Some(outcome); + self.c.finish(payout); + } +} + +impl Game for Blackjack { + fn players(&self) -> Vec { + vec![self.c.player.id] + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(180) + } + + fn render(&self, t: u32) -> Rendered { + let player = hand_value(&self.hand); + let done = self.outcome.is_some(); + let dealer_text = if done { format!("{} = **{}**", show(&self.dealer, false), hand_value(&self.dealer)) } else { format!("{} = **?**", show(&self.dealer, true)) }; + let (accent, message) = match self.outcome { + Some("blackjack") => (GREEN, "🃏 **Blackjack!** Pays 2.5×"), + Some("dealer bust") => (GREEN, "🎉 **Dealer busts — you win!**"), + Some("win") => (GREEN, "🎉 **You win!**"), + Some("push") => (GOLD, "🤝 **Push** — bet returned"), + Some("lose") => (RED, "😢 **Dealer wins.**"), + Some(_) => (RED, "💥 **Bust!** Over 21."), + None => (CASINO, ""), + }; + let mut card = Card::new(Some(accent)).text(&format!("### 🃏 Blackjack · {}{}\n**You:** {} = **{player}**\n**Dealer:** {dealer_text}", fmt(self.c.bet), if self.doubled { " (doubled)" } else { "" }, show(&self.hand, false))); + if done { + card = self.c.finish_card(card.text(message), t); + } else { + let cant_double = self.hand.len() != 2 || balance(self.c.player.id) < self.c.bet; + card = card.row(vec![btn(t, "hit", "Hit", "🃏", ButtonStyle::Primary, false), btn(t, "stand", "Stand", "✋", ButtonStyle::Secondary, false), btn(t, "double", "Double", "✖️", ButtonStyle::Secondary, cant_double)]).footer("Dealer stands on 17 · blackjack pays 2.5× · double = one more card, twice the bet"); + } + card.into() + } + + fn click(&mut self, _: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + match action { + "hit" => { + if self.outcome.is_some() { + return Reply::Ignore; + } + let c = self.deck.pop().unwrap(); + self.hand.push(c); + if hand_value(&self.hand) >= 21 { + self.settle(); + } + Reply::Update + } + "stand" => { + if self.outcome.is_none() { + self.settle(); + } + Reply::Update + } + "double" => { + if self.outcome.is_some() || self.hand.len() != 2 { + return Reply::Ignore; + } + if !take(self.c.player.id, self.c.bet) { + return Reply::Private("❌ You can't cover the double.".into()); + } + self.c.bet *= 2; + self.doubled = true; + let c = self.deck.pop().unwrap(); + self.hand.push(c); + self.settle(); + Reply::Update + } + "again" => { + let bet = if self.doubled { self.c.bet / 2 } else { self.c.bet }; + self.c.bet = bet; + self.c.again(|p, b| Box::new(Blackjack::new(p, b))) + } + _ => Reply::Ignore, + } + } + + fn allowed(&self, who: u64, _: &str) -> Result<(), String> { + self.c.allowed(who) + } + + fn is_over(&self) -> bool { + self.outcome.is_some() + } + + fn abandon(&mut self) { + if self.outcome.is_none() { + self.settle(); // idle: stand + } + } + + fn discard(&mut self) { + if !self.c.done { + add(self.c.player.id, self.c.bet); + self.c.done = true; + self.outcome = Some("lose"); + } + } +} + +// ---- slots ------------------------------------------------------------------------------------------------------------------- + +/// symbol, weight, three-of-a-kind multiplier +const SLOT_SYMBOLS: [(&str, u32, i64); 8] = [("🍒", 15, 5), ("🍋", 15, 5), ("🍇", 12, 8), ("🍉", 12, 8), ("🍎", 10, 10), ("🔔", 8, 15), ("💎", 5, 30), ("7️⃣", 3, 77)]; +const TWO_MATCH: i64 = 2; + +fn pick_symbol() -> &'static str { + let total: u32 = SLOT_SYMBOLS.iter().map(|s| s.1).sum(); + let mut roll = rand::rng().random_range(0..total); + for (s, w, _) in SLOT_SYMBOLS { + if roll < w { + return s; + } + roll -= w; + } + SLOT_SYMBOLS[0].0 +} + +fn slot_payout(reels: &[&str; 3], bet: i64) -> i64 { + let [a, b, c] = *reels; + if a == b && b == c { + bet * SLOT_SYMBOLS.iter().find(|s| s.0 == a).map_or(0, |s| s.2) + } else if a == b || b == c || a == c { + bet * TWO_MATCH + } else { + 0 + } +} + +pub struct Slots { + c: Core, + reels: Option<[&'static str; 3]>, +} + +impl Slots { + fn new(player: P, bet: i64) -> Self { + Self { c: Core::new(player, bet), reels: None } + } +} + +impl Game for Slots { + fn players(&self) -> Vec { + vec![self.c.player.id] + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(120) + } + + fn deadline(&self) -> Option { + self.c.reveal_at + } + + fn on_deadline(&mut self) { + self.c.reveal_at = None; + } + + fn render(&self, t: u32) -> Rendered { + let title = format!("### 🎰 Slots · {}", fmt(self.c.bet)); + if self.c.spinning() { + let reels: Vec<&str> = (0..3).map(|_| pick_symbol()).collect(); + return Card::new(Some(GOLD)).text(&format!("{title}\n# {}\n*spinning…*", reels.join(" "))).into(); + } + let Some([a, b, c]) = self.reels else { + let table = SLOT_SYMBOLS.iter().map(|(s, _, m)| format!("{s}×3 = {m}×")).collect::>().join(" · "); + return Card::new(Some(CASINO)).text(&format!("{title}\n# ❔ ❔ ❔")).footer(&format!("{table} · any two = {TWO_MATCH}×")).row(vec![btn(t, "spin", "Spin!", "🎰", ButtonStyle::Primary, false)]).into(); + }; + let line = if a == b && b == c { + format!("🎉 **JACKPOT!** Three {a} pays **{}×**", self.c.payout / self.c.bet.max(1)) + } else if self.c.payout > 0 { + format!("✨ **Two of a kind!** Pays {TWO_MATCH}×") + } else { + "😢 No match this time.".to_string() + }; + let accent = if a == b && b == c { GOLD } else if self.c.payout > 0 { GREEN } else { RED }; + self.c.finish_card(Card::new(Some(accent)).text(&format!("{title}\n# {a} {b} {c}\n{line}")), t).into() + } + + fn click(&mut self, _: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + match action { + "spin" => { + if self.reels.is_some() { + return Reply::Ignore; + } + let reels = [pick_symbol(), pick_symbol(), pick_symbol()]; + self.reels = Some(reels); + self.c.finish(slot_payout(&reels, self.c.bet)); + self.c.animate(1.2); + Reply::Update + } + "again" => self.c.again(|p, b| Box::new(Slots::new(p, b))), + _ => Reply::Ignore, + } + } + + fn allowed(&self, who: u64, _: &str) -> Result<(), String> { + self.c.allowed(who) + } + + fn is_over(&self) -> bool { + self.c.done && !self.c.spinning() + } + + fn abandon(&mut self) { + if !self.c.done { + self.c.finish(self.c.bet); + } + } + + fn discard(&mut self) { + if !self.c.done { + add(self.c.player.id, self.c.bet); + self.c.done = true; + } + } +} + +// ---- roulette --------------------------------------------------------------------------------------------------------------------- + +/// colour, emoji, payout multiplier, button style +const ROULETTE: [(&str, &str, i64, ButtonStyle); 3] = [("red", "🔴", 2, ButtonStyle::Danger), ("black", "⚫", 2, ButtonStyle::Secondary), ("green", "🟢", 14, ButtonStyle::Success)]; + +fn colour_of(n: u32) -> &'static str { + if n == 0 { "green" } else if n <= 7 { "red" } else { "black" } +} + +fn roulette_row(colour: &str) -> &'static (&'static str, &'static str, i64, ButtonStyle) { + ROULETTE.iter().find(|r| r.0 == colour).unwrap_or(&ROULETTE[0]) +} + +pub struct Roulette { + c: Core, + colour: Option<&'static str>, + number: Option, +} + +impl Roulette { + fn new(player: P, bet: i64, colour: Option<&'static str>) -> Self { + let mut g = Self { c: Core::new(player, bet), colour, number: None }; + if g.colour.is_some() { + g.spin(); + } + g + } + + fn spin(&mut self) { + let n = rand::rng().random_range(0..15u32); + self.number = Some(n); + let colour = self.colour.unwrap_or("red"); + self.c.finish(if colour_of(n) == colour { self.c.bet * roulette_row(colour).2 } else { 0 }); + self.c.animate(1.5); + } +} + +impl Game for Roulette { + fn players(&self) -> Vec { + vec![self.c.player.id] + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(120) + } + + fn deadline(&self) -> Option { + self.c.reveal_at + } + + fn on_deadline(&mut self) { + self.c.reveal_at = None; + } + + fn render(&self, t: u32) -> Rendered { + let title = format!("### 🎡 Roulette · {}", fmt(self.c.bet)); + if self.c.spinning() { + let colour = self.colour.unwrap_or("red"); + return Card::new(Some(GOLD)).text(&format!("{title}\nOn {} **{colour}**…\n# 🎡 *spinning…*", roulette_row(colour).1)).into(); + } + let Some(n) = self.number else { + let buttons = ROULETTE.iter().map(|(c, e, _, s)| btn(t, c, &(c[..1].to_uppercase() + &c[1..]), e, *s, false)).collect(); + return Card::new(Some(CASINO)).text(&format!("{title}\nPick a colour: 🔴 red 2× · ⚫ black 2× · 🟢 green 14×")).footer("15 pockets: 0 is green, 1–7 red, 8–14 black").row(buttons).into(); + }; + let colour = self.colour.unwrap_or("red"); + let landed = colour_of(n); + let won = landed == colour; + let line = if won { format!("🎉 **You win {}×!**", roulette_row(landed).2) } else { "😢 **You lose.**".to_string() }; + self.c.finish_card(Card::new(Some(if won { GREEN } else { RED })).text(&format!("{title}\nYou bet {} **{colour}** — the ball landed on {} **{n}**\n{line}", roulette_row(colour).1, roulette_row(landed).1)), t).into() + } + + fn click(&mut self, _: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + if let Some(r) = ROULETTE.iter().find(|r| r.0 == action) { + if self.number.is_some() { + return Reply::Ignore; + } + self.colour = Some(r.0); + self.spin(); + return Reply::Update; + } + if action == "again" { + let colour = self.colour; + return self.c.again(|p, b| Box::new(Roulette::new(p, b, colour))); + } + Reply::Ignore + } + + fn allowed(&self, who: u64, _: &str) -> Result<(), String> { + self.c.allowed(who) + } + + fn is_over(&self) -> bool { + self.c.done && !self.c.spinning() + } + + fn abandon(&mut self) { + if !self.c.done { + self.c.finish(self.c.bet); + } + } + + fn discard(&mut self) { + if !self.c.done { + add(self.c.player.id, self.c.bet); + self.c.done = true; + } + } +} + +// ---- commands ----------------------------------------------------------------------------------------------------------------------- + +fn side_of(s: &str) -> Option<&'static str> { + match s.to_lowercase().as_str() { + "h" | "heads" | "head" => Some("heads"), + "t" | "tails" | "tail" => Some("tails"), + _ => None, + } +} + +fn colour_pick(s: &str) -> Option<&'static str> { + match s.to_lowercase().as_str() { + "r" | "red" => Some("red"), + "b" | "black" => Some("black"), + "g" | "green" | "0" => Some("green"), + _ => None, + } +} + +async fn start(ctx: &Arc, kind: Kind, amount: &str, choice: &str) -> Result<()> { + let me = P { id: ctx.user_id.get(), name: display_name_of(&ctx.state, ctx.guild_id, ctx.user_id).await, bot: false }; + let bal = balance(me.id); + let bet = match parse_bet(amount, bal) { + Ok(b) => b, + Err(e) => return ctx.fail(&format!("❌ {e}")).await, + }; + if !take(me.id, bet) { + return ctx.fail(&format!("❌ You only have {}.{}", fmt(bal), if bal == 0 { " Grab a `loan`!" } else { "" })).await; + } + let game: Box = match kind { + Kind::Coin => Box::new(CoinFlip::new(me, bet, side_of(choice))), + Kind::Blackjack => Box::new(Blackjack::new(me, bet)), + Kind::Slots => Box::new(Slots::new(me, bet)), + Kind::Roulette => Box::new(Roulette::new(me, bet, colour_pick(choice))), + }; + let user = ctx.user_id.get(); + let result = launch(ctx, game, None).await; + if result.is_err() { + add(user, bet); // the game never showed up: give the bet back + } + result +} + +async fn gamble(ctx: Arc) -> Result<()> { + let kind = match ctx.args.str("game").unwrap_or("") { + "coinflip" => Kind::Coin, + "blackjack" => Kind::Blackjack, + "slots" => Kind::Slots, + "roulette" => Kind::Roulette, + _ => bail_user!("Pick a game from the list."), + }; + start(&ctx, kind, ctx.args.str("amount").unwrap_or(""), ctx.args.str("choice").unwrap_or("")).await +} + +async fn cf(ctx: Arc) -> Result<()> { + let (a, s) = (ctx.args.str("amount").unwrap_or("").to_string(), ctx.args.str("side").unwrap_or("").to_string()); + start(&ctx, Kind::Coin, &a, &s).await +} + +async fn bj(ctx: Arc) -> Result<()> { + let a = ctx.args.str("amount").unwrap_or("").to_string(); + start(&ctx, Kind::Blackjack, &a, "").await +} + +async fn slots(ctx: Arc) -> Result<()> { + let a = ctx.args.str("amount").unwrap_or("").to_string(); + start(&ctx, Kind::Slots, &a, "").await +} + +async fn rl(ctx: Arc) -> Result<()> { + let (a, c) = (ctx.args.str("amount").unwrap_or("").to_string(), ctx.args.str("colour").unwrap_or("").to_string()); + start(&ctx, Kind::Roulette, &a, &c).await +} + +async fn balance_cmd(ctx: Arc) -> Result<()> { + let target = if ctx.is_slash() { + ctx.args.user("user").unwrap_or(ctx.user_id) + } else { + match ctx.args.str("user") { + Some(w) => ctx.guild_id.and_then(|g| find_member(&ctx.state.cache, g, w)).or_else(|| ctx.args.user("user")).ok_or_else(|| crate::error::UserError::new(format!("I couldn't find `{}`.", escape(w))))?, + None => ctx.reply_to.unwrap_or(ctx.user_id), + } + }; + ctx.defer().await?; + let name = display_name_of(&ctx.state, ctx.guild_id, target).await; + let money = balance(target.get()); + let stats = store().get("players").map(|p| p[target.get().to_string()].clone()).unwrap_or(Value::Null); + let rank = top(None, 10_000).iter().position(|(u, _)| *u == target.get()).map(|i| i + 1); + let mut lines = vec![format!("## {}", fmt(money))]; + let games = stats["games"].as_i64().unwrap_or(0); + if games > 0 { + lines.push(format!("🎲 {} games · {:.0}% won · {} wagered", thousands(games as u64), stats["wins"].as_f64().unwrap_or(0.0) / games as f64 * 100.0, thousands(stats["wagered"].as_u64().unwrap_or(0)))); + if let Some(best) = stats["best"].as_u64().filter(|b| *b > 0) { + lines.push(format!("🏆 Best win: +{}", thousands(best))); + } + } + if let Some(r) = rank { + lines.push(format!("-# #{r} richest overall")); + } + let avatar = super::super::media::avatar(&ctx.state, target, 128).await; + ctx.reply(Card::new(Some(CASINO)).header(&[&format!("### 💰 {}'s wallet", escape(&name)), &lines.join("\n")], Some(&avatar)).build()).await +} + +async fn donate(ctx: Arc) -> Result<()> { + let Some(target) = (if ctx.is_slash() { ctx.args.user("user") } else { ctx.args.str("user").and_then(|w| ctx.guild_id.and_then(|g| find_member(&ctx.state.cache, g, w)).or_else(|| ctx.args.user("user"))) }) else { bail_user!("Who gets the coins? `give @user 50`") }; + if target == ctx.user_id || ctx.state.cache.user(target).is_some_and(|u| u.bot) { + return ctx.fail("❌ You can't give coins to bots or yourself.").await; + } + let coins = match parse_bet(ctx.args.str("amount").unwrap_or(""), balance(ctx.user_id.get())) { + Ok(c) => c, + Err(e) => return ctx.fail(&format!("❌ {e}")).await, + }; + if !take(ctx.user_id.get(), coins) { + return ctx.fail(&format!("❌ You only have {}.", fmt(balance(ctx.user_id.get())))).await; + } + add(target.get(), coins); + ctx.reply(Card::new(Some(GREEN)).text(&format!("💸 <@{}> gave **{}** to <@{target}>\n-# You have {} left", ctx.user_id, fmt(coins), fmt(balance(ctx.user_id.get())))).build()).await +} + +async fn loan(ctx: Arc) -> Result<()> { + let me = ctx.user_id.get(); + let bal = balance(me); + if bal > 0 { + return ctx.fail(&format!("❌ Loans are for broke people — you still have {}.", fmt(bal))).await; + } + let last = store().get("loans").and_then(|l| l[me.to_string()].as_f64()).unwrap_or(0.0); + let wait = LOAN_COOLDOWN - (now() - last); + if wait > 0.0 { + return ctx.fail(&format!("⏳ Next loan .", (now() + wait) as u64)).await; + } + add(me, LOAN_AMOUNT); + store().update(|all| { + all.entry("loans".to_string()).or_insert_with(|| json!({})).as_object_mut().unwrap().insert(me.to_string(), json!(now())); + }); + ctx.reply(Card::new(Some(GREEN)).text(&format!("🏦 **Loan granted:** {}. Spend it wisely!", fmt(LOAN_AMOUNT))).build()).await +} + +async fn richest(ctx: Arc) -> Result<()> { + let everywhere = ctx.guild_id.is_none() || matches!(ctx.args.str("scope").map(str::to_lowercase).as_deref(), Some("global" | "all" | "everyone")); + let ids: Option> = if everywhere { None } else { ctx.guild_id.and_then(|g| ctx.state.cache.guild_members(g)).map(|m| m.iter().map(|u| u.get()).collect()) }; + let rows = top(ids.as_ref(), 50); + if rows.is_empty() { + return ctx.say("Nobody here has played yet!").await; + } + let medals = ["🥇", "🥈", "🥉"]; + let lines: Vec = rows.iter().enumerate().map(|(i, (u, m))| format!("{} <@{u}> — {}", medals.get(i).map_or(format!("`{:>2}.`", i + 1), |s| s.to_string()), fmt(*m))).collect(); + let guild = ctx.guild_id.and_then(|g| ctx.state.cache.guild(g).map(|g| g.name().to_string())).unwrap_or_default(); + let title = format!("### 🏆 Richest players{}", if everywhere { String::new() } else { format!(" in {}", escape(&guild)) }); + let pages: Vec = lines.chunks(10).map(|chunk| { + let card = Card::new(Some(GOLD)).text(&format!("{title}\n{}", chunk.join("\n"))); + pager::fixed(card) + }).collect(); + pager::start(&ctx, pages, Duration::from_secs(300)).await +} + +fn suggest_choice(_: Arc, _focused: String, current: String, _: Option>, _: Id) -> BoxFuture<'static, Vec<(String, String)>> { + async move { + let current = current.to_lowercase(); + ["heads", "tails", "red", "black", "green"].iter().filter(|o| o.starts_with(¤t)).map(|o| (o.to_string(), o.to_string())).collect() + } + .boxed() +} + +pub fn commands() -> Vec { + vec![ + Command::new("balance", "casino", "Show your coins, games played, win rate and best win — or someone else's.", |c| balance_cmd(c).boxed()) + .aliases(&["bal", "money", "cash", "wallet"]) + .usage("[@user]") + .opt(Opt::opt("user", "Whose balance to show", OptKind::User)), + Command::new("donate", "casino", "Give coins to someone: `give @user 50` (also `all`, `half`, `10k`).", |c| donate(c).boxed()) + .aliases(&["give", "send", "pay"]) + .usage("<@user> ") + .opt(Opt::req("user", "Who gets the coins", OptKind::User)) + .opt(Opt::req("amount", "How many (e.g. 50, half, all, 10k)", OptKind::String)), + Command::new("loan", "casino", "Get 100 coins when you have none left (once an hour).", |c| loan(c).boxed()).aliases(&["cashloan"]), + Command::new("richest", "casino", "The richest players — in this server (or everywhere in DMs). `richest global` for everyone.", |c| richest(c).boxed()) + .aliases(&["leaderboard", "lb", "top", "rich"]) + .usage("[global]") + .opt(Opt::opt("scope", "'global' for everyone", OptKind::String)) + .prefix_only(), + Command::new("gamble", "casino", "Casino games: coin flip, blackjack, slots or roulette", |c| gamble(c).boxed()) + .usage(" [choice]") + .opt(Opt::req("game", "Which game", OptKind::String).choices(&["coinflip", "blackjack", "slots", "roulette"])) + .opt(Opt::req("amount", "Your bet (e.g. 50, half, all, 10k)", OptKind::String)) + .opt(Opt::opt("choice", "Coin flip: heads/tails · Roulette: red/black/green (optional)", OptKind::String).autocomplete()) + .suggest(suggest_choice), + Command::new("coinflip", "casino", "Double or nothing: `cf 50 heads` (or pick with the buttons).", |c| cf(c).boxed()) + .aliases(&["cf", "flip"]) + .usage(" [heads|tails]") + .opt(Opt::opt("amount", "Your bet", OptKind::String)) + .opt(Opt::opt("side", "heads or tails", OptKind::String)) + .prefix_only(), + Command::new("blackjack", "casino", "Blackjack against the dealer — hit, stand or double. Blackjack pays 2.5×.", |c| bj(c).boxed()) + .aliases(&["bj", "21"]) + .usage("") + .opt(Opt::opt("amount", "Your bet", OptKind::String)) + .prefix_only(), + Command::new("slots", "casino", "Spin the slot machine: any two match pays 2×, three of a kind up to 77×.", |c| slots(c).boxed()) + .aliases(&["slot", "spin"]) + .usage("") + .opt(Opt::opt("amount", "Your bet", OptKind::String)) + .prefix_only(), + Command::new("roulette", "casino", "Bet on a colour: red/black pay 2×, green pays 14×. `rl 50 red`.", |c| rl(c).boxed()) + .aliases(&["rl"]) + .usage(" [red|black|green]") + .opt(Opt::opt("amount", "Your bet", OptKind::String)) + .opt(Opt::opt("colour", "red, black or green", OptKind::String)) + .prefix_only(), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p(id: u64) -> P { + P { id, name: format!("p{id}"), bot: false } + } + + #[test] + fn bets_understand_words_percentages_and_suffixes() { + assert_eq!(parse_bet("50", 1000), Ok(50)); + assert_eq!(parse_bet("all", 1000), Ok(1000)); + assert_eq!(parse_bet("half", 1000), Ok(500)); + assert_eq!(parse_bet("25%", 1000), Ok(250)); + assert_eq!(parse_bet("10k", 1_000_000), Ok(10_000)); + assert_eq!(parse_bet("1.5m", 9_000_000), Ok(1_500_000)); + assert_eq!(parse_bet("1,000", 5000), Ok(1000)); + assert!(parse_bet("", 10).is_err() && parse_bet("lots", 10).is_err() && parse_bet("-5", 10).is_err()); + assert!(parse_bet("all", 0).unwrap_err().contains("broke")); + assert!(parse_bet("0", 10).unwrap_err().contains("at least")); + } + + #[test] + fn hands_count_aces_softly() { + assert_eq!(hand_value(&[("A", "♠"), ("K", "♥")]), 21); + assert_eq!(hand_value(&[("A", "♠"), ("A", "♥"), ("9", "♦")]), 21); + assert_eq!(hand_value(&[("K", "♠"), ("Q", "♥"), ("5", "♦")]), 25); + assert_eq!(hand_value(&[("A", "♠"), ("5", "♥"), ("K", "♦")]), 16); + } + + #[test] + fn slot_paytable() { + assert_eq!(slot_payout(&["7️⃣", "7️⃣", "7️⃣"], 10), 770); + assert_eq!(slot_payout(&["🍒", "🍒", "🍒"], 10), 50); + assert_eq!(slot_payout(&["🍒", "🍋", "🍒"], 10), 20); + assert_eq!(slot_payout(&["🍒", "🍋", "🍇"], 10), 0); + } + + #[test] + fn roulette_pockets() { + assert_eq!((colour_of(0), colour_of(1), colour_of(7), colour_of(8), colour_of(14)), ("green", "red", "red", "black", "black")); + } + + #[test] + fn a_bet_is_taken_once_and_paid_once() { + let id = 9_100_000_001; + store().set(id.to_string().as_str(), json!(null)); // irrelevant key, keeps the store warm + with_player(id, |p| { + p.insert("money".into(), json!(1000)); + }); + assert!(take(id, 100) && balance(id) == 900); + let mut g = CoinFlip::new(p(id), 100, Some("heads")); + g.c.reveal_at = None; + let after = balance(id); + assert!(after == 900 || after == 1100, "{after}"); + g.c.finish(0); // settling twice does nothing + assert_eq!(balance(id), after); + assert!(!take(id, 5000) && balance(id) == after); + } + + #[test] + fn dropped_games_refund() { + let id = 9_100_000_002; + with_player(id, |p| { + p.insert("money".into(), json!(500)); + }); + assert!(take(id, 200)); + let mut g = Slots::new(p(id), 200); + g.discard(); + assert_eq!(balance(id), 500); + g.discard(); + assert_eq!(balance(id), 500, "refunded only once"); + } + + #[test] + fn idle_blackjack_stands_and_idle_coinflip_refunds() { + let id = 9_100_000_003; + with_player(id, |p| { + p.insert("money".into(), json!(300)); + }); + assert!(take(id, 100)); + let mut g = CoinFlip::new(p(id), 100, None); + g.abandon(); + assert_eq!(balance(id), 300); + assert!(take(id, 100)); + let mut b = Blackjack::new(p(id), 100); + b.abandon(); + assert!(b.outcome.is_some() && b.c.done); + } +} diff --git a/src/commands/games/chess.rs b/src/commands/games/chess.rs new file mode 100644 index 0000000..9a38bf6 --- /dev/null +++ b/src/commands/games/chess.rs @@ -0,0 +1,407 @@ +//! Chess between two people. Pick a piece, then where it goes — or type a move (`Nf3`, `e2e4`, `O-O`). The board +//! image follows whoever is to move and highlights the last move. Draw offers, resigning, the draw rules, and a PGN +//! of the game at the end. +use super::*; +use crate::ui::{select_menu, Card}; +use shakmaty::fen::Fen; +use shakmaty::san::{San, SanPlus}; +use shakmaty::uci::UciMove; +use shakmaty::{CastlingMode, Chess, Color, EnPassantMode, Move, Position, Role, Square}; + +fn glyph(c: char) -> &'static str { + match c { + 'P' => "♙", 'N' => "♘", 'B' => "♗", 'R' => "♖", 'Q' => "♕", 'K' => "♔", + 'p' => "♟", 'n' => "♞", 'b' => "♝", 'r' => "♜", 'q' => "♛", 'k' => "♚", + _ => "?", + } +} + +fn role_name(r: Role) -> &'static str { + match r { + Role::Pawn => "Pawn", Role::Knight => "Knight", Role::Bishop => "Bishop", Role::Rook => "Rook", Role::Queen => "Queen", Role::King => "King", + } +} + +fn role_value(r: Role) -> i32 { + match r { + Role::Pawn => 1, Role::Knight | Role::Bishop => 3, Role::Rook => 5, Role::Queen => 9, Role::King => 0, + } +} + +const START: [(Role, usize); 5] = [(Role::Pawn, 8), (Role::Knight, 2), (Role::Bishop, 2), (Role::Rook, 2), (Role::Queen, 1)]; + +fn san(pos: &Chess, m: &Move) -> String { + SanPlus::from_move(pos.clone(), m.clone()).to_string() +} + +pub struct Chess_ { + white: P, + black: P, + pos: Chess, + /// every move played, as (position before, move) + played: Vec<(Chess, Move)>, + history: Vec, + selected: Option, + draw_offer: Option, + ending: Option, + result_tag: Option<&'static str>, + over: bool, + timed_out: bool, +} + +/// The type the rest of the engine names (the module is `chess`). +pub type Chessgame = Chess_; + +impl Chess_ { + pub fn start(white: P, black: P) -> Box { + Box::new(Self::new(white, black)) + } + + fn new(white: P, black: P) -> Self { + let pos = Chess::default(); + let key = Self::key(&pos); + Self { white, black, pos, played: vec![], history: vec![key], selected: None, draw_offer: None, ending: None, result_tag: None, over: false, timed_out: false } + } + + fn key(pos: &Chess) -> String { + Fen::from_position(pos, EnPassantMode::Legal).to_string().split(' ').take(4).collect::>().join(" ") + } + + fn to_move(&self) -> &P { + if self.pos.turn() == Color::White { &self.white } else { &self.black } + } + + /// Pieces of `colour` that have been taken, and their value. + fn captured(&self, colour: Color) -> (String, i32) { + let (mut glyphs, mut value) = (String::new(), 0); + for (role, count) in START { + let have = (self.pos.board().by_color(colour) & self.pos.board().by_role(role)).count(); + let missing = count.saturating_sub(have); + let ch = if colour == Color::White { role.upper_char() } else { role.char() }; + glyphs.push_str(&glyph(ch).repeat(missing)); + value += role_value(role) * missing as i32; + } + (glyphs, value) + } + + /// Ended by the rules? (text, winner colour) + fn rule_outcome(&self) -> Option<(String, Option)> { + if self.pos.legal_moves().is_empty() { + return Some(if self.pos.is_check() { ("checkmate".into(), Some(!self.pos.turn())) } else { ("stalemate".into(), None) }); + } + if self.pos.is_insufficient_material() { + return Some(("insufficient material".into(), None)); + } + if self.pos.halfmoves() >= 100 { + return Some(("fifty-move rule".into(), None)); + } + let key = Self::key(&self.pos); + if self.history.iter().filter(|k| **k == key).count() >= 3 { + return Some(("threefold repetition".into(), None)); + } + None + } + + fn status(&self) -> (String, u32) { + if let Some(e) = &self.ending { + return (e.clone(), if e.contains("wins") { WIN } else { DRAW }); + } + if let Some((why, winner)) = self.rule_outcome() { + return match winner { + None => (format!("🤝 Draw — {why}."), DRAW), + Some(c) => (format!("🏆 Checkmate! **{}** wins.", if c == Color::White { self.white.name() } else { self.black.name() }), WIN), + }; + } + if self.timed_out { + return (format!("⏰ Abandoned — **{}** didn't move in time.", self.to_move().name()), DRAW); + } + let side = if self.pos.turn() == Color::White { "⚪ White" } else { "⚫ Black" }; + let mut text = format!("{side} to move — **{}**", self.to_move().name()); + if self.pos.is_check() { + text.push_str(" · ❗ **Check!**"); + } + (text, BLURPLE) + } + + fn board_url(&self) -> String { + let fen = Fen::from_position(&self.pos, EnPassantMode::Legal).to_string(); + let mut url = format!("https://lichess1.org/export/fen.gif?fen={}&color={}&theme=brown&piece=cburnett", urlencoding::encode(&fen), if self.pos.turn() == Color::White { "white" } else { "black" }); + if let Some((_, m)) = self.played.last() { + let uci = UciMove::from_move(m.clone(), CastlingMode::Standard).to_string(); + url.push_str(&format!("&lastMove={}", &uci[..4.min(uci.len())])); + } + url + } + + fn play(&mut self, m: &Move) { + let before = self.pos.clone(); + self.pos.play_unchecked(m.clone()); + self.played.push((before, m.clone())); + self.history.push(Self::key(&self.pos)); + self.selected = None; + self.draw_offer = None; + if self.rule_outcome().is_some() { + self.over = true; + } + } + + fn pgn(&self) -> String { + let result = self.result_tag.unwrap_or_else(|| match self.rule_outcome() { + Some((_, Some(Color::White))) => "1-0", + Some((_, Some(Color::Black))) => "0-1", + Some((_, None)) => "1/2-1/2", + None => "*", + }); + let mut out = format!("[Event \"Dezio chess\"]\n[White \"{}\"]\n[Black \"{}\"]\n[Result \"{result}\"]\n\n", self.white.name, self.black.name); + for (i, (before, m)) in self.played.iter().enumerate() { + if i % 2 == 0 { + out.push_str(&format!("{}. ", i / 2 + 1)); + } + out.push_str(&san(before, m)); + out.push(' '); + } + out.push_str(result); + out + } + + fn find_move(&self, text: &str) -> Option { + let text = text.trim(); + if let Ok(s) = text.parse::() { + if let Ok(m) = s.to_move(&self.pos) { + return Some(m); + } + } + UciMove::from_ascii(text.as_bytes()).ok()?.to_move(&self.pos).ok() + } +} + +impl Game for Chess_ { + fn players(&self) -> Vec { + vec![self.white.id, self.black.id] + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(900) + } + + fn allowed(&self, who: u64, action: &str) -> Result<(), String> { + if self.over && action == "pgn" { + return Ok(()); // anyone may grab the PGN + } + if who == self.white.id || who == self.black.id { Ok(()) } else { Err("You're not in this game — start your own with `/startgame`.".into()) } + } + + fn render(&self, t: u32) -> Rendered { + let (status, accent) = self.status(); + let over = self.over || accent != BLURPLE; + let (lost_white, value_white) = self.captured(Color::White); + let (lost_black, value_black) = self.captured(Color::Black); + let last = self.played.last().map(|(before, m)| format!("\n-# Last move: **{}** · move {}", san(before, m), (self.played.len() + 1) / 2)).unwrap_or_default(); + let mut card = Card::new(Some(accent)).text(&format!("### ♟️ Chess\n⚪ {} vs ⚫ {}\n{status}{last}", self.white.name(), self.black.name())).gallery(&[&self.board_url()]); + let mut material = Vec::new(); + if !lost_black.is_empty() { + material.push(format!("⚪ took {lost_black}{}", if value_black > value_white { format!(" (+{})", value_black - value_white) } else { String::new() })); + } + if !lost_white.is_empty() { + material.push(format!("⚫ took {lost_white}{}", if value_white > value_black { format!(" (+{})", value_white - value_black) } else { String::new() })); + } + if !material.is_empty() { + card = card.footer(&material.join(" · ")); + } + if over { + return card.row(vec![btn(t, "pgn", "PGN", "📜", ButtonStyle::Secondary, false)]).into(); + } + let moves = self.pos.legal_moves(); + let mut squares: Vec = moves.iter().filter_map(|m| m.from()).collect(); + squares.sort(); + squares.dedup(); + squares.sort_by_key(|s| (std::cmp::Reverse(self.pos.board().role_at(*s).map_or(0, |r| r as u8)), *s)); + let options = squares + .iter() + .take(25) + .map(|s| { + let piece = self.pos.board().piece_at(*s).unwrap(); + let n = moves.iter().filter(|m| m.from() == Some(*s)).count(); + let mut o = opt(&format!("{} {} · {s}", glyph(piece.char()), role_name(piece.role)), &u32::from(*s).to_string()); + o.default = self.selected == Some(*s); + o.description = Some(format!("{n} moves")); + o + }) + .collect(); + card = card.select(select_menu(&format!("gm:{t}:pick"), "1️⃣ Pick a piece…", options)); + if let Some(sel) = self.selected { + let options: Vec<_> = moves + .iter() + .filter(|m| m.from() == Some(sel)) + .map(|m| { + let mut desc = format!("to {}", m.to()); + if let Some(r) = m.capture() { + desc.push_str(&format!(" · takes {}", role_name(r).to_lowercase())); + } + let mut after = self.pos.clone(); + after.play_unchecked(m.clone()); + if after.is_check() { + desc.push_str(" · check"); + } + let mut o = opt(&san(&self.pos, m), &UciMove::from_move(m.clone(), CastlingMode::Standard).to_string()); + o.description = Some(desc); + o + }) + .collect(); + for (i, chunk) in options.chunks(25).enumerate() { + card = card.select(select_menu(&format!("gm:{t}:mv{i}"), &format!("2️⃣ …and where it goes{}", if i > 0 { " (more)" } else { "" }), chunk.to_vec())); + } + } + let offered = self.draw_offer.is_some(); + card = card.row(vec![ + btn(t, "type", "Type a move", "⌨️", ButtonStyle::Primary, false), + btn(t, "draw", if offered { "Accept draw" } else { "Offer draw" }, "🤝", if offered { ButtonStyle::Success } else { ButtonStyle::Secondary }, false), + btn(t, "resign", "Resign", "🏳️", ButtonStyle::Danger, false), + ]); + if let Some(o) = self.draw_offer { + card = card.footer(&format!("🤝 {} offers a draw — the other player can accept.", if o == self.white.id { self.white.name() } else { self.black.name() })); + } + card.into() + } + + fn click(&mut self, who: u64, action: &str, values: &[String], fields: &HashMap) -> Reply { + let mine = who == self.to_move().id; + let not_yours = || Reply::Private("⏳ It's not your turn.".into()); + match action { + "pgn" => Reply::Private(format!("```\n{}\n```", self.pgn().chars().take(1900).collect::())), + _ if self.over => Reply::Ignore, + "pick" => { + if !mine { + return not_yours(); + } + self.selected = values.first().and_then(|v| v.parse::().ok()).filter(|n| *n < 64).map(Square::new); + Reply::Update + } + a if a.starts_with("mv") => { + if !mine { + return not_yours(); + } + let Some(m) = values.first().and_then(|v| self.find_move(v)) else { return Reply::Private("❌ That move isn't legal any more.".into()) }; + self.play(&m); + Reply::Update + } + "type" => { + if !mine { + return not_yours(); + } + Reply::Modal { action: "typesub".into(), title: "Type your move".into(), fields: vec![crate::interact::text_field("move", "Move", Some("Standard notation or from-to squares"), "", 10, false, Some("Nf3, exd5, O-O, e7e8q …"))] } + } + "typesub" => { + if !mine { + return not_yours(); + } + let text = fields.get("move").cloned().unwrap_or_default(); + match self.find_move(&text) { + Some(m) => { + self.play(&m); + Reply::Update + } + None => Reply::Private(format!("❌ `{}` isn't a legal move here.", escape(text.trim()))), + } + } + "draw" => match self.draw_offer { + Some(o) if o != who => { + self.ending = Some("🤝 Draw agreed.".into()); + self.over = true; + self.result_tag = Some("1/2-1/2"); + Reply::Update + } + Some(_) => Reply::Private("You already offered a draw.".into()), + None => { + self.draw_offer = Some(who); + Reply::Update + } + }, + "resign" => { + let (me, winner, tag) = if who == self.white.id { (&self.white, &self.black, "0-1") } else { (&self.black, &self.white, "1-0") }; + self.ending = Some(format!("🏳️ {} resigned — **{}** wins.", me.name(), winner.name())); + self.result_tag = Some(tag); + self.over = true; + Reply::Update + } + _ => Reply::Ignore, + } + } + + fn is_over(&self) -> bool { + self.over + } + + fn abandon(&mut self) { + self.timed_out = true; + self.over = true; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p(id: u64) -> P { + P { id, name: format!("p{id}"), bot: false } + } + + fn typed(g: &mut Chess_, who: u64, mv: &str) -> Reply { + g.click(who, "typesub", &[], &HashMap::from([("move".to_string(), mv.to_string())])) + } + + #[test] + fn fools_mate_ends_the_game() { + let mut g = Chess_::new(p(1), p(2)); + for (who, mv) in [(1, "f3"), (2, "e5"), (1, "g4"), (2, "Qh4#")] { + assert!(matches!(typed(&mut g, who, mv), Reply::Update), "{mv}"); + } + assert!(g.over); + assert!(g.status().0.contains("Checkmate") && g.status().0.contains("p2")); + assert!(g.pgn().ends_with("0-1") && g.pgn().contains("1. f3 e5 2. g4 Qh4#")); + } + + #[test] + fn turns_legality_and_uci_input() { + let mut g = Chess_::new(p(1), p(2)); + assert!(matches!(typed(&mut g, 2, "e5"), Reply::Private(_)), "black can't move first"); + assert!(matches!(typed(&mut g, 1, "e5"), Reply::Private(_)), "illegal for white"); + assert!(matches!(typed(&mut g, 1, "e2e4"), Reply::Update)); + assert_eq!(g.pos.turn(), Color::Black); + assert!(g.board_url().contains("lastMove=e2e4")); + } + + #[test] + fn piece_menus_and_selection() { + let mut g = Chess_::new(p(1), p(2)); + let sq = u32::from(Square::G1).to_string(); + g.click(1, "pick", &[sq], &Default::default()); + assert_eq!(g.selected, Some(Square::G1)); + let json = serde_json::to_string(&g.render(5).card.build()).unwrap(); + assert!(json.contains("gm:5:mv0") && json.contains("Nf3")); + g.click(1, "mv0", &["g1f3".into()], &Default::default()); + assert!(g.selected.is_none() && g.played.len() == 1); + } + + #[test] + fn draws_and_resigning() { + let mut g = Chess_::new(p(1), p(2)); + g.click(1, "draw", &[], &Default::default()); + assert!(matches!(g.click(1, "draw", &[], &Default::default()), Reply::Private(_))); + g.click(2, "draw", &[], &Default::default()); + assert!(g.over && g.pgn().ends_with("1/2-1/2")); + let mut g = Chess_::new(p(1), p(2)); + g.click(1, "resign", &[], &Default::default()); + assert!(g.over && g.status().0.contains("p2") && g.pgn().ends_with("0-1")); + } + + #[test] + fn threefold_repetition_is_a_draw() { + let mut g = Chess_::new(p(1), p(2)); + for mv in ["Nf3", "Nf6", "Ng1", "Ng8", "Nf3", "Nf6", "Ng1", "Ng8"] { + let who = if g.pos.turn() == Color::White { 1 } else { 2 }; + typed(&mut g, who, mv); + } + assert!(g.over && g.status().0.contains("threefold")); + } +} diff --git a/src/commands/games/classic.rs b/src/commands/games/classic.rs new file mode 100644 index 0000000..bc5f8f2 --- /dev/null +++ b/src/commands/games/classic.rs @@ -0,0 +1,565 @@ +//! Tic-tac-toe, Connect 4 and rock paper scissors against a friend or Dezio. +use super::*; +use crate::ui::Card; +use rand::RngExt as _; +use std::time::Duration; + +// ---- tic-tac-toe (Dezio never loses — try to draw!) --------------------------------------------------------- + +const LINES: [[usize; 3]; 8] = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]; +const MARKS: [&str; 2] = ["❌", "⭕"]; + +type Board = [Option; 9]; + +fn ttt_winner(b: &Board) -> Option<(u8, [usize; 3])> { + LINES.iter().find_map(|l| match (b[l[0]], b[l[1]], b[l[2]]) { + (Some(a), Some(b2), Some(c)) if a == b2 && b2 == c => Some((a, *l)), + _ => None, + }) +} + +/// Score for the player to move (`me`): 1 win, 0 draw, -1 loss. +fn minimax(b: &mut Board, me: u8) -> i32 { + if let Some((w, _)) = ttt_winner(b) { + return if w == me { 1 } else { -1 }; + } + if b.iter().all(Option::is_some) { + return 0; + } + let mut best = -2; + for i in 0..9 { + if b[i].is_none() { + b[i] = Some(me); + best = best.max(-minimax(b, 1 - me)); + b[i] = None; + if best == 1 { + break; + } + } + } + best +} + +fn ttt_best_move(b: &Board, me: u8) -> usize { + let mut scores = Vec::new(); + let mut work = *b; + for i in 0..9 { + if work[i].is_none() { + work[i] = Some(me); + scores.push((i, -minimax(&mut work, 1 - me))); + work[i] = None; + } + } + let top = scores.iter().map(|s| s.1).max().unwrap_or(0); + let best: Vec = scores.iter().filter(|s| s.1 == top).map(|s| s.0).collect(); + best[rand::rng().random_range(0..best.len())] +} + +pub struct Ttt { + p: [P; 2], + board: Board, + turn: usize, + starter: usize, + over: bool, + timed_out: bool, +} + +impl Ttt { + pub fn start(p1: P, p2: P) -> Box { + Box::new(Self::new(p1, p2, 0)) + } + + fn new(p1: P, p2: P, starter: usize) -> Self { + let mut g = Self { p: [p1, p2], board: [None; 9], turn: starter, starter, over: false, timed_out: false }; + if g.p[g.turn].bot { + let m = ttt_best_move(&g.board, g.turn as u8); + g.play(m); + } + g + } + + fn play(&mut self, i: usize) { + self.board[i] = Some(self.turn as u8); + if ttt_winner(&self.board).is_some() || self.board.iter().all(Option::is_some) { + self.over = true; + } else { + self.turn = 1 - self.turn; + } + } +} + +impl Game for Ttt { + fn players(&self) -> Vec { + self.p.iter().map(|p| p.id).collect() + } + + fn render(&self, t: u32) -> Rendered { + let found = ttt_winner(&self.board); + let (status, accent) = if let Some((w, _)) = found { + (format!("🎉 **{}** wins!", self.p[w as usize].name()), WIN) + } else if self.board.iter().all(Option::is_some) { + ("🤝 It's a draw!".to_string(), DRAW) + } else if self.timed_out { + ("Game abandoned.".to_string(), DRAW) + } else { + (format!("{} **{}**'s turn", MARKS[self.turn], self.p[self.turn].name()), BLURPLE) + }; + let mut card = Card::new(Some(accent)).text(&format!("### ❌⭕ Tic-tac-toe\n{} {} vs {} {}\n{status}", MARKS[0], self.p[0].name(), MARKS[1], self.p[1].name())); + let line = found.map(|f| f.1).unwrap_or([9, 9, 9]); + for row in 0..3 { + let buttons = (row * 3..row * 3 + 3) + .map(|i| { + let (label, emoji) = match self.board[i] { + Some(m) => ("", MARKS[m as usize]), + None => ("\u{200b}", ""), + }; + btn(t, &format!("m{i}"), label, emoji, if line.contains(&i) { ButtonStyle::Success } else { ButtonStyle::Secondary }, self.board[i].is_some() || self.over) + }) + .collect(); + card = card.row(buttons); + } + if self.over && !self.timed_out { + card = card.row(vec![again(t, "Rematch")]); + } + card.into() + } + + fn click(&mut self, who: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + if action == "again" { + let next = Self::new(self.p[0].clone(), self.p[1].clone(), 1 - self.starter); + return Reply::Replace(Box::new(next)); + } + let Some(i) = action.strip_prefix('m').and_then(|n| n.parse::().ok()).filter(|i| *i < 9) else { return Reply::Ignore }; + if self.over || self.board[i].is_some() { + return Reply::Ignore; + } + if who != self.p[self.turn].id { + return Reply::Private("⏳ It's not your turn.".into()); + } + self.play(i); + if !self.over && self.p[self.turn].bot { + let m = ttt_best_move(&self.board, self.turn as u8); + self.play(m); + } + Reply::Update + } + + fn is_over(&self) -> bool { + self.over + } + + fn abandon(&mut self) { + self.timed_out = true; + self.over = true; + } +} + +// ---- Connect 4 ----------------------------------------------------------------------------------------------------- + +const ROWS: usize = 6; +const COLS: usize = 7; +const DISCS: [&str; 2] = ["🔴", "🟡"]; +const NUMBERS: [&str; 7] = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣"]; +const ORDER: [usize; 7] = [3, 2, 4, 1, 5, 0, 6]; // centre first: better pruning and better play +type Grid = [[Option; COLS]; ROWS]; +const DIRS: [(i32, i32); 4] = [(0, 1), (1, 0), (1, 1), (1, -1)]; + +fn drop_row(g: &Grid, col: usize) -> Option { + (0..ROWS).rev().find(|r| g[*r][col].is_none()) +} + +fn at(g: &Grid, r: i32, c: i32) -> Option { + if (0..ROWS as i32).contains(&r) && (0..COLS as i32).contains(&c) { g[r as usize][c as usize] } else { None } +} + +fn four(g: &Grid, player: u8) -> Option> { + for r in 0..ROWS as i32 { + for c in 0..COLS as i32 { + for (dr, dc) in DIRS { + let cells: Vec<(i32, i32)> = (0..4).map(|k| (r + dr * k, c + dc * k)).collect(); + if cells.iter().all(|(rr, cc)| at(g, *rr, *cc) == Some(player)) { + return Some(cells.into_iter().map(|(a, b)| (a as usize, b as usize)).collect()); + } + } + } + } + None +} + +/// Does the disc just dropped at (r, c) make four for `player`? +fn wins_at(g: &Grid, r: usize, c: usize, player: u8) -> bool { + DIRS.iter().any(|(dr, dc)| { + let mut count = 1; + for sign in [1, -1] { + let (mut rr, mut cc) = (r as i32 + dr * sign, c as i32 + dc * sign); + while at(g, rr, cc) == Some(player) { + count += 1; + rr += dr * sign; + cc += dc * sign; + } + } + count >= 4 + }) +} + +fn score_window(w: [Option; 4], me: u8) -> i32 { + let mine = w.iter().filter(|x| **x == Some(me)).count(); + let theirs = w.iter().filter(|x| **x == Some(1 - me)).count(); + let empty = w.iter().filter(|x| x.is_none()).count(); + match (mine, theirs, empty) { + (4, _, _) => 1000, + (3, _, 1) => 6, + (2, _, 2) => 2, + (_, 3, 1) => -8, + _ => 0, + } +} + +fn evaluate(g: &Grid, me: u8) -> i32 { + let mut score: i32 = (0..ROWS).filter(|r| g[*r][3] == Some(me)).count() as i32 * 3; + for r in 0..ROWS as i32 { + for c in 0..COLS as i32 { + for (dr, dc) in DIRS { + if (0..ROWS as i32).contains(&(r + dr * 3)) && (0..COLS as i32).contains(&(c + dc * 3)) { + let w = [0, 1, 2, 3].map(|k| at(g, r + dr * k, c + dc * k)); + score += score_window(w, me); + } + } + } + } + score +} + +fn negamax(g: &mut Grid, depth: u32, me: u8, mut alpha: i32, beta: i32, last: (usize, usize)) -> i32 { + if wins_at(g, last.0, last.1, 1 - me) { + return -100_000 - depth as i32; + } + let moves: Vec = ORDER.iter().copied().filter(|c| g[0][*c].is_none()).collect(); + if moves.is_empty() { + return 0; + } + if depth == 0 { + return evaluate(g, me) - evaluate(g, 1 - me); + } + let mut best = i32::MIN + 1; + for col in moves { + let row = drop_row(g, col).unwrap(); + g[row][col] = Some(me); + let value = -negamax(g, depth - 1, 1 - me, -beta, -alpha, (row, col)); + g[row][col] = None; + best = best.max(value); + alpha = alpha.max(value); + if alpha >= beta { + break; + } + } + best +} + +fn c4_best_move(board: &Grid, me: u8, depth: u32) -> usize { + let mut g = *board; + let mut scores = Vec::new(); + for col in ORDER { + let Some(row) = drop_row(&g, col) else { continue }; + g[row][col] = Some(me); + scores.push((col, -negamax(&mut g, depth, 1 - me, i32::MIN + 1, i32::MAX, (row, col)))); + g[row][col] = None; + } + let top = scores.iter().map(|s| s.1).max().unwrap_or(0); + let best: Vec = scores.iter().filter(|s| s.1 >= top - 1).map(|s| s.0).collect(); + best[rand::rng().random_range(0..best.len())] +} + +pub struct Connect4 { + p: [P; 2], + board: Grid, + turn: usize, + starter: usize, + win_cells: Vec<(usize, usize)>, + over: bool, + timed_out: bool, +} + +impl Connect4 { + pub fn start(p1: P, p2: P) -> Box { + Box::new(Self::new(p1, p2, 0)) + } + + fn new(p1: P, p2: P, starter: usize) -> Self { + let mut g = Self { p: [p1, p2], board: [[None; COLS]; ROWS], turn: starter, starter, win_cells: vec![], over: false, timed_out: false }; + if g.p[g.turn].bot { + let c = c4_best_move(&g.board, g.turn as u8, 4); + g.play(c); + } + g + } + + fn full(&self) -> bool { + (0..COLS).all(|c| self.board[0][c].is_some()) + } + + fn play(&mut self, col: usize) { + let Some(row) = drop_row(&self.board, col) else { return }; + self.board[row][col] = Some(self.turn as u8); + if let Some(cells) = four(&self.board, self.turn as u8) { + self.win_cells = cells; + self.over = true; + } else if self.full() { + self.over = true; + } else { + self.turn = 1 - self.turn; + } + } +} + +impl Game for Connect4 { + fn players(&self) -> Vec { + self.p.iter().map(|p| p.id).collect() + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(600) + } + + fn render(&self, t: u32) -> Rendered { + let rows: Vec = (0..ROWS) + .map(|r| { + (0..COLS) + .map(|c| if self.win_cells.contains(&(r, c)) { "⭐" } else { self.board[r][c].map_or("⚫", |v| DISCS[v as usize]) }) + .collect::() + }) + .collect(); + let grid = format!("{}\n{}", NUMBERS.concat(), rows.join("\n")); + let (status, accent) = if !self.win_cells.is_empty() { + (format!("🎉 **{}** {} connects four!", self.p[self.turn].name(), DISCS[self.turn]), WIN) + } else if self.full() { + ("🤝 The board is full — draw!".to_string(), DRAW) + } else if self.timed_out { + ("Game abandoned.".to_string(), DRAW) + } else { + (format!("{} **{}**'s turn", DISCS[self.turn], self.p[self.turn].name()), BLURPLE) + }; + let mut card = Card::new(Some(accent)).text(&format!("### 🔴🟡 Connect 4\n{} {} vs {} {}", DISCS[0], self.p[0].name(), DISCS[1], self.p[1].name())).text(&grid).text(&status); + let buttons: Vec<_> = (0..COLS).map(|c| btn(t, &format!("c{c}"), "", NUMBERS[c], ButtonStyle::Secondary, self.over || self.board[0][c].is_some())).collect(); + card = card.row(buttons[..4].to_vec()).row(buttons[4..].to_vec()); + if self.over && !self.timed_out { + card = card.row(vec![again(t, "Rematch")]); + } + card.into() + } + + fn click(&mut self, who: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + if action == "again" { + return Reply::Replace(Box::new(Self::new(self.p[0].clone(), self.p[1].clone(), 1 - self.starter))); + } + let Some(col) = action.strip_prefix('c').and_then(|n| n.parse::().ok()).filter(|c| *c < COLS) else { return Reply::Ignore }; + if self.over || self.board[0][col].is_some() { + return Reply::Ignore; + } + if who != self.p[self.turn].id { + return Reply::Private("⏳ It's not your turn.".into()); + } + self.play(col); + if !self.over && self.p[self.turn].bot { + let c = c4_best_move(&self.board, self.turn as u8, 4); + self.play(c); + } + Reply::Update + } + + fn is_over(&self) -> bool { + self.over + } + + fn abandon(&mut self) { + self.timed_out = true; + self.over = true; + } +} + +// ---- rock paper scissors ---------------------------------------------------------------------------------------------- + +const MOVES: [(&str, &str); 3] = [("rock", "🪨"), ("paper", "📄"), ("scissors", "✂️")]; +const TARGET: u32 = 2; + +fn beats(a: usize, b: usize) -> bool { + // rock(0) beats scissors(2), paper(1) beats rock(0), scissors(2) beats paper(1) + (a + 2) % 3 == b +} + +pub struct Rps { + p: [P; 2], + picks: [Option; 2], + score: [u32; 2], + history: Vec, + over: bool, + timed_out: bool, +} + +impl Rps { + pub fn start(p1: P, p2: P) -> Box { + Box::new(Self::new(p1, p2)) + } + + fn new(p1: P, p2: P) -> Self { + Self { p: [p1, p2], picks: [None; 2], score: [0; 2], history: vec![], over: false, timed_out: false } + } + + fn resolve(&mut self) { + let (a, b) = (self.picks[0].unwrap(), self.picks[1].unwrap()); + let round = self.history.len() + 1; + let line = if a == b { + format!("{} vs {} — tie", MOVES[a].1, MOVES[b].1) + } else { + let w = if beats(a, b) { 0 } else { 1 }; + self.score[w] += 1; + format!("{} vs {} — **{}** takes the round", MOVES[a].1, MOVES[b].1, self.p[w].name()) + }; + self.history.push(format!("`R{round}` {line}")); + self.picks = [None; 2]; + if self.score.iter().any(|s| *s >= TARGET) { + self.over = true; + } + } +} + +impl Game for Rps { + fn players(&self) -> Vec { + self.p.iter().map(|p| p.id).collect() + } + + fn render(&self, t: u32) -> Rendered { + let champion = (0..2).find(|i| self.score[*i] >= TARGET); + let (status, accent) = if let Some(c) = champion { + (format!("🏆 **{}** wins the match!", self.p[c].name()), WIN) + } else if self.timed_out { + ("Game abandoned.".to_string(), DRAW) + } else { + let waiting: Vec = (0..2).filter(|i| self.picks[*i].is_none()).map(|i| self.p[i].name()).collect(); + (format!("Round {} — waiting for **{}**", self.history.len() + 1, waiting.join("** and **")), BLURPLE) + }; + let mut card = Card::new(Some(accent)).text(&format!("### 🪨📄✂️ Rock paper scissors\n**{}** {} – {} **{}** · first to {TARGET}", self.p[0].name(), self.score[0], self.score[1], self.p[1].name())); + if !self.history.is_empty() { + let from = self.history.len().saturating_sub(5); + card = card.text(&self.history[from..].join("\n")); + } + card = card.text(&status); + if !self.over { + card = card.row(MOVES.iter().enumerate().map(|(i, (m, e))| btn(t, &format!("p{i}"), &m[..1].to_uppercase().chars().chain(m[1..].chars()).collect::(), e, ButtonStyle::Primary, false)).collect()); + let ready = (0..2).map(|i| format!("{} {}", self.p[i].name(), if self.picks[i].is_some() { "✅" } else { "⏳" })).collect::>().join(" · "); + card = card.footer(&ready); + } else if !self.timed_out { + card = card.row(vec![again(t, "Rematch")]); + } + card.into() + } + + fn click(&mut self, who: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + if action == "again" { + return Reply::Replace(Box::new(Self::new(self.p[0].clone(), self.p[1].clone()))); + } + let Some(m) = action.strip_prefix('p').and_then(|n| n.parse::().ok()).filter(|m| *m < 3) else { return Reply::Ignore }; + let i = if who == self.p[0].id { 0 } else { 1 }; + if self.over { + return Reply::Ignore; + } + if let Some(prev) = self.picks[i] { + return Reply::Private(format!("You already picked {} this round.", MOVES[prev].1)); + } + self.picks[i] = Some(m); + let other = 1 - i; + if self.p[other].bot { + self.picks[other] = Some(rand::rng().random_range(0..3)); + } + if self.picks.iter().all(Option::is_some) { + self.resolve(); + Reply::Update + } else { + Reply::UpdateAndNote(format!("You picked {} — waiting for the other player.", MOVES[m].1)) + } + } + + fn is_over(&self) -> bool { + self.over + } + + fn abandon(&mut self) { + self.timed_out = true; + self.over = true; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn human(id: u64) -> P { + P { id, name: format!("p{id}"), bot: false } + } + + fn robot() -> P { + P { id: 99, name: "Dezio".into(), bot: true } + } + + #[test] + fn dezio_never_loses_at_tic_tac_toe() { + // play every possible human line against the bot: it must never lose + fn explore(g: &Ttt, depth: u32) { + if g.over { + if let Some((w, _)) = ttt_winner(&g.board) { + assert_eq!(w, 1, "the human won?!"); + } + return; + } + for i in 0..9 { + if g.board[i].is_none() { + let mut next = Ttt { p: g.p.clone(), board: g.board, turn: g.turn, starter: g.starter, over: false, timed_out: false }; + next.click(1, &format!("m{i}"), &[], &Default::default()); + explore(&next, depth + 1); + } + } + } + explore(&Ttt::new(human(1), robot(), 0), 0); + explore(&Ttt::new(human(1), robot(), 1), 0); + } + + #[test] + fn tic_tac_toe_turns_and_wins() { + let mut g = Ttt::new(human(1), human(2), 0); + assert!(matches!(g.click(2, "m0", &[], &Default::default()), Reply::Private(_))); + for (who, cell) in [(1, 0), (2, 3), (1, 1), (2, 4), (1, 2)] { + assert!(matches!(g.click(who, &format!("m{cell}"), &[], &Default::default()), Reply::Update)); + } + assert!(g.over && ttt_winner(&g.board).is_some_and(|w| w.0 == 0)); + } + + #[test] + fn connect4_detects_fours_and_the_bot_blocks() { + let mut g = Connect4::new(human(1), human(2), 0); + for col in [0, 1, 0, 1, 0, 1, 0] { + g.play(col); + } + assert!(g.over && g.win_cells.len() == 4); + // three in a row for the human: the bot (to move) must block column 3 + let mut g = Connect4::new(human(1), robot(), 0); + for col in [0, 6, 1, 6] { + g.play(col); + } + // human has 0,1 ... drop a third and let the bot answer through click + g.turn = 0; + g.click(1, "c2", &[], &Default::default()); + assert!(g.board[ROWS - 1][3].is_some(), "the bot should block at column 4"); + } + + #[test] + fn rps_beats_table_and_match_end() { + assert!(beats(0, 2) && beats(1, 0) && beats(2, 1) && !beats(0, 1)); + let mut g = Rps::new(human(1), human(2)); + g.click(1, "p0", &[], &Default::default()); + assert!(matches!(g.click(1, "p1", &[], &Default::default()), Reply::Private(_))); + g.click(2, "p2", &[], &Default::default()); // rock beats scissors + g.click(1, "p0", &[], &Default::default()); + g.click(2, "p2", &[], &Default::default()); + assert!(g.over && g.score == [2, 0]); + } +} diff --git a/src/commands/games/cookie.rs b/src/commands/games/cookie.rs new file mode 100644 index 0000000..56cbcbb --- /dev/null +++ b/src/commands/games/cookie.rs @@ -0,0 +1,229 @@ +//! Cookie Clicker. Your bakery keeps baking while you're away (and while the bot restarts): cookies are worked out +//! from the time since your last visit. The buttons on a cookie card keep working forever — they carry your user id +//! and the game state lives in data/cookieclicker.json. +use super::*; +use crate::converters::thousands; +use crate::paths; +use crate::storage::JsonStore; +use crate::ui::{select_menu, select_option, Card}; +use rand::RngExt as _; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// name, base price, cookies per second, emoji +const UPGRADES: [(&str, f64, f64, &str); 10] = [ + ("Cursor", 15.0, 1.0, "👆"), + ("Grandma", 100.0, 5.0, "👵"), + ("Farm", 1_100.0, 10.0, "🌾"), + ("Mine", 12_000.0, 50.0, "⛏️"), + ("Factory", 130_000.0, 260.0, "🏭"), + ("Bank", 1_400_000.0, 1_400.0, "🏦"), + ("Temple", 20_000_000.0, 7_800.0, "🛕"), + ("Wizard Tower", 330_000_000.0, 44_000.0, "🧙"), + ("Shipment", 5_100_000_000.0, 260_000.0, "🚀"), + ("Alchemy Lab", 75_000_000_000.0, 1_600_000.0, "⚗️"), +]; +const ACCENT: u32 = 0xF8C471; +const GOLDEN_CHANCE: f64 = 0.03; + +fn store() -> &'static Arc { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| JsonStore::open(paths::data(&["cookieclicker.json"]))) +} + +fn now() -> f64 { + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64()) +} + +pub fn short(n: f64) -> String { + for (size, suffix) in [(1e12, "T"), (1e9, "B"), (1e6, "M"), (1e3, "K")] { + if n >= size * 10.0 { + let v = n / size; + return format!("{}.{}{suffix}", thousands(v as u64), ((v.fract() * 10.0) as u64).min(9)); + } + } + thousands(n as u64) +} + +fn cost(index: usize, owned: u64) -> f64 { + (UPGRADES[index].1 * 1.15f64.powi(owned as i32)).floor() +} + +/// A player's save, with passive income applied whenever it's loaded. +pub struct Bakery { + user: u64, + cookies: f64, + owned: [u64; 10], + clicks: u64, + baked: f64, + last: f64, + gained_offline: f64, +} + +impl Bakery { + pub fn load(user: u64) -> Self { + let d = store().get(user).unwrap_or(Value::Null); + let cookies = d["cookies"].as_f64().unwrap_or(0.0); + let mut owned = [0u64; 10]; + for (i, (name, ..)) in UPGRADES.iter().enumerate() { + owned[i] = d["owned"][*name].as_u64().unwrap_or(0); + } + let mut b = Self { user, cookies, owned, clicks: d["clicks"].as_u64().unwrap_or(0), baked: d["baked"].as_f64().unwrap_or(cookies), last: d["last"].as_f64().unwrap_or_else(now), gained_offline: 0.0 }; + let elapsed = (now() - b.last).max(0.0); + if elapsed > 0.0 { + b.gained_offline = b.cps() * elapsed; + b.cookies += b.gained_offline; + b.baked += b.gained_offline; + } + b.last = now(); + b + } + + pub fn cps(&self) -> f64 { + UPGRADES.iter().zip(self.owned).map(|(u, n)| u.2 * n as f64).sum() + } + + pub fn save(&self) { + let owned: serde_json::Map = UPGRADES.iter().zip(self.owned).map(|(u, n)| (u.0.to_string(), json!(n))).collect(); + store().set(self.user, json!({"cookies": self.cookies, "cps": self.cps(), "owned": owned, "clicks": self.clicks, "baked": self.baked, "last": self.last})); + } + + /// The golden-cookie bonus, if one dropped. + fn click(&mut self) -> Option { + self.clicks += 1; + let mut gain = 1.0 + self.cps() * 0.01; // clicks get better as the bakery grows + let mut bonus = None; + if rand::rng().random_bool(GOLDEN_CHANCE) { + let b = (self.cps() * 60.0).max(77.0); + gain += b; + bonus = Some(b); + } + self.cookies += gain; + self.baked += gain; + bonus + } + + fn buy(&mut self, index: usize) -> bool { + let price = cost(index, self.owned[index]); + if self.cookies >= price { + self.cookies -= price; + self.owned[index] += 1; + true + } else { + false + } + } +} + +fn card(user: u64, name: &str, b: &Bakery, note: Option<&str>) -> Component { + let who = if name.is_empty() { format!("<@{user}>") } else { escape(name) }; + let mut c = Card::new(Some(ACCENT)).text(&format!("### 🍪 {who}'s bakery\n# {} cookies\n**{}**/sec · {} clicks · {} baked all-time", short(b.cookies), short(b.cps()), thousands(b.clicks), short(b.baked))); + let owned: Vec = UPGRADES.iter().zip(b.owned).filter(|(_, n)| *n > 0).map(|(u, n)| format!("{} {} ×{n}", u.3, u.0)).collect(); + c = c.text(&if owned.is_empty() { "-# Buy a Cursor to start baking automatically.".to_string() } else { owned.join(" · ") }); + if let Some(n) = note { + c = c.text(n); + } + let id = |a: &str| format!("cookie:{user}:{a}"); + c = c.row(vec![btn_style(&id("click"), "Click!", "🍪", ButtonStyle::Primary), btn_style(&id("refresh"), "", "🔄", ButtonStyle::Secondary)]); + let options = UPGRADES + .iter() + .enumerate() + .map(|(i, (name, _, cps, emoji))| { + let price = cost(i, b.owned[i]); + select_option(&format!("{name} — {} 🍪", short(price)), name, emoji, &format!("+{}/sec · own {}{}", short(*cps), b.owned[i], if b.cookies >= price { " · ✅ affordable" } else { "" }), false) + }) + .collect(); + c.select(select_menu(&id("buy"), "🛒 Buy an upgrade…", options)).footer("Your bakery keeps baking while you're away · 🌟 golden cookies drop sometimes").build() +} + +fn btn_style(id: &str, label: &str, emoji: &str, style: ButtonStyle) -> Button { + let mut b = button(id, label, style); + if label.is_empty() { + b.label = None; + } + b.emoji = Some(EmojiReactionType::Unicode { name: emoji.into() }); + b +} + +pub async fn start(ctx: &Arc) -> Result<()> { + let mut b = Bakery::load(ctx.user_id.get()); + let note = (b.gained_offline >= 1.0).then(|| format!("🌙 While you were away you baked **{}** cookies.", short(b.gained_offline))); + b.gained_offline = 0.0; + b.save(); + let name = display_name_of(&ctx.state, ctx.guild_id, ctx.user_id).await; + ctx.reply(card(ctx.user_id.get(), &name, &b, note.as_deref())).await +} + +pub async fn on_component(state: &Arc, i: &Interaction) { + let Some(InteractionData::MessageComponent(d)) = i.data.as_ref() else { return }; + let mut p = d.custom_id.split(':').skip(1); + let (Some(owner), Some(action)) = (p.next().and_then(|u| u.parse::().ok()), p.next()) else { return }; + let Some(user) = i.author() else { return }; + if user.id.get() != owner { + return interact::private_text(state, i, "🍪 That's not your bakery — open yours with `D!cookie`.").await; + } + let mut b = Bakery::load(owner); + let note = match action { + "click" => b.click().map(|bonus| format!("🌟 **Golden cookie!** +{}", short(bonus))), + "buy" => { + let Some(index) = d.values.first().and_then(|v| UPGRADES.iter().position(|u| u.0 == v)) else { return interact::ack(state, i).await }; + let price = cost(index, b.owned[index]); + if b.buy(index) { + Some(format!("🛒 Bought a **{}** for {} 🍪", UPGRADES[index].0, short(price))) + } else { + Some(format!("💸 A {} costs {} — you need {} more.", UPGRADES[index].0, short(price), short(price - b.cookies))) + } + } + _ => None, + }; + b.gained_offline = 0.0; + b.save(); + let name = display_name_of(state, i.guild_id, user.id).await; + interact::update(state, i, card(owner, &name, &b, note.as_deref())).await; +} + +/// Top bakers by cookies baked all-time. +#[allow(dead_code)] +pub fn leaderboard(limit: usize) -> Vec<(u64, f64)> { + let mut rows: Vec<(u64, f64)> = store().snapshot().iter().filter_map(|(k, v)| Some((k.parse().ok()?, v["baked"].as_f64().or_else(|| v["cookies"].as_f64())?))).collect(); + rows.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); + rows.truncate(limit); + rows +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn numbers_read_nicely() { + assert_eq!(short(950.0), "950"); + assert_eq!(short(12_345.0), "12.3K"); + assert_eq!(short(5_400_000.0), "5,400.0K"); // same as the Python bot: millions start at 10M + assert_eq!(short(25_000_000.0), "25.0M"); + } + + #[test] + fn prices_grow_fifteen_percent_each() { + assert_eq!(cost(0, 0), 15.0); + assert_eq!(cost(0, 1), 17.0); + assert_eq!(cost(1, 10), 404.0); + } + + #[test] + fn buying_and_baking() { + let mut b = Bakery { user: 1, cookies: 100.0, owned: [0; 10], clicks: 0, baked: 100.0, last: now(), gained_offline: 0.0 }; + assert!(b.buy(0) && b.owned[0] == 1 && b.cookies == 85.0); + assert!(!b.buy(2)); + assert_eq!(b.cps(), 1.0); + let before = b.cookies; + b.click(); + assert!(b.cookies > before && b.clicks == 1); + } + + #[test] + fn the_card_is_clickable_by_id() { + let b = Bakery { user: 9, cookies: 20.0, owned: [0; 10], clicks: 0, baked: 20.0, last: now(), gained_offline: 0.0 }; + let json = serde_json::to_string(&card(9, "Me", &b, None)).unwrap(); + assert!(json.contains("cookie:9:click") && json.contains("cookie:9:buy") && json.contains("affordable")); + } +} diff --git a/src/commands/games/hangman.rs b/src/commands/games/hangman.rs new file mode 100644 index 0000000..592d4e4 --- /dev/null +++ b/src/commands/games/hangman.rs @@ -0,0 +1,219 @@ +//! Hangman. Pick letters from the two dropdowns or guess the whole word. +//! +//! * Random word from a category — you (and your opponent, if you named one) guess together. +//! * Custom word — the person who set it can't guess; their opponent (or anyone, if no opponent was named) does. +use super::*; +use crate::ui::{select_menu, Card}; + +const STAGES: [&str; 7] = [ + " ┌───┐\n │\n │\n │\n ═╧═", + " ┌───┐\n │ O\n │\n │\n ═╧═", + " ┌───┐\n │ O\n │ |\n │\n ═╧═", + " ┌───┐\n │ O\n │ /|\n │\n ═╧═", + " ┌───┐\n │ O\n │ /|\\\n │\n ═╧═", + " ┌───┐\n │ O\n │ /|\\\n │ /\n ═╧═", + " ┌───┐\n │ O\n │ /|\\\n │ / \\\n ═╧═", +]; +const LIVES: usize = 6; + +pub fn categories() -> Vec { + data()["hangman"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default() +} + +pub struct Hangman { + setter: P, + guessers: Vec

, + custom: bool, + category: Option, + word: String, + guessed: Vec, + misses: Vec, + lives: usize, + solved_by: Option, + over: bool, + timed_out: bool, +} + +impl Hangman { + pub fn start(player: P, opponent: Option

, word: Option, category: Option) -> Box { + match word.map(|w| w.trim().to_lowercase()).filter(|w| !w.is_empty()) { + Some(w) => Box::new(Self::new(player, opponent.into_iter().collect(), Some(w), None)), + None => { + let mut guessers = vec![player.clone()]; + guessers.extend(opponent); + Box::new(Self::new(player, guessers, None, category)) + } + } + } + + fn new(setter: P, guessers: Vec

, word: Option, category: Option) -> Self { + let cats = categories(); + let custom = word.is_some(); + let category = if custom { None } else { Some(category.filter(|c| cats.contains(c)).unwrap_or_else(|| pick(&cats))) }; + let word = word.unwrap_or_else(|| { + let list: Vec = data()["hangman"][category.as_deref().unwrap_or("animals")].as_array().into_iter().flatten().filter_map(|w| w.as_str().map(str::to_string)).collect(); + pick(&list) + }); + Self { setter, guessers, custom, category, word, guessed: vec![], misses: vec![], lives: LIVES, solved_by: None, over: false, timed_out: false } + } + + fn won(&self) -> bool { + self.word.chars().all(|c| self.guessed.contains(&c) || !c.is_alphabetic()) + } + + fn miss(&mut self, what: String) { + self.misses.push(what); + self.lives -= 1; + if self.lives == 0 { + self.over = true; + } + } +} + +impl Game for Hangman { + fn players(&self) -> Vec { + self.guessers.iter().map(|p| p.id).collect() + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(600) + } + + fn allowed(&self, who: u64, _: &str) -> Result<(), String> { + if self.custom && who == self.setter.id && !self.over { + return Err("You set the word — let the others guess!".into()); + } + let p = self.players(); + if p.is_empty() || p.contains(&who) { Ok(()) } else { Err("You're not in this game — start your own with `/startgame`.".into()) } + } + + fn render(&self, t: u32) -> Rendered { + let shown: String = self.word.chars().map(|c| if self.guessed.contains(&c) || !c.is_alphabetic() { c.to_uppercase().to_string() } else { "_".to_string() }).collect::>().join(" "); + let title = format!("### 🪢 Hangman{}", self.category.as_ref().map_or(" · custom word".to_string(), |c| format!(" · {}", c[..1].to_uppercase() + &c[1..]))); + let (status, accent) = if self.over && self.won() { + let who = self.solved_by.clone().or_else(|| self.guessers.first().map(P::name)); + (format!("🎉 Solved{}! It was **{}**.", who.map(|w| format!(" by **{w}**")).unwrap_or_default(), self.word), WIN) + } else if self.over { + (format!("💀 Out of lives — the word was **{}**.", escape(&self.word)), LOSE) + } else { + (format!("❤️ {}{} ({} left)", "♥".repeat(self.lives), "♡".repeat(LIVES - self.lives), self.lives), BLURPLE) + }; + let mut card = Card::new(Some(accent)).text(&title).text(&format!("```\n{}\n```\n# `{shown}`", STAGES[LIVES - self.lives])); + let mut wrong: Vec = self.misses.iter().map(|m| m.to_uppercase()).collect(); + wrong.sort(); + wrong.dedup(); + card = card.text(&format!("{status}{}", if wrong.is_empty() { String::new() } else { format!("\n-# Wrong: {}", wrong.join(", ")) })); + if !self.over { + let remaining: Vec = ('a'..='z').filter(|c| !self.guessed.contains(c) && !self.misses.contains(&c.to_string())).collect(); + for (half, action, letters) in [("A–M", "la", remaining.iter().filter(|c| **c <= 'm').collect::>()), ("N–Z", "lb", remaining.iter().filter(|c| **c > 'm').collect::>())] { + let options = if letters.is_empty() { vec![opt("-", "-")] } else { letters.iter().map(|c| opt(&c.to_uppercase().to_string(), &c.to_string())).collect() }; + let mut menu = select_menu(&format!("gm:{t}:{action}"), &if letters.is_empty() { format!("No letters left in {half}") } else { format!("Pick a letter ({half})") }, options); + menu.disabled = letters.is_empty(); + card = card.select(menu); + } + card = card.row(vec![btn(t, "word", "Guess the word", "💬", ButtonStyle::Primary, false)]); + let who = if self.custom && self.guessers.is_empty() { format!("anyone except {}", self.setter.name()) } else { self.guessers.iter().map(P::name).collect::>().join(", ") }; + card = card.footer(&format!("Guessing: {who}{}", if self.custom { format!(" · word set by {}", self.setter.name()) } else { String::new() })); + } else if !self.custom && !self.timed_out { + card = card.row(vec![again(t, "New word")]); + } + card.into() + } + + fn click(&mut self, who: u64, action: &str, values: &[String], fields: &HashMap) -> Reply { + let name = |me: &Hangman| me.guessers.iter().find(|p| p.id == who).map(|p| p.name()).unwrap_or_else(|| "someone".into()); + match action { + "la" | "lb" => { + let Some(letter) = values.first().and_then(|v| v.chars().next()).filter(|c| c.is_ascii_lowercase()) else { return Reply::Ignore }; + if self.over || self.guessed.contains(&letter) || self.misses.contains(&letter.to_string()) { + return Reply::Ignore; + } + if self.word.contains(letter) { + self.guessed.push(letter); + if self.won() { + self.solved_by = Some(name(self)); + self.over = true; + } + } else { + self.miss(letter.to_string()); + } + Reply::Update + } + "word" => Reply::Modal { action: "wordsub".into(), title: "Guess the whole word".into(), fields: vec![crate::interact::text_field("word", "The word is…", Some("A wrong guess costs a life"), "", 40, false, Some("Your answer"))] }, + "wordsub" => { + if self.over { + return Reply::Ignore; + } + let guess = fields.get("word").map(|w| w.trim().to_lowercase()).unwrap_or_default(); + if guess == self.word { + self.guessed.extend(self.word.chars()); + self.solved_by = Some(name(self)); + self.over = true; + } else if !guess.is_empty() { + self.miss(guess); + } + Reply::Update + } + "again" => Reply::Replace(Box::new(Self::new(self.setter.clone(), self.guessers.clone(), None, self.category.clone()))), + _ => Reply::Ignore, + } + } + + fn is_over(&self) -> bool { + self.over + } + + fn abandon(&mut self) { + self.timed_out = true; + self.over = true; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p(id: u64) -> P { + P { id, name: format!("p{id}"), bot: false } + } + + #[test] + fn letters_lives_and_winning() { + let mut g = Hangman::new(p(1), vec![p(1)], Some("cat".into()), None); + for l in ["c", "a"] { + g.click(1, "la", &[l.to_string()], &Default::default()); + } + assert!(!g.over); + g.click(1, "lb", &["z".into()], &Default::default()); + assert_eq!(g.lives, LIVES - 1); + g.click(1, "lb", &["t".into()], &Default::default()); + assert!(g.over && g.won()); + } + + #[test] + fn the_setter_cannot_guess_and_a_wrong_word_costs_a_life() { + let g = Hangman::new(p(1), vec![], Some("secret".into()), None); + assert!(g.allowed(1, "la").is_err() && g.allowed(2, "la").is_ok()); + let mut g = Hangman::new(p(1), vec![p(2)], Some("secret".into()), None); + g.click(2, "wordsub", &[], &HashMap::from([("word".to_string(), "nope".to_string())])); + assert_eq!(g.lives, LIVES - 1); + g.click(2, "wordsub", &[], &HashMap::from([("word".to_string(), "Secret".to_string())])); + assert!(g.over && g.won()); + } + + #[test] + fn six_misses_lose() { + let mut g = Hangman::new(p(1), vec![p(1)], Some("a".into()), None); + for l in ["b", "c", "d", "e", "f", "g"] { + g.click(1, "la", &[l.to_string()], &Default::default()); + } + assert!(g.over && !g.won()); + } + + #[test] + fn category_words_exist() { + let g = Hangman::new(p(1), vec![p(1)], None, Some("food".into())); + assert_eq!(g.category.as_deref(), Some("food")); + assert!(g.word.len() > 1); + } +} diff --git a/src/commands/games/minesweeper.rs b/src/commands/games/minesweeper.rs new file mode 100644 index 0000000..b213f31 --- /dev/null +++ b/src/commands/games/minesweeper.rs @@ -0,0 +1,276 @@ +//! Minesweeper on a 5×5 board. Your first click is always safe (mines are placed after it), and +//! **Flag mode** lets you mark mines. Best times are remembered per difficulty. +use super::*; +use crate::prefs; +use crate::ui::Card; +use rand::seq::SliceRandom; +use std::collections::BTreeSet; +use std::time::Instant; + +const SIZE: i32 = 5; +pub const DIFFICULTIES: [(&str, usize); 3] = [("easy", 3), ("medium", 5), ("hard", 8)]; +const NUMBERS: [&str; 9] = ["🟦", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣"]; + +type Cell = (i32, i32); + +fn neighbours((r, c): Cell) -> impl Iterator { + (-1..=1).flat_map(move |dr| (-1..=1).map(move |dc| (dr, dc))).filter(|(dr, dc)| *dr != 0 || *dc != 0).map(move |(dr, dc)| (r + dr, c + dc)).filter(|(r, c)| (0..SIZE).contains(r) && (0..SIZE).contains(c)) +} + +fn mines_for(d: &str) -> usize { + DIFFICULTIES.iter().find(|x| x.0 == d).map_or(3, |x| x.1) +} + +pub struct Minesweeper { + player: P, + difficulty: String, + mines: BTreeSet, + revealed: BTreeSet, + flags: BTreeSet, + flag_mode: bool, + boom: Option, + started: Option, + finished_in: Option, + best: Option, + over: bool, + timed_out: bool, +} + +/// Before a difficulty is chosen. +pub struct Picker { + player: P, +} + +impl Minesweeper { + pub fn start(player: P, difficulty: Option) -> Box { + match difficulty.filter(|d| DIFFICULTIES.iter().any(|x| x.0 == d)) { + Some(d) => Box::new(Self::new(player, d)), + None => Box::new(Picker { player }), + } + } + + fn new(player: P, difficulty: String) -> Self { + Self { player, difficulty, mines: BTreeSet::new(), revealed: BTreeSet::new(), flags: BTreeSet::new(), flag_mode: false, boom: None, started: None, finished_in: None, best: None, over: false, timed_out: false } + } + + fn count(&self, cell: Cell) -> usize { + neighbours(cell).filter(|n| self.mines.contains(n)).count() + } + + fn place_mines(&mut self, safe: Cell) { + let around: Vec = std::iter::once(safe).chain(neighbours(safe)).collect(); + let all: Vec = (0..SIZE).flat_map(|r| (0..SIZE).map(move |c| (r, c))).collect(); + let mut cells: Vec = all.iter().copied().filter(|c| !around.contains(c)).collect(); + let n = mines_for(&self.difficulty); + if cells.len() < n { + cells = all.into_iter().filter(|c| *c != safe).collect(); + } + cells.shuffle(&mut rand::rng()); + self.mines = cells.into_iter().take(n).collect(); + self.started = Some(Instant::now()); + } + + fn reveal(&mut self, cell: Cell) { + let mut stack = vec![cell]; + while let Some(cur) = stack.pop() { + if self.revealed.contains(&cur) || self.flags.contains(&cur) { + continue; + } + self.revealed.insert(cur); + if self.count(cur) == 0 { + stack.extend(neighbours(cur).filter(|n| !self.revealed.contains(n))); + } + } + } + + fn won(&self) -> bool { + self.revealed.len() == (SIZE * SIZE) as usize - self.mines.len() + } + + fn record(&mut self) { + let took = self.started.map_or(0.0, |s| s.elapsed().as_secs_f64()); + self.finished_in = Some(took); + let key = format!("minesweeper_best_{}", self.difficulty); + self.best = prefs::user_pref(self.player.id, &key).and_then(|v| v.as_f64()); + if self.best.is_none_or(|b| took < b) { + prefs::set_user_pref(self.player.id, &key, Some(serde_json::json!((took * 100.0).round() / 100.0))); + } + } +} + +impl Game for Minesweeper { + fn players(&self) -> Vec { + vec![self.player.id] + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(600) + } + + fn render(&self, t: u32) -> Rendered { + let mines = mines_for(&self.difficulty); + let (status, accent) = if self.boom.is_some() { + ("💥 **Boom!** You hit a mine.".to_string(), LOSE) + } else if self.over && self.won() { + let took = self.finished_in.unwrap_or(0.0); + let record = if self.best.is_none_or(|b| took <= b) { " — **new best!** 🏅".to_string() } else { format!(" (best {:.1}s)", self.best.unwrap_or(0.0)) }; + (format!("🎉 **Cleared in {took:.1}s!**{record}"), WIN) + } else if self.timed_out { + ("Game abandoned.".to_string(), LOSE) + } else { + (format!("💣 {mines} mines · 🚩 {} flagged{}", self.flags.len(), if self.flag_mode { " · **flag mode on** — clicks place flags" } else { "" }), BLURPLE) + }; + let title: String = self.difficulty[..1].to_uppercase() + &self.difficulty[1..]; + let mut card = Card::new(Some(accent)).text(&format!("### 💣 Minesweeper · {title}\n{status}")); + for r in 0..SIZE { + let mut buttons = Vec::new(); + for c in 0..SIZE { + let cell = (r, c); + let (mut style, mut emoji, mut disabled) = (ButtonStyle::Secondary, "⬜", self.over); + if Some(cell) == self.boom { + (emoji, style) = ("💥", ButtonStyle::Danger); + } else if self.over && self.mines.contains(&cell) { + emoji = if self.flags.contains(&cell) { "🚩" } else { "💣" }; + style = if self.flags.contains(&cell) { ButtonStyle::Success } else { ButtonStyle::Secondary }; + } else if self.revealed.contains(&cell) { + (emoji, disabled) = (NUMBERS[self.count(cell)], true); + } else if self.flags.contains(&cell) { + (emoji, style) = ("🚩", ButtonStyle::Primary); + } + buttons.push(btn(t, &format!("c{r}{c}"), "", emoji, style, disabled)); + } + card = card.row(buttons); + } + card = if !self.over { + card.row(vec![btn(t, "flag", if self.flag_mode { "Flag mode: on" } else { "Flag mode: off" }, "🚩", if self.flag_mode { ButtonStyle::Primary } else { ButtonStyle::Secondary }, false)]) + } else { + card.row(vec![again(t, "New board")]) + }; + card.into() + } + + fn click(&mut self, _: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + match action { + "flag" => { + self.flag_mode = !self.flag_mode; + Reply::Update + } + "again" => Reply::Replace(Box::new(Self::new(self.player.clone(), self.difficulty.clone()))), + a => { + let digits: Vec = a.strip_prefix('c').unwrap_or("").chars().filter_map(|d| d.to_digit(10)).map(|d| d as i32).collect(); + let [r, c] = digits[..] else { return Reply::Ignore }; + let cell = (r, c); + if self.over || self.revealed.contains(&cell) { + return Reply::Ignore; + } + if self.flag_mode { + if !self.flags.remove(&cell) { + self.flags.insert(cell); + } + } else if !self.flags.contains(&cell) { + if self.mines.is_empty() { + self.place_mines(cell); + } + if self.mines.contains(&cell) { + self.boom = Some(cell); + self.over = true; + } else { + self.reveal(cell); + if self.won() { + self.over = true; + self.record(); + } + } + } + Reply::Update + } + } + } + + fn is_over(&self) -> bool { + self.over + } + + fn abandon(&mut self) { + self.timed_out = true; + self.over = true; + } +} + +impl Game for Picker { + fn players(&self) -> Vec { + vec![self.player.id] + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(120) + } + + fn render(&self, t: u32) -> Rendered { + let styles = [ButtonStyle::Success, ButtonStyle::Primary, ButtonStyle::Danger]; + let buttons = DIFFICULTIES.iter().zip(styles).map(|((d, n), s)| btn(t, &format!("d_{d}"), &format!("{} ({n} mines)", d[..1].to_uppercase() + &d[1..]), "", s, false)).collect(); + Card::new(Some(BLURPLE)).text("### 💣 Minesweeper\nPick a difficulty — your first click is always safe.").row(buttons).into() + } + + fn click(&mut self, _: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + match action.strip_prefix("d_") { + Some(d) if DIFFICULTIES.iter().any(|x| x.0 == d) => Reply::Replace(Box::new(Minesweeper::new(self.player.clone(), d.to_string()))), + _ => Reply::Ignore, + } + } + + fn is_over(&self) -> bool { + false + } + + fn abandon(&mut self) {} +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p() -> P { + P { id: 1, name: "me".into(), bot: false } + } + + #[test] + fn the_first_click_is_safe_and_wins_are_detected() { + for _ in 0..50 { + let mut g = Minesweeper::new(p(), "hard".into()); + g.click(1, "c22", &[], &Default::default()); + assert!(g.boom.is_none() && g.mines.len() == 8 && !g.mines.contains(&(2, 2))); + // click every safe cell + let safe: Vec = (0..SIZE).flat_map(|r| (0..SIZE).map(move |c| (r, c))).filter(|c| !g.mines.contains(c)).collect(); + for (r, c) in safe { + g.click(1, &format!("c{r}{c}"), &[], &Default::default()); + } + assert!(g.over && g.won() && g.boom.is_none()); + } + } + + #[test] + fn hitting_a_mine_ends_the_game_and_flags_protect_cells() { + let mut g = Minesweeper::new(p(), "easy".into()); + g.click(1, "c00", &[], &Default::default()); + let mine = *g.mines.iter().next().unwrap(); + g.click(1, "flag", &[], &Default::default()); + g.click(1, &format!("c{}{}", mine.0, mine.1), &[], &Default::default()); + assert!(g.flags.contains(&mine) && !g.over); + g.click(1, "flag", &[], &Default::default()); + g.click(1, &format!("c{}{}", mine.0, mine.1), &[], &Default::default()); // flagged: ignored + assert!(!g.over); + g.click(1, "flag", &[], &Default::default()); + g.click(1, &format!("c{}{}", mine.0, mine.1), &[], &Default::default()); // unflag + g.click(1, "flag", &[], &Default::default()); + g.click(1, &format!("c{}{}", mine.0, mine.1), &[], &Default::default()); + assert_eq!(g.boom, Some(mine)); + } + + #[test] + fn the_picker_starts_a_board() { + let mut pk = Picker { player: p() }; + assert!(matches!(pk.click(1, "d_medium", &[], &Default::default()), Reply::Replace(_))); + assert!(matches!(pk.click(1, "d_nope", &[], &Default::default()), Reply::Ignore)); + } +} diff --git a/src/commands/games/mod.rs b/src/commands/games/mod.rs new file mode 100644 index 0000000..668e428 --- /dev/null +++ b/src/commands/games/mod.rs @@ -0,0 +1,632 @@ +//! The arcade: `/startgame` or `D!game [@opponent]` — and a shortcut per game (`D!ttt`, `D!c4`, +//! `D!chess @friend`, `D!wordle`, `D!2048`, `D!cookie` …). +//! +//! Two-player games without an opponent are played against Dezio. This file is the engine every game +//! plugs into: a game is a struct that draws itself as a card and reacts to button clicks; the engine keeps +//! the games in memory (like the Python views), checks who may press what, edits the message, and ends games +//! nobody touches for a while. Buttons carry `gm::`. +mod aki; +pub mod casino; +mod chess; +mod classic; +mod cookie; +mod hangman; +mod minesweeper; +mod numbers; +mod words; + +use super::info::display_name_of; +use crate::bail_user; +use crate::cmd::{Command, Ctx, Opt, OptKind, Origin}; +use crate::converters::find_member; +use crate::interact; +use crate::state::State; +use crate::ui::{button, escape, Card}; +use anyhow::Result; +use futures::future::BoxFuture; +use futures::FutureExt; +use serde_json::{json, Value}; +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; +use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_model::channel::message::component::{Button, ButtonStyle, Component}; +use twilight_model::channel::message::{AllowedMentions, EmojiReactionType, MessageFlags}; +use twilight_model::http::attachment::Attachment; +use twilight_model::id::marker::{ChannelMarker, MessageMarker, UserMarker}; +use twilight_model::id::Id; + +pub const BLURPLE: u32 = 0x5865F2; +pub const WIN: u32 = 0x57F287; +pub const LOSE: u32 = 0xED4245; +pub const DRAW: u32 = 0xF1C40F; + +/// A person in a game. +#[derive(Clone, Debug, PartialEq)] +pub struct P { + pub id: u64, + pub name: String, + pub bot: bool, +} + +impl P { + pub fn name(&self) -> String { + escape(&self.name) + } +} + +pub struct Rendered { + pub card: Card, + pub file: Option<(String, Vec)>, +} + +impl From for Rendered { + fn from(card: Card) -> Self { + Self { card, file: None } + } +} + +pub enum Reply { + /// Redraw the card. + Update, + /// Redraw, then tell the clicker something privately. + UpdateAndNote(String), + /// Nothing changed (acknowledge the click). + Ignore, + /// A private message (an error, usually). + Private(String), + /// A form; its submit comes back to `click` as `action` with the typed values in `fields`. + Modal { action: String, title: String, fields: Vec }, + /// A new game takes this one's place (rematch, new word…). + Replace(Box), + /// This game is finished with and a new one starts in a fresh message (casino "Play again"). + Spawn(Box), + /// Slow work (a web request): the click is acknowledged, then this runs and gives the real reply. + Defer(BoxFuture<'static, Reply>), +} + +pub trait Game: Send { + /// Who may press the buttons (empty = anyone). + fn players(&self) -> Vec; + fn render(&self, token: u32) -> Rendered; + fn click(&mut self, who: u64, action: &str, values: &[String], fields: &HashMap) -> Reply; + fn is_over(&self) -> bool; + /// Nobody played for a while. + fn abandon(&mut self); + /// A chat message in the game's channel (games that listen for typed answers). True = the card changed. + fn chat(&mut self, _who: u64, _text: &str) -> bool { + false + } + /// The game was dropped before it ever showed up (give back whatever it took). + fn discard(&mut self) {} + fn idle_timeout(&self) -> Duration { + Duration::from_secs(300) + } + /// A hard stop (a timer in the game itself). + fn deadline(&self) -> Option { + None + } + fn on_deadline(&mut self) {} + /// Can this person press this? `Err` is shown to them privately. + fn allowed(&self, who: u64, _action: &str) -> Result<(), String> { + let p = self.players(); + if p.is_empty() || p.contains(&who) { Ok(()) } else { Err("You're not in this game — start your own with `/startgame`.".into()) } + } +} + +// ---- helpers the games share ----------------------------------------------------------------------------- + +pub fn btn(token: u32, action: &str, label: &str, emoji: &str, style: ButtonStyle, disabled: bool) -> Button { + let mut b = button(&format!("gm:{token}:{action}"), label, style); + if label.is_empty() { + b.label = None; + } + if !emoji.is_empty() { + b.emoji = Some(EmojiReactionType::Unicode { name: emoji.into() }); + } + b.disabled = disabled; + b +} + +/// A dropdown choice without an emoji. +pub fn opt(label: &str, value: &str) -> twilight_model::channel::message::component::SelectMenuOption { + twilight_model::channel::message::component::SelectMenuOption { default: false, description: None, emoji: None, label: label.into(), value: value.into() } +} + +/// The word lists and other game data (assets/data/games.json). +pub fn data() -> &'static Value { + static D: OnceLock = OnceLock::new(); + D.get_or_init(|| crate::storage::read_json(&crate::paths::asset(&["data", "games.json"])).unwrap_or(Value::Null)) +} + +pub fn pick(items: &[T]) -> T { + use rand::RngExt as _; + items[rand::rng().random_range(0..items.len())].clone() +} + +pub fn again(token: u32, label: &str) -> Button { + btn(token, "again", label, "🔁", ButtonStyle::Success, false) +} + +pub fn bot_player(state: &State) -> P { + P { id: state.bot_id().get(), name: "Dezio".into(), bot: true } +} + +/// Switch every button and menu off, except the ones that must stay usable after the game ends. +fn disable_all(card: &Component) -> Component { + let mut v = serde_json::to_value(card).unwrap_or(Value::Null); + fn walk(v: &mut Value) { + match v { + Value::Object(o) => { + let kind = o.get("type").and_then(Value::as_u64); + let keep = o.get("custom_id").and_then(Value::as_str).is_some_and(|c| c.ends_with(":again") || c.ends_with(":pgn")); + let link = o.get("url").is_some(); + if matches!(kind, Some(2 | 3 | 5 | 6 | 7 | 8)) && !keep && !link { + o.insert("disabled".into(), json!(true)); + } + o.values_mut().for_each(walk); + } + Value::Array(a) => a.iter_mut().for_each(walk), + _ => {} + } + } + walk(&mut v); + serde_json::from_value(v).unwrap_or_else(|_| card.clone()) +} + +fn present(token: u32, game: &dyn Game) -> (Component, Option<(String, Vec)>) { + let r = game.render(token); + let card = r.card.build(); + (if game.is_over() { disable_all(&card) } else { card }, r.file) +} + +// ---- sessions ----------------------------------------------------------------------------------------------- + +struct Session { + game: Box, + loc: Option<(Id, Id)>, + last: Instant, + done: bool, +} + +fn sessions() -> &'static Mutex> { + static S: OnceLock>> = OnceLock::new(); + S.get_or_init(Default::default) +} + +fn lock() -> std::sync::MutexGuard<'static, HashMap> { + sessions().lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Post a game card and remember the game. +pub async fn launch(ctx: &Ctx, game: Box, challenged: Option<(u64, &str)>) -> Result<()> { + let token = rand::random::(); + let (card, file) = present(token, game.as_ref()); + let files: Vec = file.into_iter().map(|(n, b)| Attachment::from_bytes(n, b, 1)).collect(); + let no_pings = AllowedMentions::default(); + let state = &ctx.state; + let (channel, message) = match &ctx.origin { + Origin::Message { channel_id } => { + let m = state.http.create_message(*channel_id).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]).attachments(&files).allowed_mentions(Some(&no_pings)).await?.model().await?; + (*channel_id, m.id) + } + Origin::Interaction { token: itoken, .. } => { + ctx.defer().await?; + let m = state.http.interaction(state.app_id()).create_followup(itoken).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]).attachments(&files).allowed_mentions(Some(&no_pings)).await?.model().await?; + (ctx.channel_id, m.id) + } + }; + { + let mut all = lock(); + all.retain(|_, s| !(s.done && s.last.elapsed() > Duration::from_secs(3600))); + all.insert(token, Session { game, loc: Some((channel, message)), last: Instant::now(), done: false }); + } + if let Some((id, who)) = challenged { + let text = format!("🎮 <@{id}>, {} challenged you!", escape(who)); + let allow = AllowedMentions { users: vec![Id::new(id)], parse: vec![], ..Default::default() }; + if let Ok(r) = state.http.create_message(channel).content(&text).allowed_mentions(Some(&allow)).await { + if let Ok(m) = r.model().await { + let (http, c, id) = (state.http.clone(), m.channel_id, m.id); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(60)).await; + let _ = http.delete_message(c, id).await; + }); + } + } + } + Ok(()) +} + +/// Redraw a game's message from the bot (timers and timeouts, no interaction involved). +async fn push(state: &State, token: u32) { + let (card, file, loc) = { + let all = lock(); + let Some(s) = all.get(&token) else { return }; + let (c, f) = present(token, s.game.as_ref()); + (c, f, s.loc) + }; + let Some((channel, message)) = loc else { return }; + let files: Vec = file.into_iter().map(|(n, b)| Attachment::from_bytes(n, b, 1)).collect(); + let comps = [card]; + let mut req = state.http.update_message(channel, message).components(Some(&comps)); + if !files.is_empty() { + req = req.attachments(&files); + } + if let Err(e) = req.await { + tracing::debug!("couldn't redraw a game: {e}"); + } +} + +/// Ends games nobody plays and runs in-game timers. Started once. +pub fn start_watch(state: Arc) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tokio::spawn(async move { + loop { + tokio::time::sleep(Duration::from_millis(500)).await; + let mut redraw = Vec::new(); + { + let mut all = lock(); + for (token, s) in all.iter_mut() { + if s.done { + continue; + } + if s.game.is_over() { + s.done = true; + continue; + } + if s.game.deadline().is_some_and(|d| Instant::now() >= d) { + s.game.on_deadline(); + s.done = s.game.is_over(); + redraw.push(*token); + } else if s.last.elapsed() > s.game.idle_timeout() { + s.game.abandon(); + s.done = true; + redraw.push(*token); + } + } + } + for t in redraw { + push(&state, t).await; + } + } + }); + }); +} + +/// Typed answers: every message in a channel with a listening game goes to it. +pub async fn on_chat(state: Arc, m: twilight_model::channel::Message) { + if m.author.bot || m.content.is_empty() { + return; + } + let prefix = state.prefix(m.guild_id); + if m.content.get(..prefix.len()).is_some_and(|h| h.eq_ignore_ascii_case(&prefix)) { + return; + } + let changed: Vec = { + let mut all = lock(); + all.iter_mut() + .filter(|(_, s)| !s.done && s.loc.is_some_and(|l| l.0 == m.channel_id)) + .filter_map(|(t, s)| { + let c = s.game.chat(m.author.id.get(), &m.content); + if c { + s.last = Instant::now(); + s.done = s.game.is_over(); + } + c.then_some(*t) + }) + .collect() + }; + for t in changed { + push(&state, t).await; + } +} + +// ---- clicks ------------------------------------------------------------------------------------------------------ + +async fn edit_from(state: &State, i: &Interaction, token: u32) { + let (card, file) = { + let all = lock(); + let Some(s) = all.get(&token) else { return }; + present(token, s.game.as_ref()) + }; + match file { + Some((name, bytes)) => interact::edit_with_file(state, i, card, &name, bytes).await, + None => { + let r = state.http.interaction(state.app_id()).update_response(&i.token).components(Some(&[card])).await; + if let Err(e) = r { + tracing::warn!("couldn't update a game: {e}"); + } + } + } +} + +pub async fn on_component(state: &Arc, i: &Interaction) { + let (custom_id, values, fields) = match i.data.as_ref() { + Some(InteractionData::MessageComponent(d)) => (d.custom_id.clone(), d.values.clone(), HashMap::new()), + Some(InteractionData::ModalSubmit(d)) => (d.custom_id.clone(), vec![], interact::modal_values(d)), + _ => return, + }; + let mut p = custom_id.splitn(3, ':').skip(1); + let (Some(token), Some(action)) = (p.next().and_then(|t| t.parse::().ok()), p.next()) else { return }; + let Some(user) = i.author() else { return }; + let outcome: Result = { + let mut all = lock(); + match all.get_mut(&token) { + None => Err("This game has ended — start a new one with `/startgame`.".into()), + Some(s) => match s.game.allowed(user.id.get(), action) { + Err(text) => Err(text), + Ok(()) => { + s.last = Instant::now(); + Ok(s.game.click(user.id.get(), action, &values, &fields)) + } + }, + } + }; + let reply = match outcome { + Ok(r) => r, + Err(text) => return interact::private_text(state, i, &text).await, + }; + respond(state, i, token, reply).await; +} + +fn respond<'a>(state: &'a Arc, i: &'a Interaction, token: u32, reply: Reply) -> BoxFuture<'a, ()> { + async move { + match reply { + Reply::Ignore => interact::ack(state, i).await, + Reply::Private(t) => interact::private_text(state, i, &t).await, + Reply::Modal { action, title, fields } => interact::modal(state, i, &format!("gm:{token}:{action}"), &title, fields).await, + Reply::Update => { + interact::ack(state, i).await; + edit_from(state, i, token).await; + mark_done(token); + } + Reply::UpdateAndNote(note) => { + interact::ack(state, i).await; + edit_from(state, i, token).await; + interact::followup_text(state, i, ¬e).await; + mark_done(token); + } + Reply::Replace(game) => { + if let Some(s) = lock().get_mut(&token) { + s.game = game; + s.last = Instant::now(); + s.done = false; + } + interact::ack(state, i).await; + edit_from(state, i, token).await; + } + Reply::Spawn(game) => { + interact::ack(state, i).await; + edit_from(state, i, token).await; + mark_done(token); + spawn_followup(state, i, game).await; + } + Reply::Defer(fut) => { + interact::ack(state, i).await; + let next = fut.await; + match next { + Reply::Update | Reply::Replace(_) | Reply::UpdateAndNote(_) => { + let note = if let Reply::UpdateAndNote(n) = &next { Some(n.clone()) } else { None }; + if let Reply::Replace(g) = next { + if let Some(s) = lock().get_mut(&token) { + s.game = g; + s.done = false; + } + } + edit_from(state, i, token).await; + if let Some(n) = note { + interact::followup_text(state, i, &n).await; + } + mark_done(token); + } + Reply::Private(t) => interact::followup_text(state, i, &t).await, + _ => {} + } + } + } + } + .boxed() +} + +/// Post a new game as a follow-up to the clicked message. +async fn spawn_followup(state: &Arc, i: &Interaction, mut game: Box) { + let token = rand::random::(); + let (card, file) = present(token, game.as_ref()); + let files: Vec = file.into_iter().map(|(n, b)| Attachment::from_bytes(n, b, 1)).collect(); + let sent = state.http.interaction(state.app_id()).create_followup(&i.token).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]).attachments(&files).allowed_mentions(Some(&AllowedMentions::default())).await; + match sent { + Ok(r) => { + if let Ok(m) = r.model().await { + lock().insert(token, Session { game, loc: Some((m.channel_id, m.id)), last: Instant::now(), done: false }); + return; + } + game.discard(); + } + Err(_) => game.discard(), + } +} + +fn mark_done(token: u32) { + if let Some(s) = lock().get_mut(&token) { + if s.game.is_over() { + s.done = true; + } + } +} + +// ---- starting games --------------------------------------------------------------------------------------------------- + +/// (key, label, prefix names, opponent, help) +pub const GAMES: [(&str, &str, &[&str], &str, &str); 11] = [ + ("tictactoe", "❌ Tic-tac-toe", &["ttt", "tictactoe"], "optional", "Tic-tac-toe vs a friend or Dezio."), + ("connect4", "🔴 Connect 4", &["c4", "connect4"], "optional", "Connect 4 vs a friend or Dezio."), + ("rps", "✂️ Rock paper scissors", &["rps"], "optional", "Best of 3 vs a friend or Dezio."), + ("chess", "♟️ Chess", &["chess"], "required", "Chess vs a friend (pick pieces or type moves)."), + ("hangman", "🪢 Hangman", &["hangman"], "optional", "Guess the word letter by letter."), + ("unscramble", "🔠 Word unscramble", &["unscramble", "scramble"], "optional", "Unscramble a word in 90 seconds."), + ("wordle", "🟩 Wordle", &["wordle"], "none", "Guess the 5-letter word in 6 tries."), + ("minesweeper", "💣 Minesweeper", &["minesweeper", "mines", "ms"], "none", "Clear the board without hitting a mine."), + ("2048", "🔢 2048", &["2048"], "none", "Slide and merge tiles to reach 2048."), + ("akinator", "🧞 Akinator", &["akinator", "aki"], "none", "Akinator guesses who you're thinking of."), + ("cookie", "🍪 Cookie Clicker", &["cookie", "cookies", "cookieclicker"], "none", "Bake cookies — keeps going while you're away."), +]; + +async fn start_game(ctx: &Arc, key: &str, opponent: Option>, word: Option, category: Option) -> Result<()> { + let state = &ctx.state; + let me = P { id: ctx.user_id.get(), name: display_name_of(state, ctx.guild_id, ctx.user_id).await, bot: false }; + let need = GAMES.iter().find(|g| g.0 == key).map_or("none", |g| g.3); + let label = GAMES.iter().find(|g| g.0 == key).map_or("That game", |g| g.1); + let rival: Option

= match opponent { + Some(o) => { + let is_bot = state.cache.user(o).map(|u| u.bot).unwrap_or(false); + if o == ctx.user_id || (is_bot && o != state.bot_id()) { + return ctx.fail("❌ Pick a real person (not yourself) — or nobody to play me.").await; + } + Some(P { id: o.get(), name: display_name_of(state, ctx.guild_id, o).await, bot: o == state.bot_id() }) + } + None => None, + }; + if need == "required" && rival.is_none() { + return ctx.fail(&format!("❌ {label} needs an opponent.")).await; + } + let nsfw = ctx.guild_id.is_some() && state.cache.channel(ctx.channel_id).is_some_and(|c| c.nsfw.unwrap_or(false)); + let vs = rival.clone().unwrap_or_else(|| bot_player(state)); + let challenge = rival.as_ref().filter(|r| !r.bot && matches!(key, "tictactoe" | "connect4" | "rps" | "chess")).map(|r| (r.id, me.name.clone())); + let game: Box = match key { + "tictactoe" => classic::Ttt::start(me, vs), + "connect4" => classic::Connect4::start(me, vs), + "rps" => classic::Rps::start(me, vs), + "chess" => chess::Chess_::start(me, rival.unwrap()), + "hangman" => hangman::Hangman::start(me, rival, word, category), + "unscramble" => words::Unscramble::start(me, rival), + "wordle" => words::Wordle::start(me), + "minesweeper" => minesweeper::Minesweeper::start(me, category), + "2048" => numbers::Game2048::start(me), + "akinator" => { + ctx.defer().await?; + match aki::start(state, me, category, !nsfw).await { + Ok(g) => g, + Err(e) => return ctx.fail(&format!("⚠️ Akinator isn't available right now: {e}")).await, + } + } + "cookie" => return cookie::start(ctx).await, + _ => bail_user!("Unknown game."), + }; + launch(ctx, game, challenge.as_ref().map(|(i, n)| (*i, n.as_str()))).await +} + +async fn prefix_start(ctx: Arc, key: &str, args: &str) -> Result<()> { + let (mut opponent, mut extra) = (None, None); + for word in args.split_whitespace() { + let member = ctx.guild_id.and_then(|g| find_member(&ctx.state.cache, g, word)); + match member { + Some(m) if opponent.is_none() => opponent = Some(m), + _ => extra = Some(word.to_lowercase()), + } + } + if key == "wordle" { + extra = None; + } + start_game(&ctx, key, opponent, None, extra).await +} + +async fn shortcut(ctx: Arc) -> Result<()> { + let key = GAMES.iter().find(|g| g.2.contains(&ctx.invoked)).map(|g| g.0).unwrap_or("tictactoe"); + let args = ctx.args.str("args").unwrap_or("").to_string(); + prefix_start(ctx, key, &args).await +} + +async fn startgame(ctx: Arc) -> Result<()> { + let key = ctx.args.str("game").unwrap_or("").to_string(); + if !GAMES.iter().any(|g| g.0 == key) { + bail_user!("Pick a game from the list."); + } + start_game(&ctx, &key, ctx.args.user("opponent"), ctx.args.str("word").map(str::to_string), ctx.args.str("category").map(|s| s.to_lowercase())).await +} + +async fn game_list(ctx: Arc) -> Result<()> { + let args = ctx.args.str("args").unwrap_or("").to_string(); + let (name, rest) = args.split_once(char::is_whitespace).map_or((args.as_str(), ""), |(a, b)| (a, b)); + let name = name.to_lowercase(); + if let Some(g) = GAMES.iter().find(|g| g.0 == name || g.2.contains(&name.as_str())) { + return prefix_start(ctx.clone(), g.0, rest).await; + } + let p = ctx.state.prefix(ctx.guild_id); + let lines: Vec = GAMES.iter().map(|(_, label, aliases, need, help)| format!("**{label}** — `{p}{}`{} · {help}", aliases[0], if *need == "required" { " @someone" } else { "" })).collect(); + ctx.reply(Card::new(Some(BLURPLE)).text(&format!("### 🎮 Arcade\n{}", lines.join("\n"))).footer("Two-player games without an opponent are played against me · also /startgame").build()).await +} + +fn suggest_category(_: Arc, _focused: String, current: String, _: Option>, _: Id) -> BoxFuture<'static, Vec<(String, String)>> { + async move { + let current = current.to_lowercase(); + let mut all: Vec = hangman::categories(); + all.extend(minesweeper::DIFFICULTIES.iter().map(|(d, _)| d.to_string())); + all.extend(aki::THEMES.iter().map(|(t, _)| t.to_string())); + all.dedup(); + all.into_iter().filter(|o| o.starts_with(¤t)).take(25).map(|o| (o.clone(), o)).collect() + } + .boxed() +} + +pub fn commands() -> Vec { + let choices: &'static [&'static str] = Box::leak(GAMES.iter().map(|g| g.0).collect::>().into_boxed_slice()); + let mut v = vec![ + Command::new("startgame", "games", "Play a game: chess, Connect 4, Wordle, 2048, Akinator and more", |c| startgame(c).boxed()) + .usage(" [@opponent]") + .opt(Opt::req("game", "Which game", OptKind::String).choices(choices).slash_only()) + .opt(Opt::opt("opponent", "Who to play (empty: play Dezio where possible)", OptKind::User).slash_only()) + .opt(Opt::opt("word", "Hangman: a secret word for your opponent to guess", OptKind::String).slash_only()) + .opt(Opt::opt("category", "Hangman category · Minesweeper difficulty · Akinator theme", OptKind::String).autocomplete().slash_only()) + .suggest(suggest_category), + Command::new("game", "games", "Start a game: `game chess @friend`, `game wordle` … — `game` alone lists them all.", |c| game_list(c).boxed()) + .aliases(&["games", "arcade"]) + .usage(" [@opponent]") + .opt(Opt::opt("args", "The game and an opponent", OptKind::String)) + .prefix_only(), + ]; + v.extend(casino::commands()); + v +} + +/// One shortcut command per game; names other commands already have are skipped. +pub fn late_commands(taken: &mut HashSet) -> Vec { + let mut out = Vec::new(); + for (_, _, aliases, need, help) in GAMES { + let usage: &'static str = match need { + "optional" => "[@opponent]", + "required" => "<@opponent>", + _ => "", + }; + let names: Vec<&'static str> = aliases.iter().copied().filter(|a| !taken.contains(&a.to_lowercase())).collect(); + let Some((first, rest)) = names.split_first() else { continue }; + taken.extend(names.iter().map(|n| n.to_lowercase())); + let rest: &'static [&'static str] = Box::leak(rest.to_vec().into_boxed_slice()); + out.push(Command::new(first, "games", help, |c| shortcut(c).boxed()).aliases(rest).usage(usage).opt(Opt::opt("args", "An opponent or an option", OptKind::String)).prefix_only()); + } + out +} + +pub async fn on_cookie(state: &Arc, i: &Interaction) { + cookie::on_component(state, i).await +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finished_games_keep_only_the_rematch_buttons() { + let card = Card::new(None).text("x").row(vec![btn(1, "m0", "A", "", ButtonStyle::Primary, false), again(1, "Rematch")]).build(); + let off = serde_json::to_string(&disable_all(&card)).unwrap(); + assert_eq!(off.matches("\"disabled\":true").count(), 1, "{off}"); + } + + #[test] + fn every_game_has_a_shortcut_name() { + let mut taken = HashSet::new(); + let cmds = late_commands(&mut taken); + assert_eq!(cmds.len(), GAMES.len()); + assert!(late_commands(&mut taken).is_empty(), "names are only handed out once"); + } +} diff --git a/src/commands/games/numbers.rs b/src/commands/games/numbers.rs new file mode 100644 index 0000000..6a8b6cf --- /dev/null +++ b/src/commands/games/numbers.rs @@ -0,0 +1,247 @@ +//! 2048: slide the tiles with the arrows; equal tiles merge. Reach 2048 to win (you can keep going). Your best +//! score is remembered. +use super::*; +use crate::pix; +use crate::prefs; +use crate::text::{self, Look}; +use crate::ui::Card; +use cosmic_text::Align; +use image::{Rgba, RgbaImage}; +use rand::RngExt as _; + +const SIZE: usize = 4; +const TILE: i32 = 96; +const GAP: i32 = 12; +const PAD: i32 = 16; +const BOARD_PX: i32 = PAD * 2 + TILE * SIZE as i32 + GAP * (SIZE as i32 - 1); + +type Grid = [[u32; SIZE]; SIZE]; + +fn slide_row(row: [u32; SIZE]) -> ([u32; SIZE], u32) { + let tiles: Vec = row.iter().copied().filter(|t| *t > 0).collect(); + let (mut merged, mut score, mut i) = (Vec::new(), 0, 0); + while i < tiles.len() { + if i + 1 < tiles.len() && tiles[i] == tiles[i + 1] { + merged.push(tiles[i] * 2); + score += tiles[i] * 2; + i += 2; + } else { + merged.push(tiles[i]); + i += 1; + } + } + let mut out = [0; SIZE]; + out[..merged.len()].copy_from_slice(&merged); + (out, score) +} + +fn tile_colour(v: u32) -> Rgba { + let c = match v { + 2 => (238, 228, 218), 4 => (237, 224, 200), 8 => (242, 177, 121), 16 => (245, 149, 99), 32 => (246, 124, 95), 64 => (246, 94, 59), + 128 => (237, 207, 114), 256 => (237, 204, 97), 512 => (237, 200, 80), 1024 => (237, 197, 63), 2048 => (237, 194, 46), _ => (60, 58, 50), + }; + Rgba([c.0, c.1, c.2, 255]) +} + +fn render_board(grid: &Grid) -> Vec { + let mut img = RgbaImage::from_pixel(BOARD_PX as u32, BOARD_PX as u32, Rgba([187, 173, 160, 255])); + for r in 0..SIZE { + for c in 0..SIZE { + let v = grid[r][c]; + let (x, y) = (PAD + c as i32 * (TILE + GAP), PAD + r as i32 * (TILE + GAP)); + pix::rounded_rect(&mut img, x, y, TILE, TILE, 8, if v > 0 { tile_colour(v) } else { Rgba([205, 193, 180, 255]) }); + if v > 0 { + let size = if v < 100 { 44.0 } else if v < 1000 { 36.0 } else if v < 10000 { 28.0 } else { 22.0 }; + let ink = if v < 8 { [119, 110, 101] } else { [249, 246, 242] }; + let look = Look::new(None, true, ink); + let s = v.to_string(); + let w = text::width_of(&s, size, &look); + text::layout(&s, size, &look, None, Align::Left).draw(&mut img, x + ((TILE as f32 - w) / 2.0) as i32, y + ((TILE as f32 - size * 1.25) / 2.0) as i32); + } + } + } + pix::encode_png(&img) +} + +pub struct Game2048 { + player: P, + grid: Grid, + score: u32, + moves: u32, + won: bool, + best: u32, + over: bool, + timed_out: bool, +} + +impl Game2048 { + pub fn start(player: P) -> Box { + Box::new(Self::new(player)) + } + + fn new(player: P) -> Self { + let best = prefs::user_pref(player.id, "best_2048").and_then(|v| v.as_u64()).unwrap_or(0) as u32; + let mut g = Self { player, grid: [[0; SIZE]; SIZE], score: 0, moves: 0, won: false, best, over: false, timed_out: false }; + g.spawn(); + g.spawn(); + g + } + + fn spawn(&mut self) { + let empty: Vec<(usize, usize)> = (0..SIZE).flat_map(|r| (0..SIZE).map(move |c| (r, c))).filter(|(r, c)| self.grid[*r][*c] == 0).collect(); + if empty.is_empty() { + return; + } + let mut rng = rand::rng(); + let (r, c) = empty[rng.random_range(0..empty.len())]; + self.grid[r][c] = if rng.random_bool(0.1) { 4 } else { 2 }; + } + + fn can_move(&self) -> bool { + (0..SIZE).any(|r| (0..SIZE).any(|c| { + let v = self.grid[r][c]; + v == 0 || (c + 1 < SIZE && self.grid[r][c + 1] == v) || (r + 1 < SIZE && self.grid[r + 1][c] == v) + })) + } + + /// Slide everything one way. False if nothing moved. + fn slide(&mut self, dir: &str) -> bool { + let g = self.grid; + let line = |i: usize| -> [u32; SIZE] { + match dir { + "left" => g[i], + "right" => [g[i][3], g[i][2], g[i][1], g[i][0]], + "up" => [g[0][i], g[1][i], g[2][i], g[3][i]], + _ => [g[3][i], g[2][i], g[1][i], g[0][i]], + } + }; + let mut new = [[0; SIZE]; SIZE]; + let (mut moved, mut gained) = (false, 0); + for i in 0..SIZE { + let before = line(i); + let (after, s) = slide_row(before); + moved |= after != before; + gained += s; + for (k, v) in after.iter().enumerate() { + match dir { + "left" => new[i][k] = *v, + "right" => new[i][3 - k] = *v, + "up" => new[k][i] = *v, + _ => new[3 - k][i] = *v, + } + } + } + if !moved { + return false; + } + self.grid = new; + self.score += gained; + self.moves += 1; + self.spawn(); + if self.grid.iter().flatten().any(|v| *v >= 2048) { + self.won = true; + } + if !self.can_move() { + self.over = true; + self.save_best(); + } + true + } + + fn save_best(&self) { + if self.score > self.best { + prefs::set_user_pref(self.player.id, "best_2048", Some(serde_json::json!(self.score))); + } + } +} + +impl Game for Game2048 { + fn players(&self) -> Vec { + vec![self.player.id] + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(600) + } + + fn render(&self, t: u32) -> Rendered { + let biggest = self.grid.iter().flatten().max().copied().unwrap_or(0); + let thousands = crate::converters::thousands; + let (status, accent) = if self.over && !self.timed_out { + (format!("💀 **No moves left!** Final score **{}**{}", thousands(self.score as u64), if self.score > self.best { " — 🏅 new best!".to_string() } else { format!(" (best {})", thousands(self.best as u64)) }), LOSE) + } else if self.won { + ("🎉 **2048 reached!** Keep going for a higher score.".to_string(), WIN) + } else { + (format!("Biggest tile **{biggest}**"), BLURPLE) + }; + let mut card = Card::new(Some(accent)).text(&format!("### 🔢 2048 · Score {}\n{status}", thousands(self.score as u64))).gallery(&["attachment://2048.png"]); + if !self.over { + let buttons = [("left", "⬅️"), ("up", "⬆️"), ("down", "⬇️"), ("right", "➡️")].iter().map(|(d, e)| btn(t, d, "", e, ButtonStyle::Primary, false)).collect(); + card = card.row(buttons).footer(&format!("{} moves · best {}", self.moves, thousands(self.best.max(self.score) as u64))); + } else if !self.timed_out { + card = card.row(vec![again(t, "New game")]); + } + Rendered { card, file: Some(("2048.png".into(), render_board(&self.grid))) } + } + + fn click(&mut self, _: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + match action { + "left" | "right" | "up" | "down" => { + if self.over { + return Reply::Ignore; + } + if self.slide(action) { Reply::Update } else { Reply::Private("Nothing moves that way.".into()) } + } + "again" => Reply::Replace(Box::new(Self::new(self.player.clone()))), + _ => Reply::Ignore, + } + } + + fn is_over(&self) -> bool { + self.over + } + + fn abandon(&mut self) { + self.save_best(); + self.timed_out = true; + self.over = true; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rows_merge_once_per_move() { + assert_eq!(slide_row([2, 2, 2, 2]), ([4, 4, 0, 0], 8)); + assert_eq!(slide_row([2, 2, 4, 0]), ([4, 4, 0, 0], 4)); + assert_eq!(slide_row([0, 2, 0, 2]), ([4, 0, 0, 0], 4)); + assert_eq!(slide_row([2, 4, 8, 16]), ([2, 4, 8, 16], 0)); + } + + #[test] + fn moves_go_the_right_way() { + let mut g = Game2048::new(P { id: 7, name: "me".into(), bot: false }); + g.grid = [[2, 0, 0, 2], [0; 4], [0; 4], [0; 4]]; + assert!(g.slide("left")); + assert_eq!(g.grid[0][0], 4); + g.grid = [[2, 0, 0, 0], [2, 0, 0, 0], [0; 4], [0; 4]]; + assert!(g.slide("up")); + assert_eq!(g.grid[0][0], 4); + g.grid = [[0; 4], [0; 4], [0; 4], [2, 0, 0, 0]]; + assert!(!g.slide("down"), "already at the bottom"); + assert!(g.slide("right")); + assert!(g.grid[3][3] == 2); + } + + #[test] + fn a_full_board_with_no_merges_is_over() { + let mut g = Game2048::new(P { id: 7, name: "me".into(), bot: false }); + g.grid = [[2, 4, 2, 4], [4, 2, 4, 2], [2, 4, 2, 4], [4, 2, 4, 0]]; + assert!(g.can_move()); + g.grid[3][3] = 8; + assert!(!g.can_move()); + assert_eq!(&render_board(&g.grid)[1..4], b"PNG"); + } +} diff --git a/src/commands/games/words.rs b/src/commands/games/words.rs new file mode 100644 index 0000000..2de0089 --- /dev/null +++ b/src/commands/games/words.rs @@ -0,0 +1,359 @@ +//! Word games: unscramble (a timer and a race) and Wordle (a drawn board). +use super::*; +use crate::pix; +use crate::text::{self, Look}; +use crate::ui::Card; +use cosmic_text::Align; +use image::{Rgba, RgbaImage}; +use rand::seq::SliceRandom; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +fn word_list(key: &str) -> Vec { + data()[key].as_array().into_iter().flatten().filter_map(|w| w.as_str().map(str::to_string)).collect() +} + +// ---- unscramble ------------------------------------------------------------------------------------------------------- + +const TIME_LIMIT: u64 = 90; + +fn scramble(word: &str) -> String { + let mut letters: Vec = word.chars().collect(); + for _ in 0..20 { + letters.shuffle(&mut rand::rng()); + if letters.iter().collect::() != word { + break; + } + } + letters.into_iter().collect() +} + +pub struct Unscramble { + players: Vec

, + word: String, + scrambled: String, + hints: usize, + ends_unix: u64, + ends: Instant, + started: Instant, + winner: Option<(String, f64, u32)>, + over: bool, +} + +impl Unscramble { + pub fn start(player: P, opponent: Option

) -> Box { + Box::new(Self::new(std::iter::once(player).chain(opponent).collect())) + } + + fn new(players: Vec

) -> Self { + let word = pick(&word_list("unscramble")); + let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()); + Self { players, scrambled: scramble(&word), word, hints: 0, ends_unix: now + TIME_LIMIT, ends: Instant::now() + Duration::from_secs(TIME_LIMIT), started: Instant::now(), winner: None, over: false } + } + + fn points_now(&self) -> u32 { + (100u32 >> self.hints.min(31)).max(1) + } +} + +impl Game for Unscramble { + fn players(&self) -> Vec { + self.players.iter().map(|p| p.id).collect() + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(TIME_LIMIT + 60) + } + + fn deadline(&self) -> Option { + (!self.over).then_some(self.ends) + } + + fn on_deadline(&mut self) { + self.over = true; + } + + fn render(&self, t: u32) -> Rendered { + let hint: String = self.word.chars().enumerate().map(|(i, c)| if i < self.hints { c } else { '·' }).collect(); + let (status, accent) = match &self.winner { + Some((who, took, points)) => (format!("🎉 **{who}** got it in {took:.1}s — **{}** (+{points} points)", self.word), WIN), + None if self.over => (format!("⏰ Time's up! The word was **{}**.", self.word), LOSE), + None => (format!("⏳ Ends · worth **{}** points", self.ends_unix, self.points_now()), BLURPLE), + }; + let mut card = Card::new(Some(accent)).text(&format!("### 🔠 Word unscramble\n# `{}`", self.scrambled.to_uppercase().chars().map(String::from).collect::>().join(" "))); + if self.hints > 0 && !self.over { + card = card.text(&format!("💡 Hint: `{}`", hint.to_uppercase())); + } + card = card.text(&status); + if !self.over { + card = card.row(vec![ + btn(t, "guess", "Guess", "💬", ButtonStyle::Primary, false), + btn(t, "hint", "Hint", "💡", ButtonStyle::Secondary, self.hints + 2 >= self.word.len()), + btn(t, "giveup", "Give up", "", ButtonStyle::Danger, false), + ]); + if self.players.len() > 1 { + card = card.footer(&format!("Race! First right answer wins: {}", self.players.iter().map(P::name).collect::>().join(" vs "))); + } + } else { + card = card.row(vec![again(t, "Another word")]); + } + card.into() + } + + fn click(&mut self, who: u64, action: &str, _: &[String], fields: &HashMap) -> Reply { + match action { + "guess" => Reply::Modal { action: "guesssub".into(), title: "Unscramble it".into(), fields: vec![crate::interact::text_field("answer", &format!("What is {}?", self.scrambled.to_uppercase()), None, "", 30, false, Some("Your answer"))] }, + "guesssub" => { + if self.over { + return Reply::Private("Too late — the game is over.".into()); + } + let answer = fields.get("answer").map(|a| a.trim().to_lowercase()).unwrap_or_default(); + if answer == self.word { + let name = self.players.iter().find(|p| p.id == who).map(P::name).unwrap_or_else(|| "Someone".into()); + self.winner = Some((name, self.started.elapsed().as_secs_f64(), self.points_now())); + self.over = true; + Reply::Update + } else { + Reply::Private(format!("❌ **{}** isn't it — keep trying!", escape(&answer))) + } + } + "hint" => { + if !self.over { + self.hints += 1; + } + Reply::Update + } + "giveup" => { + self.over = true; + Reply::Update + } + "again" => Reply::Replace(Box::new(Self::new(self.players.clone()))), + _ => Reply::Ignore, + } + } + + fn is_over(&self) -> bool { + self.over + } + + fn abandon(&mut self) { + self.over = true; + } +} + +// ---- wordle --------------------------------------------------------------------------------------------------------------- + +const TRIES: usize = 6; +const FILENAME: &str = "wordle.png"; +const BOX: i32 = 62; +const GAP: i32 = 5; +const MARGIN: i32 = 20; +const KEYBOARD: [&str; 3] = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]; + +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum Tile { + Absent, + Present, + Correct, +} + +/// correct / present / absent for each letter (repeated letters counted properly). +pub fn score(guess: &str, word: &str) -> Vec { + let (g, w): (Vec, Vec) = (guess.chars().collect(), word.chars().collect()); + let mut result = vec![Tile::Absent; g.len()]; + let mut left: Vec> = w.iter().map(|c| Some(*c)).collect(); + for i in 0..g.len() { + if g[i] == w[i] { + result[i] = Tile::Correct; + left[i] = None; + } + } + for i in 0..g.len() { + if result[i] != Tile::Correct { + if let Some(pos) = left.iter().position(|c| *c == Some(g[i])) { + result[i] = Tile::Present; + left[pos] = None; + } + } + } + result +} + +fn draw_board(guesses: &[(String, Vec)]) -> Vec { + let width = MARGIN * 2 + 5 * BOX + 4 * GAP; + let height = MARGIN * 2 + TRIES as i32 * BOX + (TRIES as i32 - 1) * GAP; + let mut img = RgbaImage::from_pixel(width as u32, height as u32, Rgba([18, 18, 19, 255])); + let look = Look::new(None, true, [255, 255, 255]); + for row in 0..TRIES { + for col in 0..5 { + let (x, y) = (MARGIN + col as i32 * (BOX + GAP), MARGIN + row as i32 * (BOX + GAP)); + let colour = match guesses.get(row).map(|g| g.1[col]) { + Some(Tile::Correct) => Rgba([83, 141, 78, 255]), + Some(Tile::Present) => Rgba([181, 159, 59, 255]), + _ => Rgba([58, 58, 60, 255]), + }; + pix::rounded_rect(&mut img, x, y, BOX, BOX, 8, colour); + if let Some((word, _)) = guesses.get(row) { + let letter = word.chars().nth(col).unwrap_or(' ').to_uppercase().to_string(); + let w = text::width_of(&letter, 36.0, &look); + text::layout(&letter, 36.0, &look, None, Align::Left).draw(&mut img, x + ((BOX as f32 - w) / 2.0) as i32, y + (BOX - 45) / 2); + } + } + } + pix::encode_png(&img) +} + +pub struct Wordle { + player: P, + word: String, + guesses: Vec<(String, Vec)>, + won: bool, + over: bool, + timed_out: bool, + letters: HashMap, +} + +impl Wordle { + pub fn start(player: P) -> Box { + Box::new(Self::new(player)) + } + + fn new(player: P) -> Self { + Self { player, word: pick(&word_list("wordle")), guesses: vec![], won: false, over: false, timed_out: false, letters: HashMap::new() } + } + + fn add(&mut self, guess: &str) { + let result = score(guess, &self.word); + let rank = |t: Tile| t as u8; + for (letter, state) in guess.chars().zip(&result) { + if self.letters.get(&letter).is_none_or(|old| rank(*state) > rank(*old)) { + self.letters.insert(letter, *state); + } + } + self.guesses.push((guess.to_string(), result)); + if guess == self.word { + self.won = true; + self.over = true; + } else if self.guesses.len() >= TRIES { + self.over = true; + } + } + + fn key(&self, letter: char) -> String { + let shown = letter.to_uppercase().to_string(); + match self.letters.get(&letter) { + Some(Tile::Correct) => format!("**{shown}**🟩"), + Some(Tile::Present) => format!("**{shown}**🟨"), + Some(Tile::Absent) => format!("~~{shown}~~"), + None => shown, + } + } +} + +impl Game for Wordle { + fn players(&self) -> Vec { + vec![self.player.id] + } + + fn render(&self, t: u32) -> Rendered { + let upper = self.word.to_uppercase(); + let (status, accent) = if self.won { + (format!("🎉 **{} got it in {}/{TRIES}!** The word was **{upper}**.", self.player.name(), self.guesses.len()), WIN) + } else if self.over && !self.timed_out { + (format!("😞 **Out of tries!** The word was **{upper}**."), LOSE) + } else if self.timed_out { + (format!("The word was **{upper}**."), LOSE) + } else { + let left = TRIES - self.guesses.len(); + (format!("🔍 {left} {} left — press **Guess** and type a word.", if left == 1 { "try" } else { "tries" }), BLURPLE) + }; + let mut card = Card::new(Some(accent)).text(&format!("### 🟩 Wordle · {}\n{status}", self.player.name())).gallery(&[&format!("attachment://{FILENAME}")]); + if !self.guesses.is_empty() { + let square = |t: &Tile| match t { Tile::Correct => "🟩", Tile::Present => "🟨", Tile::Absent => "⬛" }; + let grid = self.guesses.iter().map(|(_, r)| r.iter().map(square).collect::()).collect::>().join("\n"); + let keys = KEYBOARD.iter().map(|row| row.chars().map(|k| self.key(k)).collect::>().join(" ")).collect::>().join("\n"); + card = card.text(&format!("{grid}\n\n{keys}")); + } + if !self.over { + card = card.row(vec![btn(t, "guess", "Guess", "🎯", ButtonStyle::Primary, false)]).footer("🟩 right spot · 🟨 wrong spot · letters ~~crossed out~~ aren't in the word"); + } else if !self.timed_out { + card = card.row(vec![again(t, "New game")]); + } + Rendered { card, file: Some((FILENAME.into(), draw_board(&self.guesses))) } + } + + fn click(&mut self, _: u64, action: &str, _: &[String], fields: &HashMap) -> Reply { + match action { + "guess" if !self.over => Reply::Modal { action: "guesssub".into(), title: "Your guess".into(), fields: vec![crate::interact::text_field("guess", "5-letter word", None, "", 5, false, Some("e.g. crane"))] }, + "guesssub" => { + let guess = fields.get("guess").map(|g| g.trim().to_lowercase()).unwrap_or_default(); + if guess.chars().count() != 5 || !guess.chars().all(|c| c.is_ascii_alphabetic()) { + return Reply::Private("❌ Letters only — exactly 5 of them.".into()); + } + if self.over { + return Reply::Private("This game is already over.".into()); + } + self.add(&guess); + Reply::Update + } + "again" => Reply::Replace(Box::new(Self::new(self.player.clone()))), + _ => Reply::Ignore, + } + } + + fn is_over(&self) -> bool { + self.over + } + + fn abandon(&mut self) { + self.timed_out = true; + self.over = true; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p() -> P { + P { id: 1, name: "me".into(), bot: false } + } + + #[test] + fn scoring_handles_repeated_letters() { + use Tile::*; + assert_eq!(score("crane", "crane"), vec![Correct; 5]); + assert_eq!(score("speed", "abide"), vec![Absent, Absent, Present, Absent, Present]); + assert_eq!(score("llama", "hello"), vec![Present, Present, Absent, Absent, Absent]); + assert_eq!(score("eerie", "geese"), vec![Present, Correct, Absent, Absent, Correct]); + } + + #[test] + fn wordle_play_through_and_picture() { + let mut g = Wordle::new(p()); + g.word = "crane".into(); + for w in ["adieu", "stone"] { + g.click(1, "guesssub", &[], &HashMap::from([("guess".to_string(), w.to_string())])); + } + assert!(!g.over && g.guesses.len() == 2); + assert!(matches!(g.click(1, "guesssub", &[], &HashMap::from([("guess".to_string(), "abc".to_string())])), Reply::Private(_))); + g.click(1, "guesssub", &[], &HashMap::from([("guess".to_string(), "crane".to_string())])); + assert!(g.won && g.over); + let r = g.render(1); + let png = r.file.unwrap().1; + assert_eq!(&png[1..4], b"PNG"); + } + + #[test] + fn unscramble_hints_halve_points_and_wrong_answers_dont_end_it() { + let mut g = Unscramble::new(vec![p()]); + assert_eq!(g.points_now(), 100); + g.click(1, "hint", &[], &Default::default()); + assert_eq!(g.points_now(), 50); + assert_ne!(g.scrambled, g.word); + assert!(matches!(g.click(1, "guesssub", &[], &HashMap::from([("answer".to_string(), "zzz".to_string())])), Reply::Private(_))); + assert!(!g.over); + let w = g.word.clone(); + g.click(1, "guesssub", &[], &HashMap::from([("answer".to_string(), w)])); + assert!(g.over && g.winner.is_some()); + } +} diff --git a/src/commands/general.rs b/src/commands/general.rs new file mode 100644 index 0000000..800f3a0 --- /dev/null +++ b/src/commands/general.rs @@ -0,0 +1,48 @@ +//! ping and prefix. +use crate::cmd::{Command, Ctx, Opt, OptKind}; +use crate::ui::{Card, GREEN, RED}; +use anyhow::Result; +use futures::FutureExt; +use std::sync::Arc; +use std::time::Instant; +use twilight_model::guild::Permissions; + +pub fn commands() -> Vec { + vec![ + Command::new("ping", "fun", "Check that the bot is alive", |c| ping(c).boxed()), + Command::new("prefix", "server", "Show or change this server's prefix", |c| prefix(c).boxed()) + .opt(Opt::opt("new", "The new prefix", OptKind::String)) + .usage("[new prefix]") + .guild_only(), + ] +} + +async fn ping(ctx: Arc) -> Result<()> { + let t = Instant::now(); + ctx.state.http.current_user().await?; + let api = t.elapsed().as_millis(); + let gateway = ctx.state.gateway_ms.load(std::sync::atomic::Ordering::Relaxed); + let (colour, quality) = if api < 300 { (GREEN, "🟢 great") } else if api < 800 { (0xF1C40F, "🟡 okay") } else { (RED, "🔴 slow") }; + let up = ctx.state.started.elapsed().as_secs(); + let gw = if gateway == 0 { "…".to_string() } else { format!("{gateway} ms") }; + let card = Card::new(Some(colour)) + .header(&["### 🏓 Pong!"], None) + .text(&format!("**Gateway** {gw} · **API** {api} ms — {quality}")) + .footer(&format!("Up for {}h {}m", up / 3600, up % 3600 / 60)) + .build(); + ctx.reply(card).await +} + +async fn prefix(ctx: Arc) -> Result<()> { + let guild = ctx.guild()?; + let Some(new) = ctx.args.str("new") else { + let current = ctx.state.prefix(Some(guild)); + return ctx.say(&format!("This server's prefix is `{current}`.")).await; + }; + ctx.require(Permissions::MANAGE_GUILD, "manage guild")?; + if new.chars().count() > 5 || new.contains(char::is_whitespace) { + bail_user!("A prefix is 1–5 characters with no spaces."); + } + ctx.state.set_prefix(guild, new); + ctx.reply(Card::new(Some(GREEN)).text(&format!("✅ Prefix is now `{new}`.")).build()).await +} diff --git a/src/commands/help.rs b/src/commands/help.rs new file mode 100644 index 0000000..855921d --- /dev/null +++ b/src/commands/help.rs @@ -0,0 +1,497 @@ +//! The help menu — built from the registered commands, so it can't go out of date. +//! +//! Every control carries its page in the custom_id (`help::`), so old help messages +//! keep working after a restart. Clicking someone else's menu opens your own copy, privately. +//! Pages: `home` · `c..` · `x.`. +use crate::cmd::{Command, Ctx}; +use crate::state::State; +use crate::ui::{self, emoji_button, select_menu, select_option, truncate, Card}; +use anyhow::Result; +use futures::FutureExt; +use std::sync::Arc; +use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_model::channel::message::{AllowedMentions, Component, MessageFlags}; +use twilight_model::guild::Permissions; +use twilight_model::http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType}; +use twilight_model::id::marker::UserMarker; +use twilight_model::id::Id; + +const PAGE_BUDGET: usize = 3000; // characters of command list per page (a message holds 4000 in total) + +pub struct Category { + pub key: &'static str, + pub emoji: &'static str, + pub name: &'static str, + pub blurb: &'static str, + pub accent: u32, + pub note: &'static str, +} + +const fn cat(key: &'static str, emoji: &'static str, name: &'static str, blurb: &'static str, accent: u32, note: &'static str) -> Category { + Category { key, emoji, name, blurb, accent, note } +} + +pub const CATEGORIES: &[Category] = &[ + cat("music", "🎵", "Music", "Play music in voice with a live player", 0x9B59B6, ""), + cat("lastfm", "📊", "Last.fm", "Now playing, top charts, Who Knows, Pixel Jumble and lyrics", 0xD51007, "Link your account first: `{p}fmset ` or `/fm mode:link`."), + cat("media", "🎨", "Media", "Downloads, image effects, quotes and emojis", 0xE67E22, ""), + cat("moderation", "🛡️", "Moderation", "Kick, ban, timeout, purge, nicknames and roles", 0xED4245, "Moderation commands also work as a reply to someone's message."), + cat("server", "⚙️", "Server setup", "Logging, welcome, role menus, channel tools and the prefix", 0xF1C40F, ""), + cat("utility", "🔧", "Utility", "Info cards, web search, weather, calculator, snipe and AFK", 0x607D8B, ""), + cat("ai", "🤖", "AI chat", "Talk to Dezio and set its personality", 0x1ABC9C, "Mention @Dezio (or reply to one of its messages) to chat."), + cat("fun", "🎉", "Fun & social", "Phone calls, confessions, smash or pass", 0xE91E63, ""), + cat("actions", "🤗", "Actions", "Anime GIF actions: hug, pat, slap, dance…", 0xFF73FA, ""), + cat("animals", "🐾", "Animals", "Random animal pictures and facts", 0x2ECC71, ""), + cat("games", "🎮", "Games", "Chess, Connect 4, Wordle, Akinator, Game Boy and more", 0x5865F2, "Two-player games without an opponent are played against Dezio."), + cat("casino", "🎰", "Casino", "Coins, coin flip, blackjack, slots and roulette", 0xC27C0E, ""), + cat("nsfw", "🔞", "NSFW", "Age-restricted commands", 0x71368A, "These only work in age-restricted channels."), + cat("apps", "🖱️", "Apps", "Right-click a message or user → Apps", 0x5865F2, ""), + cat("other", "📦", "Other", "Everything else", 0x4F545C, ""), + cat("owner", "👑", "Owner", "Bot owner tools (only you can see this page)", 0x4F545C, ""), +]; + +fn category(key: &str) -> Option<&'static Category> { + CATEGORIES.iter().find(|c| c.key == key) +} + +fn find_category(query: &str) -> Option<&'static Category> { + let q = query.trim().to_lowercase().replace('.', ""); + CATEGORIES.iter().find(|c| { + let name = c.name.to_lowercase().replace('.', ""); + q == c.key || q == name || Some(q.as_str()) == name.split_whitespace().next() + }) +} + +fn permission_names(p: Permissions) -> Vec { + let mut out = Vec::new(); + for (flag, name) in [ + (Permissions::ADMINISTRATOR, "Administrator"), (Permissions::MANAGE_GUILD, "Manage Server"), + (Permissions::KICK_MEMBERS, "Kick Members"), (Permissions::BAN_MEMBERS, "Ban Members"), + (Permissions::MODERATE_MEMBERS, "Timeout Members"), (Permissions::MANAGE_NICKNAMES, "Manage Nicknames"), + (Permissions::MANAGE_ROLES, "Manage Roles"), (Permissions::MANAGE_CHANNELS, "Manage Channels"), + (Permissions::MANAGE_MESSAGES, "Manage Messages"), (Permissions::MANAGE_GUILD_EXPRESSIONS, "Manage Expressions"), + ] { + if p.contains(flag) { + out.push(name.to_string()); + } + } + out +} + +/// What the reader is: changes what's shown. +pub struct Viewer { + pub uid: Id, + pub prefix: String, + pub owner: bool, + /// In an age-restricted channel (or a DM): the NSFW commands are listed. + pub nsfw_here: bool, + pub avatar: Option, +} + +struct Index<'a> { + commands: &'a [Command], + viewer: &'a Viewer, +} + +impl<'a> Index<'a> { + /// NSFW commands only show up in age-restricted channels. + fn shown(&self, c: &Command) -> bool { + c.category != "nsfw" || self.viewer.nsfw_here + } + + fn visible(&self, category: &str) -> Vec<&'a Command> { + let wanted = if category == "owner" { true } else { false }; + self.commands.iter() + .filter(|c| self.shown(c)) + .filter(|c| (c.category == category && !c.hidden) || (wanted && c.hidden && self.viewer.owner)) + .collect() + } + + fn categories(&self) -> Vec<&'static Category> { + CATEGORIES.iter().filter(|c| !self.visible(c.key).is_empty() && (self.viewer.owner || c.key != "owner")).collect() + } + + fn find(&self, query: &str) -> Option<&'a Command> { + let q = query.trim().trim_start_matches('/').to_lowercase(); + let q = q.split_whitespace().next().unwrap_or("").to_string(); + self.commands.iter().find(|c| self.shown(c) && (self.viewer.owner || !c.hidden) && (c.name == q || c.aliases.contains(&q.as_str()))) + } + + fn suggestions(&self, query: &str) -> Vec { + let q = query.to_lowercase(); + let mut scored: Vec<(usize, String)> = self.commands.iter() + .filter(|c| self.shown(c) && (self.viewer.owner || !c.hidden)) + .flat_map(|c| std::iter::once(c.name).chain(c.aliases.iter().copied())) + .filter_map(|n| { + let d = edit_distance(&q, n); + (d <= 2 || n.contains(&q) || q.contains(n)).then(|| (d, n.to_string())) + }) + .collect(); + scored.sort(); + scored.into_iter().map(|(_, n)| n).take(5).collect() + } +} + +fn edit_distance(a: &str, b: &str) -> usize { + let (a, b): (Vec, Vec) = (a.chars().collect(), b.chars().collect()); + let mut prev: Vec = (0..=b.len()).collect(); + for i in 1..=a.len() { + let mut cur = vec![i]; + for j in 1..=b.len() { + let cost = (a[i - 1] != b[j - 1]) as usize; + cur.push((prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost)); + } + prev = cur; + } + prev[b.len()] +} + +fn first_line(text: &str) -> &str { + text.trim().lines().next().unwrap_or("") +} + +struct Renderer<'a> { + idx: Index<'a>, +} + +impl<'a> Renderer<'a> { + fn v(&self) -> &Viewer { + self.idx.viewer + } + + fn id(&self, tag: &str, page: &str) -> String { + format!("help:{}:{tag}:{page}", self.v().uid) + } + + fn flags(&self, c: &Command) -> String { + let mut marks = String::new(); + if c.perm.is_some() { + marks.push('🔒'); + } + if c.hidden { + marks.push('👑'); + } + if marks.is_empty() { marks } else { format!(" {marks}") } + } + + fn forms(&self, c: &Command) -> Vec { + let p = &self.v().prefix; + let mut out = Vec::new(); + if c.slash { + out.push(format!("`/{}`", c.name)); + } + let usage = if c.usage.is_empty() { String::new() } else { format!(" {}", c.usage) }; + out.push(format!("`{p}{}{usage}`", c.name)); + out.extend(c.aliases.iter().map(|a| format!("`{p}{a}`"))); + out + } + + fn entry_block(&self, c: &Command) -> String { + format!("**{}**{} — {}\n-# {}", c.name, self.flags(c), truncate(c.description, 140), self.forms(c).join(" · ")) + } + + fn pages(&self, key: &str) -> Vec> { + let mut pages: Vec> = vec![vec![]]; + let mut size = 0; + for c in self.idx.visible(key) { + let block = self.entry_block(c); + if !pages.last().unwrap().is_empty() && size + block.chars().count() > PAGE_BUDGET { + pages.push(vec![]); + size = 0; + } + size += block.chars().count() + 2; + pages.last_mut().unwrap().push(block); + } + pages + } + + fn page_of(&self, c: &Command) -> usize { + self.pages(c.category).iter().position(|p| p.iter().any(|b| b.starts_with(&format!("**{}**", c.name)))).unwrap_or(0) + } + + fn select(&self, current: &str) -> twilight_model::channel::message::component::SelectMenu { + let mut options = vec![select_option("Overview", "home", "🏠", "All categories", current == "home")]; + for c in self.idx.categories().into_iter().take(24) { + options.push(select_option(c.name, c.key, c.emoji, c.blurb, current == c.key)); + } + select_menu(&format!("help:{}:cat:x", self.v().uid), "📂 Pick a category…", options) + } + + fn legend(&self) -> String { + format!("`{}help ` for details · <> required · [] optional", self.v().prefix) + } + + fn home(&self) -> Card { + let p = &self.v().prefix; + let head = format!( + "Pick a category below, or look one command up with `{p}help ping` or `/help command:ping`.\n-# Prefix here: `{p}` · Slash commands: type `/`" + ); + let mut card = Card::new(Some(0x5865F2)).header(&["### 📚 Dezio help", &head], self.v().avatar.as_deref()).separator(true, false); + let lines: Vec = self.idx.categories().iter() + .map(|c| format!("{} **{}** · {} — {}", c.emoji, c.name, self.idx.visible(c.key).len(), c.blurb)) + .collect(); + let slash = self.idx.commands.iter().filter(|c| c.slash).count(); + let prefix = self.idx.commands.iter().filter(|c| !c.hidden).count(); + card = card.text(&lines.join("\n")).footer(&format!("{slash} slash commands · {prefix} prefix commands · 🔒 needs permissions")); + card.select(self.select("home")) + } + + fn category(&self, key: &str, number: usize) -> Card { + let cat = category(key).expect("known category"); + let pages = self.pages(key); + let number = number.min(pages.len() - 1); + let mut intro = format!("{}.", cat.blurb); + if !cat.note.is_empty() { + intro.push_str(&format!("\n-# {}", cat.note.replace("{p}", &self.v().prefix))); + } + let body = pages[number].join("\n\n"); + let footer = if pages.len() > 1 { format!("Page {}/{} · {}", number + 1, pages.len(), self.legend()) } else { self.legend() }; + let mut buttons = vec![emoji_button(&self.id("home", "home"), None, "🏠", false)]; + if pages.len() > 1 { + buttons = vec![ + emoji_button(&self.id("prev", &format!("c.{key}.{}", number.saturating_sub(1))), None, "◀️", number == 0), + ui::button(&format!("help:{}:count:x", self.v().uid), &format!("{}/{}", number + 1, pages.len()), twilight_model::channel::message::component::ButtonStyle::Secondary), + emoji_button(&self.id("next", &format!("c.{key}.{}", number + 1)), None, "▶️", number + 1 >= pages.len()), + buttons.remove(0), + ]; + buttons[1].disabled = true; + } + Card::new(Some(cat.accent)) + .text(&format!("### {} {}\n{intro}", cat.emoji, cat.name)) + .separator(true, false) + .text(if body.is_empty() { "*Nothing here.*" } else { &body }) + .separator(true, false) + .footer(&footer) + .select(self.select(key)) + .row(buttons) + } + + fn detail(&self, c: &Command) -> Card { + let cat = category(c.category).unwrap_or_else(|| category("other").unwrap()); + let p = &self.v().prefix; + let mut lines = Vec::new(); + if c.slash { + let opts: Vec = c.options.iter().filter(|o| o.in_slash) + .map(|o| if o.required { o.name.to_string() } else { format!("[{}]", o.name) }).collect(); + lines.push(format!("**Slash:** `/{}{}`", c.name, if opts.is_empty() { String::new() } else { format!(" {}", opts.join(" ")) })); + for o in c.options.iter().filter(|o| o.in_slash).take(10) { + let mut text = o.description.to_string(); + if !o.choices.is_empty() { + text.push_str(&format!(" ({})", o.choices.iter().take(8).copied().collect::>().join(", "))); + } + lines.push(format!("-# • **{}**{} — {}", o.name, if o.required { "" } else { " (optional)" }, truncate(&text, 140))); + } + } + let forms = self.forms(c); + let prefix_forms: Vec<&String> = forms.iter().filter(|f| f.starts_with(&format!("`{p}"))).collect(); + if let Some(first) = prefix_forms.first() { + let mut line = format!("**Prefix:** {first}"); + if prefix_forms.len() > 1 { + line.push_str(&format!(" · also {}", prefix_forms[1..].iter().map(|s| s.as_str()).collect::>().join(", "))); + } + lines.push(line); + } + let mut needs = Vec::new(); + if c.hidden { + needs.push("👑 Bot owner only".to_string()); + } + if let Some(perm) = c.perm { + needs.push(format!("🔒 You need {}", permission_names(perm).join(", "))); + } + if c.guild_only { + needs.push("🏠 Servers only".to_string()); + } + if !needs.is_empty() { + lines.push(format!("**Needs:** {}", needs.join(" · "))); + } + let page = format!("c.{}.{}", c.category, self.page_of(c)); + Card::new(Some(cat.accent)) + .text(&format!("### {} {}\n{}", cat.emoji, c.name, truncate(c.description, 1800))) + .separator(true, false) + .text(&lines.join("\n")) + .footer(&format!("In {} {} · <> required · [] optional", cat.emoji, cat.name)) + .select(self.select(c.category)) + .row(vec![ + emoji_button(&self.id("back", &page), Some(cat.name), "◀️", false), + emoji_button(&self.id("home", "home"), None, "🏠", false), + ]) + } + + fn notice(&self, text: &str) -> Card { + Card::new(Some(ui::RED)).text(text).select(self.select("")).row(vec![emoji_button(&self.id("home", "home"), None, "🏠", false)]) + } + + fn not_found(&self, query: &str) -> Card { + let close = self.idx.suggestions(query); + let mut text = format!("❌ No command or category called `{}`.", ui::escape(&truncate(query, 50))); + if !close.is_empty() { + text.push_str(&format!(" Did you mean {}?", close.iter().map(|c| format!("`{c}`")).collect::>().join(", "))); + } + self.notice(&text) + } + + fn page(&self, page: &str) -> Card { + let (kind, rest) = page.split_once('.').unwrap_or((page, "")); + match kind { + "c" => { + let (key, number) = rest.rsplit_once('.').unwrap_or((rest, "0")); + if category(key).is_some() && (key != "owner" || self.v().owner) { + return self.category(key, number.parse().unwrap_or(0)); + } + self.home() + } + "x" => match self.idx.find(rest) { + Some(c) => self.detail(c), + None => self.not_found(rest), + }, + _ => self.home(), + } + } +} + +/// The page for `help `: a category name, else a command. +fn page_for(commands: &[Command], viewer: &Viewer, query: Option<&str>) -> String { + let q = query.unwrap_or("").trim().to_lowercase(); + if q.is_empty() { + return "home".into(); + } + let (kind, rest) = q.split_once(':').unwrap_or(("", &q)); + if kind == "cmd" { + return format!("x.{rest}"); + } + let wanted = if kind == "cat" { rest } else { &q }; + if let Some(c) = find_category(wanted).filter(|_| !q.starts_with('/')) { + return format!("c.{}.0", c.key); + } + let idx = Index { commands, viewer }; + format!("x.{}", idx.find(&q).map_or(q.trim_start_matches('/').to_string(), |c| c.name.to_string())) +} + +fn render(state: &State, viewer: &Viewer, page: &str) -> Component { + Renderer { idx: Index { commands: state.registry.all(), viewer } }.page(page).build() +} + +fn viewer_for(state: &State, uid: Id, guild: Option>, channel: Id) -> Viewer { + let nsfw_here = guild.is_none() || state.cache.channel(channel).is_some_and(|c| c.nsfw == Some(true) || c.parent_id.and_then(|p| state.cache.channel(p)).is_some_and(|p| p.nsfw == Some(true))); + let avatar = state.cache.current_user().map(|u| ui::avatar_url(u.id, u.avatar.as_ref())); + Viewer { uid, prefix: state.prefix(guild), owner: state.is_owner(uid), nsfw_here, avatar } +} + +pub fn commands() -> Vec { + vec![Command::new("help", "utility", "Every command, by category — or details on one command", |c| help(c).boxed()) + .aliases(&["h"]) + .usage("[command | category]") + .opt(crate::cmd::Opt::opt("command", "A command or category to look up (leave empty for the overview)", crate::cmd::OptKind::String))] +} + +async fn help(ctx: Arc) -> Result<()> { + let viewer = viewer_for(&ctx.state, ctx.user_id, ctx.guild_id, ctx.channel_id); + let page = page_for(ctx.state.registry.all(), &viewer, ctx.args.str("command")); + ctx.reply(render(&ctx.state, &viewer, &page)).await +} + +/// Buttons and the category menu: `help:::`. +pub async fn on_component(state: &Arc, i: &Interaction) { + let Some(InteractionData::MessageComponent(data)) = i.data.as_ref() else { return }; + let mut parts = data.custom_id.splitn(4, ':'); + let (_, Some(uid), Some(tag), Some(arg)) = (parts.next(), parts.next(), parts.next(), parts.next()) else { return }; + let Some(owner_uid) = uid.parse::().ok().and_then(Id::new_checked) else { return }; + let page = if tag == "cat" { + match data.values.first().map(String::as_str) { + Some("home") | None => "home".to_string(), + Some(v) => format!("c.{v}.0"), + } + } else if tag == "count" { + return; + } else { + arg.to_string() + }; + let Some(user) = i.author() else { return }; + let viewer = viewer_for(state, user.id, i.guild_id, i.channel.as_ref().map_or(Id::new(1), |c| c.id)); + let card = render(state, &viewer, &page); + let mut flags = MessageFlags::IS_COMPONENTS_V2; + // someone else's menu: give them their own copy + let kind = if user.id == owner_uid { + InteractionResponseType::UpdateMessage + } else { + flags |= MessageFlags::EPHEMERAL; + InteractionResponseType::ChannelMessageWithSource + }; + let response = InteractionResponse { + kind, + data: Some(InteractionResponseData { + components: Some(vec![card]), + flags: Some(flags), + allowed_mentions: Some(AllowedMentions::default()), + ..Default::default() + }), + }; + if let Err(e) = state.http.interaction(state.app_id()).create_response(i.id, &i.token, &response).await { + tracing::warn!("help page failed: {e}"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn category_lookup() { + assert_eq!(find_category("Server").map(|c| c.key), Some("server")); + assert_eq!(find_category("last.fm").map(|c| c.key), Some("lastfm")); + assert_eq!(find_category("mod").map(|c| c.key), None); + assert_eq!(find_category("moderation").map(|c| c.key), Some("moderation")); + } + + #[test] + fn typos() { + assert_eq!(edit_distance("bna", "ban"), 2); + assert_eq!(edit_distance("kick", "kick"), 0); + } + + /// Every page must fit Discord's limits for a Components V2 message. + #[test] + fn every_page_fits_discord_limits() { + fn walk(v: &serde_json::Value, count: &mut usize, text: &mut usize, ids: &mut Vec) { + if let Some(o) = v.as_object() { + if o.contains_key("type") { + *count += 1; + } + if let Some(t) = o.get("content").and_then(|c| c.as_str()) { + *text += t.chars().count(); + } + if let Some(id) = o.get("custom_id").and_then(|c| c.as_str()) { + assert!(id.len() <= 100, "custom_id too long: {id}"); + ids.push(id.to_string()); + } + if let Some(opts) = o.get("options").and_then(|c| c.as_array()) { + assert!(opts.len() <= 25); + } + o.values().for_each(|x| walk(x, count, text, ids)); + } else if let Some(a) = v.as_array() { + a.iter().for_each(|x| walk(x, count, text, ids)); + } + } + let commands = crate::commands::all(); + let viewer = Viewer { uid: Id::new(1), prefix: "D!".into(), owner: true, nsfw_here: true, avatar: Some("https://x/y.png".into()) }; + let r = Renderer { idx: Index { commands: &commands, viewer: &viewer } }; + let mut pages = vec!["home".to_string(), "x.nothing".to_string()]; + for c in CATEGORIES { + for n in 0..r.pages(c.key).len() { + pages.push(format!("c.{}.{n}", c.key)); + } + } + pages.extend(commands.iter().map(|c| format!("x.{}", c.name))); + for page in pages { + let json = serde_json::to_value(r.page(&page).build()).unwrap(); + let (mut count, mut text, mut ids) = (0, 0, vec![]); + walk(&json, &mut count, &mut text, &mut ids); + assert!(count <= 40, "{page}: {count} components"); + assert!(text <= 4000, "{page}: {text} chars"); + let mut sorted = ids.clone(); + sorted.sort(); + sorted.dedup(); + assert_eq!(sorted.len(), ids.len(), "{page}: duplicate custom_ids {ids:?}"); + } + } +} diff --git a/src/commands/info.rs b/src/commands/info.rs new file mode 100644 index 0000000..d45d2fc --- /dev/null +++ b/src/commands/info.rs @@ -0,0 +1,474 @@ +//! Info cards: users, servers, channels, roles, avatars and banners. +//! +//! `userinfo`/`serverinfo`/`channelinfo`/`roleinfo` work as `/name` and `D!name`; `D!avatar`/`D!banner` +//! plus the "Show Avatar"/"Show Banner" right-click apps. Prefix versions accept a reply to look up the +//! person you replied to. +//! +//! Banners and accent colours need an extra API call per user; results are cached for 10 minutes so +//! repeated lookups are instant and don't burn rate limits. +use crate::bail_user; +use crate::cmd::{Command, Ctx, Opt, OptKind}; +use crate::colors; +use crate::converters::thousands; +use crate::state::State; +use crate::ui::{self, escape, truncate, Card, BLURPLE}; +use anyhow::Result; +use futures::FutureExt; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; +use twilight_model::channel::message::component::{Button, ButtonStyle}; +use twilight_model::channel::message::Component; +use twilight_model::channel::ChannelType; +use twilight_model::gateway::presence::{ActivityType, Status}; +use twilight_model::guild::Permissions; +use twilight_model::id::marker::{GuildMarker, RoleMarker, UserMarker}; +use twilight_model::id::Id; +use twilight_model::user::{User, UserFlags}; + +const KEY_PERMS: &[(Permissions, &str)] = &[ + (Permissions::ADMINISTRATOR, "Administrator"), (Permissions::MANAGE_GUILD, "Manage Server"), + (Permissions::MANAGE_ROLES, "Manage Roles"), (Permissions::MANAGE_CHANNELS, "Manage Channels"), + (Permissions::MANAGE_MESSAGES, "Manage Messages"), (Permissions::BAN_MEMBERS, "Ban Members"), + (Permissions::KICK_MEMBERS, "Kick Members"), (Permissions::MODERATE_MEMBERS, "Moderate Members"), + (Permissions::MENTION_EVERYONE, "Mention Everyone"), (Permissions::MANAGE_WEBHOOKS, "Manage Webhooks"), + (Permissions::MANAGE_GUILD_EXPRESSIONS, "Manage Expressions"), +]; + +const BADGES: &[(UserFlags, &str)] = &[ + (UserFlags::STAFF, "Discord Staff"), (UserFlags::PARTNER, "Partner"), (UserFlags::HYPESQUAD, "HypeSquad Events"), + (UserFlags::BUG_HUNTER_LEVEL_1, "Bug Hunter"), (UserFlags::BUG_HUNTER_LEVEL_2, "Bug Hunter Gold"), + (UserFlags::HYPESQUAD_ONLINE_HOUSE_1, "Bravery"), (UserFlags::HYPESQUAD_ONLINE_HOUSE_2, "Brilliance"), + (UserFlags::HYPESQUAD_ONLINE_HOUSE_3, "Balance"), (UserFlags::PREMIUM_EARLY_SUPPORTER, "Early Supporter"), + (UserFlags::VERIFIED_DEVELOPER, "Early Bot Dev"), (UserFlags::MODERATOR_PROGRAMS_ALUMNI, "Certified Mod"), + (UserFlags::ACTIVE_DEVELOPER, "Active Developer"), (UserFlags::VERIFIED_BOT, "Verified Bot"), +]; + +pub fn created_at(id: u64) -> i64 { + (((id >> 22) + 1_420_070_400_000) / 1000) as i64 +} + +fn ts(unix: i64, style: char) -> String { + format!("") +} + +/// Title-cased permission names ("manage guild" -> "Manage Server"). +pub fn perm_list(p: Permissions) -> Vec { + p.iter_names() + .map(|(n, _)| { + n.to_lowercase().replace("guild", "server").split('_').map(|w| { + let mut c = w.chars(); + c.next().map(|f| f.to_uppercase().collect::() + c.as_str()).unwrap_or_default() + }).collect::>().join(" ") + }) + .collect() +} + +fn link_button(label: &str, url: &str) -> Button { + Button { id: None, custom_id: None, disabled: false, emoji: None, label: Some(label.into()), style: ButtonStyle::Link, url: Some(url.into()), sku_id: None } +} + +// ---- the full profile (banner + accent colour) --------------------------------------------- + +#[derive(Clone)] +pub struct Full { + pub banner: Option, + pub accent: Option, +} + +fn users_cache() -> &'static Mutex> { + static C: OnceLock>> = OnceLock::new(); + C.get_or_init(Default::default) +} + +/// `GET /users/{id}` (has banner + accent colour), cached for 10 minutes. +pub async fn full_user(state: &State, id: Id) -> Option { + if let Some((at, f)) = users_cache().lock().unwrap().get(&id.get()) { + if at.elapsed() < Duration::from_secs(600) { + return Some(f.clone()); + } + } + let u = state.http.user(id).await.ok()?.model().await.ok()?; + let full = Full { + banner: u.banner.map(|b| format!("https://cdn.discordapp.com/banners/{id}/{b}.{}?size=1024", if b.is_animated() { "gif" } else { "png" })), + accent: u.accent_color, + }; + let mut c = users_cache().lock().unwrap(); + if c.len() > 500 { + c.clear(); + } + c.insert(id.get(), (Instant::now(), full.clone())); + Some(full) +} + +/// A user from the cache, or from Discord. +pub async fn user_of(state: &State, id: Id) -> Result { + if let Some(u) = state.cache.user(id) { + return Ok(u.clone()); + } + Ok(state.http.user(id).await.map_err(|_| crate::error::UserError::new("No Discord user has that ID."))?.model().await?) +} + +/// A person's server nickname, global name or username (looked up over HTTP when we haven't seen them). +pub async fn display_name_of(state: &State, guild: Option>, id: Id) -> String { + if let Some(n) = guild.and_then(|g| state.cache.member(g, id).and_then(|m| m.nick().map(str::to_string))) { + return n; + } + if let Some(u) = state.cache.user(id) { + return u.global_name.clone().unwrap_or_else(|| u.name.clone()); + } + match user_of(state, id).await { + Ok(u) => u.global_name.clone().unwrap_or(u.name), + Err(_) => "someone".into(), + } +} + +pub fn display_name(state: &State, guild: Option>, u: &User) -> String { + guild + .and_then(|g| state.cache.member(g, u.id).and_then(|m| m.nick().map(str::to_string))) + .or_else(|| u.global_name.clone()) + .unwrap_or_else(|| u.name.clone()) +} + +/// The picture shown for someone: server avatar, else their own, else the default one. +fn display_avatar(state: &State, guild: Option>, u: &User, size: u32) -> String { + if let Some(a) = guild.and_then(|g| state.cache.member(g, u.id)).and_then(|m| m.avatar()) { + let ext = if a.is_animated() { "gif" } else { "png" }; + return format!("https://cdn.discordapp.com/guilds/{}/users/{}/avatars/{a}.{ext}?size={size}", guild.unwrap(), u.id); + } + global_avatar(u, size) +} + +fn global_avatar(u: &User, size: u32) -> String { + match &u.avatar { + Some(a) => format!("https://cdn.discordapp.com/avatars/{}/{a}.{}?size={size}", u.id, if a.is_animated() { "gif" } else { "png" }), + None => ui::avatar_url(u.id, None), + } +} + +/// Who a command is about: the option, else the replied-to author, else you. +async fn target(ctx: &Ctx, option: &str) -> Result { + if let Some(id) = ctx.args.user(option) { + return user_of(&ctx.state, id).await; + } + if let Some(t) = ctx.args.str(option) { + if let Some(g) = ctx.guild_id { + if let Some(id) = crate::converters::find_member(&ctx.state.cache, g, t) { + return user_of(&ctx.state, id).await; + } + } + bail_user!("I couldn't find `{}`.", escape(t)); + } + if let Some(u) = &ctx.target_user { + return Ok(u.clone()); + } + user_of(&ctx.state, ctx.reply_to.unwrap_or(ctx.user_id)).await +} + +// ---- user ---------------------------------------------------------------------------------- + +async fn user_card(state: &State, user: &User, guild: Option>) -> Component { + let full = full_user(state, user.id).await; + let member = guild.and_then(|g| state.cache.member(g, user.id).map(|m| (g, m))); + let role_color = member.as_ref().and_then(|(g, m)| { + let top = state.cache.member_highest_role(*g, user.id)?; + let _ = m; + state.cache.role(top).map(|r| r.color).filter(|c| *c != 0) + }); + let avatar = display_avatar(state, guild, user, 256); + let accent = full.as_ref().and_then(|f| f.accent).or(role_color).unwrap_or(BLURPLE); + let accent = colors::accent(state, Some(&avatar), accent).await; + let created = created_at(user.id.get()); + let badges: Vec<&str> = user.public_flags.map(|f| BADGES.iter().filter(|(b, _)| f.contains(*b)).map(|(_, n)| *n).collect()).unwrap_or_default(); + let mut lines = vec![ + format!("**Username:** `{}`{}", user.name, user.global_name.as_ref().map_or(String::new(), |g| format!(" · **Display name:** {}", escape(g)))), + format!("**ID:** `{}`{}", user.id, if user.bot { " · 🤖 Bot" } else { "" }), + format!("**Account created:** {} ({})", ts(created, 'D'), ts(created, 'R')), + ]; + if !badges.is_empty() { + lines.push(format!("**Badges:** {}", badges.join(", "))); + } + let mut card = Card::new(Some(accent)).header(&[&format!("### 👤 {}", escape(&display_name(state, guild, user))), &lines.join("\n")], Some(&avatar)); + + if let Some((g, m)) = member { + let mut roles: Vec<(i64, Id)> = m.roles().iter().filter_map(|r| state.cache.role(*r).map(|x| (x.position, *r))).collect(); + roles.sort_by_key(|(p, _)| std::cmp::Reverse(*p)); + let shown: Vec = roles.iter().take(20).map(|(_, r)| format!("<@&{r}>")).collect(); + let role_text = if roles.is_empty() { "None".to_string() } else { shown.join(" ") + &if roles.len() > 20 { format!(" +{} more", roles.len() - 20) } else { String::new() } }; + let mut server = vec![]; + if let Some(j) = m.joined_at() { + server.push(format!("**Joined:** {} ({})", ts(j.as_secs(), 'D'), ts(j.as_secs(), 'R'))); + } + if let Some(n) = m.nick() { + server.push(format!("**Nickname:** {}", escape(n))); + } + if let Some(p) = state.cache.presence(g, user.id) { + server.push(format!("**Status:** {}", match p.status() { + Status::Online => "🟢 Online", Status::Idle => "🌙 Idle", Status::DoNotDisturb => "⛔ Do not disturb", _ => "⚫ Offline", + })); + if let Some(a) = p.activities().iter().find(|a| a.kind != ActivityType::Custom && !a.name.is_empty()) { + let verb = match a.kind { + ActivityType::Playing => "Playing", ActivityType::Listening => "Listening to", ActivityType::Watching => "Watching", + ActivityType::Streaming => "Streaming", ActivityType::Competing => "Competing in", _ => "Doing", + }; + let detail = if a.kind == ActivityType::Listening { a.details.as_ref().map_or(String::new(), |d| format!(" — {}", escape(d))) } else { String::new() }; + server.push(format!("**Activity:** {verb} {}{detail}", escape(&a.name))); + } + } else { + server.push("**Status:** ⚫ Offline".to_string()); + } + if let Some(b) = m.premium_since() { + server.push(format!("**Boosting since:** {}", ts(b.as_secs(), 'D'))); + } + if let Some(t) = m.communication_disabled_until().filter(|t| (t.as_secs() as f64) > crate::audit::now()) { + server.push(format!("**⏱️ Timed out** until {}", ts(t.as_secs(), 'f'))); + } + let perms = state.guild_permissions(g, user.id); + let mut key: Vec<&str> = KEY_PERMS.iter().filter(|(p, _)| perms.contains(*p)).map(|(_, n)| *n).collect(); + if key.contains(&"Administrator") { + key = vec!["Administrator"]; + } + if !key.is_empty() { + server.push(format!("**Key permissions:** {}", key.join(", "))); + } + server.push(format!("**Roles ({}):** {role_text}", roles.len())); + card = card.separator(true, false).text(&server.join("\n")); + } + let mut buttons = vec![link_button("Avatar", &avatar)]; + if let Some(b) = full.and_then(|f| f.banner) { + card = card.gallery(&[&b]); + buttons.push(link_button("Banner", &b)); + } + card.row(buttons).build() +} + +async fn userinfo(ctx: Arc) -> Result<()> { + let user = target(&ctx, "user").await?; + ctx.defer().await?; + ctx.reply(user_card(&ctx.state, &user, ctx.guild_id).await).await +} + +// ---- server -------------------------------------------------------------------------------- + +fn emoji_limit(tier: u8) -> usize { + [50, 100, 150, 250][tier.min(3) as usize] +} + +fn sticker_limit(tier: u8) -> usize { + [5, 15, 30, 60][tier.min(3) as usize] +} + +async fn server_card(state: &State, guild: Id) -> Result { + let Some(g) = state.cache.guild(guild) else { bail_user!("I can't see that server.") }; + let cache = &state.cache; + let members: Vec> = cache.guild_members(guild).map(|m| m.iter().copied().collect()).unwrap_or_default(); + let bots = members.iter().filter(|u| cache.user(**u).is_some_and(|x| x.bot)).count(); + let online = members.iter().filter(|u| cache.presence(guild, **u).is_some_and(|p| p.status() != Status::Offline)).count(); + let total = g.member_count().unwrap_or(members.len() as u64) as usize; + let created = created_at(guild.get()); + let mut basics = vec![ + format!("**Owner:** <@{}>", g.owner_id()), + format!("**Created:** {} ({})", ts(created, 'D'), ts(created, 'R')), + format!("**ID:** `{guild}` · **Verification:** {:?}", g.verification_level()), + ]; + if let Some(d) = g.description() { + basics.insert(0, escape(&truncate(d, 300))); + } + let icon = g.icon().map(|i| format!("https://cdn.discordapp.com/icons/{guild}/{i}.{}?size=256", if i.is_animated() { "gif" } else { "png" })); + let banner = g.banner().map(|b| format!("https://cdn.discordapp.com/banners/{guild}/{b}.png?size=1024")); + let accent = colors::accent(state, icon.as_deref().or(banner.as_deref()), BLURPLE).await; + let mut kinds: HashMap = HashMap::new(); + for id in cache.guild_channels(guild).map(|c| c.iter().copied().collect::>()).unwrap_or_default() { + if let Some(c) = cache.channel(id) { + *kinds.entry(c.kind).or_default() += 1; + } + } + let n = |k: ChannelType| kinds.get(&k).copied().unwrap_or(0); + let voice = n(ChannelType::GuildVoice) + n(ChannelType::GuildStageVoice); + let tier: u8 = u8::from(g.premium_tier()); + let roles = cache.guild_roles(guild).map_or(0, |r| r.len()); + let emojis = cache.guild_emojis(guild).map_or(0, |e| e.len()); + let stickers = cache.guild_stickers(guild).map_or(0, |e| e.len()); + let boosters = members.iter().filter(|u| cache.member(guild, **u).is_some_and(|m| m.premium_since().is_some())).count(); + let mut counts = vec![ + format!("👥 **{}** members · {} people, {} bots · 🟢 {} online", thousands(total as u64), thousands(total.saturating_sub(bots) as u64), thousands(bots as u64), thousands(online as u64)), + format!("💬 **{}** text · 🔊 **{voice}** voice · 🗂️ **{}** categories{}", n(ChannelType::GuildText) + n(ChannelType::GuildAnnouncement), n(ChannelType::GuildCategory), + if n(ChannelType::GuildForum) > 0 { format!(" · 📋 **{}** forums", n(ChannelType::GuildForum)) } else { String::new() }), + format!("🎭 **{roles}** roles · 😀 **{emojis}/{}** emojis · 🏷️ **{stickers}/{}** stickers", emoji_limit(tier), sticker_limit(tier)), + format!("💎 Level **{tier}** · **{}** boosts from **{boosters}** members", g.premium_subscription_count().unwrap_or(0)), + ]; + counts.retain(|l| !l.is_empty()); + let mut card = Card::new(Some(accent)).header(&[&format!("### 🏰 {}", escape(g.name())), &basics.join("\n")], icon.as_deref()).separator(true, false).text(&counts.join("\n")); + let features: Vec = g.features().into_iter().filter_map(|f| { + let name = format!("{f:?}"); + ["Community", "Partnered", "Verified", "Discoverable", "VanityUrl", "AnimatedIcon", "Banner", "RoleIcons", "WelcomeScreenEnabled", "MemberVerificationGateEnabled"] + .contains(&name.as_str()).then(|| name) + }).collect(); + if !features.is_empty() { + card = card.footer(&format!("Features: {}", features.join(", "))); + } + let mut buttons = vec![]; + if let Some(i) = &icon { + buttons.push(link_button("Icon", i)); + } + if let Some(b) = &banner { + card = card.gallery(&[b]); + buttons.push(link_button("Banner", b)); + } + Ok(card.row(buttons).build()) +} + +async fn serverinfo(ctx: Arc) -> Result<()> { + let card = server_card(&ctx.state, ctx.guild()?).await?; + ctx.reply(card).await +} + +// ---- channel & role ------------------------------------------------------------------------ + +async fn channelinfo(ctx: Arc) -> Result<()> { + let guild = ctx.guild()?; + let id = ctx.args.id("channel").and_then(Id::new_checked).unwrap_or(ctx.channel_id); + let Some(c) = ctx.state.cache.channel(id).map(|c| c.clone()) else { bail_user!("I can't see that channel.") }; + let kind = format!("{:?}", c.kind); + let created = created_at(id.get()); + let mut lines = vec![format!("**Type:** {kind} · **ID:** `{id}`"), format!("**Created:** {} ({})", ts(created, 'D'), ts(created, 'R'))]; + if let Some(p) = c.parent_id.and_then(|p| ctx.state.cache.channel(p).and_then(|p| p.name.clone())) { + lines.push(format!("**Category:** {}", escape(&p))); + } + if matches!(c.kind, ChannelType::GuildText | ChannelType::GuildAnnouncement | ChannelType::GuildForum) { + if let Some(t) = c.topic.as_deref().filter(|t| !t.is_empty()) { + lines.push(format!("**Topic:** {}", escape(&truncate(t, 500)))); + } + let sm = c.rate_limit_per_user.unwrap_or(0); + lines.push(format!("**Slowmode:** {} · **NSFW:** {}", if sm > 0 { format!("{sm}s") } else { "off".into() }, if c.nsfw.unwrap_or(false) { "yes" } else { "no" })); + } + if matches!(c.kind, ChannelType::GuildVoice | ChannelType::GuildStageVoice) { + lines.push(format!("**Bitrate:** {} kbps · **User limit:** {} · **Region:** {}", c.bitrate.unwrap_or(0) / 1000, + c.user_limit.filter(|l| *l > 0).map_or("none".into(), |l| l.to_string()), c.rtc_region.as_deref().unwrap_or("automatic"))); + let inside: Vec = ctx.state.cache.voice_channel_states(id).map(|it| it.take(15).map(|s| format!("<@{}>", s.user_id())).collect()).unwrap_or_default(); + if !inside.is_empty() { + lines.push(format!("**In voice ({}):** {}", inside.len(), inside.join(", "))); + } + } + if c.kind == ChannelType::GuildCategory { + let n = ctx.state.cache.guild_channels(guild).map_or(0, |ids| ids.iter().filter(|i| ctx.state.cache.channel(**i).is_some_and(|x| x.parent_id == Some(id))).count()); + lines.push(format!("**Channels:** {n}")); + } + let everyone = ctx.state.cache.role(guild.cast()).map_or(Permissions::empty(), |r| r.permissions); + let (view, send) = (everyone.contains(Permissions::VIEW_CHANNEL), everyone.contains(Permissions::SEND_MESSAGES)); + lines.push(format!("**Everyone can:** {}, {}", if view { "view".into() } else { "~~view~~" }, if send { "send".into() } else { "~~send~~" })); + let card = Card::new(Some(BLURPLE)).header(&[&format!("### #️⃣ {}", escape(c.name.as_deref().unwrap_or("?"))), &format!("<#{id}>\n{}", lines.join("\n"))], None).build(); + ctx.reply(card).await +} + +async fn roleinfo(ctx: Arc) -> Result<()> { + let guild = ctx.guild()?; + let Some(text) = ctx.args.str("role") else { bail_user!("Which role?") }; + let cache = &ctx.state.cache; + let id = ctx.args.id("role").and_then(Id::::new_checked).filter(|r| cache.role(*r).is_some()).or_else(|| { + let wanted = text.trim_start_matches('@').to_lowercase(); + cache.guild_roles(guild)?.iter().copied().find(|r| cache.role(*r).is_some_and(|x| x.name.to_lowercase() == wanted)) + }); + let Some(id) = id else { bail_user!("No role called `{}`.", escape(text)) }; + let role = cache.role(id).map(|r| r.resource().clone()).ok_or_else(|| crate::error::UserError::new("I can't see that role."))?; + let members = cache.guild_members(guild).map_or(0, |ms| ms.iter().filter(|u| cache.member(guild, **u).is_some_and(|m| m.roles().contains(&id))).count()); + let total = cache.guild_roles(guild).map_or(1, |r| r.len()) - 1; + let created = created_at(id.get()); + let lines = vec![ + format!("<@&{id}> · **ID:** `{id}`"), + format!("**Colour:** `#{:06X}` · **Position:** {} of {total}", role.color, role.position), + format!("**Members:** {} · **Created:** {}", thousands(members as u64), ts(created, 'D')), + format!("**Shown separately:** {} · **Mentionable:** {}{}", if role.hoist { "yes" } else { "no" }, if role.mentionable { "yes" } else { "no" }, if role.managed { " · **Managed by an integration**" } else { "" }), + ]; + let perms = if role.permissions.contains(Permissions::ADMINISTRATOR) { vec!["Administrator (every permission)".to_string()] } else { perm_list(role.permissions) }; + let icon = role.icon.map(|i| format!("https://cdn.discordapp.com/role-icons/{id}/{i}.png")); + let card = Card::new(Some(if role.color != 0 { role.color } else { BLURPLE })) + .header(&[&format!("### 🎭 {}", escape(&role.name)), &lines.join("\n")], icon.as_deref()) + .separator(true, false) + .text(&format!("**Permissions:** {}", if perms.is_empty() { "none beyond @everyone".to_string() } else { perms.join(", ") })) + .build(); + ctx.reply(card).await +} + +// ---- avatar & banner ----------------------------------------------------------------------- + +async fn avatar_card(state: &State, user: &User, requester: &str, guild: Option>) -> Component { + let shown = display_avatar(state, guild, user, 1024); + let mut images = vec![shown.clone()]; + let big = |u: &str| u.replace("size=1024", "size=4096"); + let mut buttons = vec![link_button("Open", &big(&shown))]; + let has_server = guild.and_then(|g| state.cache.member(g, user.id)).is_some_and(|m| m.avatar().is_some()); + if has_server && user.avatar.is_some() { + let global = global_avatar(user, 1024); + buttons.push(link_button("Global avatar", &big(&global))); + images.push(global); + } + let accent = colors::accent(state, Some(&images[0]), BLURPLE).await; + let urls: Vec<&str> = images.iter().map(String::as_str).collect(); + Card::new(Some(accent)).text(&format!("### 🖼️ {}'s avatar", escape(&display_name(state, guild, user)))).gallery(&urls) + .footer(&format!("Requested by {requester}")).row(buttons).build() +} + +async fn banner_card(state: &State, user: &User, requester: &str) -> Option { + let full = full_user(state, user.id).await?; + let banner = full.banner?; + let accent = colors::accent(state, Some(&banner), full.accent.unwrap_or(BLURPLE)).await; + Some(Card::new(Some(accent)).text(&format!("### 🏞️ {}'s banner", escape(user.global_name.as_deref().unwrap_or(&user.name)))) + .gallery(&[&banner]).footer(&format!("Requested by {requester}")).row(vec![link_button("Open", &banner.replace("size=1024", "size=4096"))]).build()) +} + +async fn avatar(ctx: Arc) -> Result<()> { + let user = target(&ctx, "user").await?; + ctx.defer().await?; + ctx.reply(avatar_card(&ctx.state, &user, &ctx.user_name, ctx.guild_id).await).await +} + +async fn banner(ctx: Arc) -> Result<()> { + let user = target(&ctx, "user").await?; + ctx.defer().await?; + match banner_card(&ctx.state, &user, &ctx.user_name).await { + Some(c) => ctx.reply(c).await, + None => ctx.fail(&format!("🙈 {} doesn't have a banner.", escape(&display_name(&ctx.state, ctx.guild_id, &user)))).await, + } +} + +pub fn commands() -> Vec { + let user = || Opt::opt("user", "Who to look up (defaults to you)", OptKind::User); + vec![ + Command::new("userinfo", "utility", "Profile card: account age, roles, status, badges and banner", |c| userinfo(c).boxed()) + .aliases(&["ui", "user", "whois"]).usage("[member]").opt(user()), + Command::new("serverinfo", "utility", "Server card: members, channels, boosts, features", |c| serverinfo(c).boxed()) + .aliases(&["si", "guildinfo", "server"]).guild_only(), + Command::new("channelinfo", "utility", "Channel card: type, topic, slowmode, permissions", |c| channelinfo(c).boxed()) + .aliases(&["ci", "channel"]).usage("[#channel]").opt(Opt::opt("channel", "Defaults to this channel", OptKind::Channel)).guild_only(), + Command::new("roleinfo", "utility", "Role card: colour, members, position and permissions", |c| roleinfo(c).boxed()) + .aliases(&["ri"]).usage("").opt(Opt::req("role", "The role to inspect", OptKind::Role)).guild_only(), + Command::new("avatar", "utility", "Someone's avatar in full size (server and global). Reply to a message for its author.", |c| avatar(c).boxed()) + .aliases(&["av", "pfp"]).usage("[member]").opt(user()).prefix_only(), + Command::new("banner", "utility", "Someone's profile banner in full size. Reply to a message for its author.", |c| banner(c).boxed()) + .aliases(&["bn"]).usage("[member]").opt(user()).prefix_only(), + Command::new("Show Avatar", "apps", "Someone's avatar in full size (server and global).", |c| avatar(c).boxed()).user_menu(), + Command::new("Show Banner", "apps", "Someone's profile banner in full size.", |c| banner(c).boxed()).user_menu(), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn snowflake_dates() { + assert_eq!(created_at((1_704_067_200_000u64 - 1_420_070_400_000) << 22), 1_704_067_200); + } + + #[test] + fn permission_names_read_like_discord() { + let names = perm_list(Permissions::MANAGE_GUILD | Permissions::KICK_MEMBERS); + assert!(names.contains(&"Manage Server".to_string()) && names.contains(&"Kick Members".to_string())); + } + + #[test] + fn limits_by_boost_level() { + assert_eq!((emoji_limit(0), emoji_limit(3), sticker_limit(2), emoji_limit(9)), (50, 250, 30, 250)); + } +} diff --git a/src/commands/lastfm/api.rs b/src/commands/lastfm/api.rs new file mode 100644 index 0000000..525bf9d --- /dev/null +++ b/src/commands/lastfm/api.rs @@ -0,0 +1,231 @@ +//! The Last.fm web API: a small client with a response cache, and the user ↔ username links (data/lastfm.json). +use crate::paths; +use crate::state::State; +use crate::storage::JsonStore; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; +use tokio::sync::Semaphore; + +const API_URL: &str = "https://ws.audioscrobbler.com/2.0/"; +/// Last.fm's grey star +const PLACEHOLDER_IMAGE: &str = "2a96cbd8b46e442fc41c2b86b821562f"; + +#[derive(Debug)] +pub enum Error { + NotFound(String), + Other(String), +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::NotFound(m) | Error::Other(m) => f.write_str(m), + } + } +} + +pub struct Lfm { + web: reqwest::Client, + key: String, + cache: Mutex>, + slots: Semaphore, +} + +impl Lfm { + pub fn get(state: &State) -> Option> { + static L: OnceLock>> = OnceLock::new(); + L.get_or_init(|| { + let key = std::env::var("LASTFM_API_KEY").ok().filter(|k| !k.is_empty())?; + Some(Arc::new(Lfm { web: state.web.clone(), key, cache: Default::default(), slots: Semaphore::new(6) })) + }) + .clone() + } + + /// One API call. `ttl` seconds of caching (0 = none). + pub async fn call(&self, method: &str, ttl: u64, params: &[(&str, String)]) -> Result { + let mut sorted: Vec<&(&str, String)> = params.iter().collect(); + sorted.sort(); + let key = format!("{method}|{}", sorted.iter().map(|(k, v)| format!("{k}={v}")).collect::>().join("&")); + if ttl > 0 { + if let Some((until, v)) = self.cache.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { + if *until > Instant::now() { + return Ok(v.clone()); + } + } + } + let mut query: Vec<(&str, String)> = vec![("method", method.to_string()), ("api_key", self.key.clone()), ("format", "json".into())]; + query.extend(params.iter().map(|(k, v)| (*k, v.clone()))); + let _slot = self.slots.acquire().await; + let mut last = None; + for attempt in 0..2 { + match self.web.get(API_URL).query(&query).timeout(Duration::from_secs(12)).send().await { + Ok(r) => match r.json::().await { + Ok(v) => { + last = Some(v); + break; + } + Err(_) if attempt == 0 => tokio::time::sleep(Duration::from_millis(500)).await, + Err(_) => return Err(Error::Other("Last.fm sent an unexpected response.".into())), + }, + Err(_) if attempt == 0 => tokio::time::sleep(Duration::from_millis(500)).await, + Err(_) => return Err(Error::Other("Last.fm isn't responding right now — try again in a moment.".into())), + } + } + let data = last.ok_or_else(|| Error::Other("Last.fm isn't responding right now — try again in a moment.".into()))?; + if let Some(code) = data.get("error").and_then(Value::as_i64) { + let message = data["message"].as_str().unwrap_or("Unknown error").to_string(); + return Err(match code { + 6 => Error::NotFound(message), + 29 => Error::Other("Last.fm is rate limiting us — try again in a minute.".into()), + 17 => Error::Other("That profile's listening history is private.".into()), + _ => Error::Other(format!("Last.fm error: {message}")), + }); + } + if ttl > 0 { + let mut c = self.cache.lock().unwrap_or_else(|e| e.into_inner()); + if c.len() > 2000 { + let now = Instant::now(); + c.retain(|_, v| v.0 > now); + } + c.insert(key, (Instant::now() + Duration::from_secs(ttl), data.clone())); + } + Ok(data) + } + + pub async fn user_info(&self, username: &str) -> Result { + Ok(self.call("user.getInfo", 120, &[("user", username.into())]).await?["user"].clone()) + } + + pub async fn recent(&self, username: &str, limit: usize) -> Result, Error> { + let d = self.call("user.getRecentTracks", 8, &[("user", username.into()), ("limit", limit.to_string())]).await?; + Ok(as_list(&d["recenttracks"]["track"])) + } + + pub async fn top(&self, username: &str, kind: &str, period: &str, limit: usize) -> Result, Error> { + let d = self.top_raw(username, kind, period, limit).await?; + Ok(as_list(&d[format!("top{kind}")][&kind[..kind.len() - 1]])) + } + + pub async fn top_raw(&self, username: &str, kind: &str, period: &str, limit: usize) -> Result { + let method = match kind { + "artists" => "user.getTopArtists", + "albums" => "user.getTopAlbums", + _ => "user.getTopTracks", + }; + self.call(method, 300, &[("user", username.into()), ("period", period.into()), ("limit", limit.to_string())]).await + } + + /// artist/album/track.getInfo; includes the user's playcount when `username` is given. + pub async fn entity(&self, kind: &str, name: &str, artist: Option<&str>, username: Option<&str>) -> Result { + let mut p: Vec<(&str, String)> = vec![("artist", artist.unwrap_or(name).into()), ("autocorrect", "1".into())]; + if let Some(u) = username { + p.push(("username", u.into())); + } + if kind != "artist" { + p.push((kind, name.into())); + } + Ok(self.call(&format!("{kind}.getInfo"), 300, &p).await?[kind].clone()) + } +} + +/// Last.fm returns a bare object instead of a one-item list. Normalise that. +pub fn as_list(v: &Value) -> Vec { + match v { + Value::Null => vec![], + Value::Array(a) => a.clone(), + other => vec![other.clone()], + } +} + +pub fn best_image(images: &Value) -> Option { + as_list(images).iter().rev().find_map(|img| { + let url = img["#text"].as_str()?; + (!url.is_empty() && !url.contains(PLACEHOLDER_IMAGE) && !url.ends_with(".gif")).then(|| url.replace("http://", "https://")) + }) +} + +fn plus(s: &str) -> String { + urlencoding::encode(s).replace("%20", "+") +} + +pub fn fm_url(parts: &[&str]) -> String { + format!("https://www.last.fm/music/{}", parts.iter().map(|p| plus(p)).collect::>().join("/")) +} + +/// (artist, title) from a Last.fm track URL like https://www.last.fm/music/Artist/_/Title. +pub fn track_from_url(url: &str) -> Option<(String, String)> { + let u = reqwest::Url::parse(url).ok()?; + let parts: Vec<&str> = u.path().trim_matches('/').split('/').collect(); + if parts.len() >= 4 && parts[0] == "music" && parts[2] == "_" { + let dec = |s: &str| urlencoding::decode(&s.replace('+', " ")).map(|c| c.into_owned()).ok(); + return Some((dec(parts[1])?, dec(parts[3])?)); + } + None +} + +// ---- linked accounts ---------------------------------------------------------------------------------------------- + +fn links() -> &'static Arc { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| JsonStore::open(paths::data(&["lastfm.json"]))) +} + +pub fn linked(user: u64) -> Option { + links().get(user).and_then(|v| v.as_str().map(str::to_string)) +} + +pub fn set_link(user: u64, name: Option<&str>) { + match name { + Some(n) => links().set(user, json!(n)), + None => { + links().pop(user); + } + } +} + +/// Everyone with a linked account: (user id, Last.fm name). +pub fn all_links() -> Vec<(u64, String)> { + links().snapshot().iter().filter_map(|(k, v)| Some((k.parse().ok()?, v.as_str()?.to_string()))).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lists_and_images_are_normalised() { + assert_eq!(as_list(&json!({"a": 1})).len(), 1); + assert_eq!(as_list(&Value::Null).len(), 0); + assert_eq!(as_list(&json!([1, 2])).len(), 2); + let imgs = json!([{"#text": "http://x/small.jpg"}, {"#text": "http://x/big.png"}, {"#text": ""}]); + assert_eq!(best_image(&imgs).as_deref(), Some("https://x/big.png")); + let star = json!([{"#text": "https://x/2a96cbd8b46e442fc41c2b86b821562f.png"}]); + assert_eq!(best_image(&star), None); + } + + #[test] + fn urls_round_trip() { + assert_eq!(fm_url(&["AC/DC", "Back In Black"]), "https://www.last.fm/music/AC%2FDC/Back+In+Black"); + assert_eq!(track_from_url("https://www.last.fm/music/Daft+Punk/_/Get+Lucky").unwrap(), ("Daft Punk".to_string(), "Get Lucky".to_string())); + assert_eq!(track_from_url("https://www.last.fm/music/Daft+Punk"), None); + } + + /// `LASTFM_API_KEY=… cargo test lastfm_live -- --ignored --nocapture` + #[tokio::test] + #[ignore = "needs LASTFM_API_KEY and the internet"] + async fn lastfm_live_reads_a_public_profile() { + let Ok(key) = std::env::var("LASTFM_API_KEY") else { return }; + let api = Lfm { web: reqwest::Client::new(), key, cache: Default::default(), slots: Semaphore::new(6) }; + let info = api.user_info("rj").await.expect("user.getInfo"); + println!("rj has {} scrobbles", info["playcount"]); + assert!(info["playcount"].as_str().is_some()); + let top = api.top("rj", "artists", "overall", 5).await.expect("top artists"); + assert_eq!(top.len(), 5); + println!("top artist: {} ({} plays)", top[0]["name"], top[0]["playcount"]); + assert!(matches!(api.user_info("this-user-does-not-exist-9z8y7x").await, Err(Error::NotFound(_)))); + let album = api.entity("album", "OK Computer", Some("Radiohead"), None).await.expect("album.getInfo"); + assert!(best_image(&album["image"]).is_some()); + } +} diff --git a/src/commands/lastfm/extras.rs b/src/commands/lastfm/extras.rs new file mode 100644 index 0000000..6e379e0 --- /dev/null +++ b/src/commands/lastfm/extras.rs @@ -0,0 +1,850 @@ +//! Who Knows, album charts, Pixel Jumble, lyrics, the Listen button and the pictures they need. +use super::super::games::{btn, Game, Rendered, Reply, LOSE}; +use super::api::{all_links, as_list, best_image, linked, track_from_url, Lfm}; +use super::{link, normalise_title, period_label, period_of}; +use crate::cmd::{Command, Ctx, Opt, OptKind}; +use crate::pix; +use crate::state::State; +use crate::text::{self, Look}; +use crate::ui::{escape, truncate, Card, GREEN, RED}; +use crate::{colors, interact, pager, paths}; +use anyhow::Result; +use cosmic_text::Align; +use futures::FutureExt; +use image::{Rgba, RgbaImage}; +use rand::seq::IndexedRandom as _; +use serde_json::Value; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; +use tokio::sync::Semaphore; +use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_model::channel::message::component::{ButtonStyle, Component}; +use twilight_model::channel::message::{AllowedMentions, MessageFlags}; +use twilight_model::http::attachment::Attachment; + +// ---- pictures ------------------------------------------------------------------------------------------------------------ + +/// Download an image, remembering recent ones (charts are re-run a lot on a slow line). +pub async fn fetch_image(state: &State, url: &str) -> Option> { + static C: OnceLock>, Vec)>> = OnceLock::new(); + let cache = C.get_or_init(Default::default); + if let Some(d) = cache.lock().unwrap_or_else(|e| e.into_inner()).0.get(url) { + return Some(d.clone()); + } + let data = super::super::media::fetch_limited(state, url, 8 * 1024 * 1024).await?; + let mut c = cache.lock().unwrap_or_else(|e| e.into_inner()); + c.0.insert(url.to_string(), data.clone()); + c.1.push(url.to_string()); + while c.1.len() > 400 { + let old = c.1.remove(0); + c.0.remove(&old); + } + Some(data) +} + +/// Last.fm no longer serves artist photos; look one up via MusicBrainz → Wikimedia Commons. +pub async fn artist_image(state: &State, artist: &str) -> Option { + static CACHE: OnceLock)>>> = OnceLock::new(); + static SLOT: Semaphore = Semaphore::const_new(1); // MusicBrainz allows 1 request/second + let cache = CACHE.get_or_init(Default::default); + let key = artist.to_lowercase(); + if let Some((until, v)) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { + if *until > Instant::now() { + return v.clone(); + } + } + let image = async { + let _s = SLOT.acquire().await.ok()?; + let get = |url: String, q: Vec<(&'static str, String)>| { + let web = state.web.clone(); + async move { web.get(url).query(&q).timeout(Duration::from_secs(8)).send().await.ok()?.json::().await.ok() } + }; + let found = get("https://musicbrainz.org/ws/2/artist/".into(), vec![("query", format!("artist:\"{artist}\"")), ("fmt", "json".into()), ("limit", "1".into())]).await?; + let first = found["artists"].get(0)?; + if first["score"].as_i64().unwrap_or(0) < 90 { + return None; + } + tokio::time::sleep(Duration::from_secs(1)).await; + let rel = get(format!("https://musicbrainz.org/ws/2/artist/{}", first["id"].as_str()?), vec![("inc", "url-rels".into()), ("fmt", "json".into())]).await?; + let commons = rel["relations"].as_array()?.iter().find_map(|r| { + let res = r["url"]["resource"].as_str()?; + (r["type"].as_str() == Some("image") && res.contains("commons.wikimedia.org/wiki/File:")).then(|| res.to_string()) + })?; + let pages = get("https://commons.wikimedia.org/w/api.php".into(), vec![("action", "query".into()), ("titles", commons.rsplit('/').next()?.to_string()), ("prop", "imageinfo".into()), ("iiprop", "url".into()), ("iiurlwidth", "300".into()), ("format", "json".into())]).await?; + pages["query"]["pages"].as_object()?.values().find_map(|p| { + let i = p["imageinfo"].get(0)?; + i["thumburl"].as_str().or_else(|| i["url"].as_str()).map(str::to_string) + }) + } + .await; + cache.lock().unwrap_or_else(|e| e.into_inner()).insert(key, (Instant::now() + Duration::from_secs(86400), image.clone())); + image +} + +/// Picture for a top-list's #1: the album cover, or the artist's photo. +pub async fn cover_for(state: &State, kind: &str, item: &Value) -> Option { + if kind == "albums" { + if let Some(i) = best_image(&item["image"]) { + return Some(i); + } + } + let artist = if kind == "artists" { item["name"].as_str() } else { item["artist"]["name"].as_str() }?; + artist_image(state, artist).await +} + +// ---- who knows ---------------------------------------------------------------------------------------------------------------- + +async fn whoknows_card(ctx: &Ctx, api: &Arc, kind: &str, name: &str, artist: Option<&str>) -> Component { + let guild = ctx.guild_id.unwrap(); + let members: Vec<(u64, String)> = all_links().into_iter().filter(|(u, _)| twilight_model::id::Id::new_checked(*u).is_some_and(|id| ctx.state.cache.member(guild, id).is_some())).collect(); + if members.is_empty() { + return Card::new(Some(RED)).text("### ❌ No linked accounts\nNo one in this server has linked Last.fm yet.").build(); + } + let results = futures::future::join_all(members.iter().map(|(u, un)| async move { + match api.entity(kind, name, artist, Some(un)).await { + Ok(d) => { + let count = if kind == "artist" { &d["stats"]["userplaycount"] } else { &d["userplaycount"] }; + let n = count.as_str().and_then(|s| s.parse::().ok()).or_else(|| count.as_u64()).unwrap_or(0); + (*u, n, Some(d)) + } + Err(_) => (*u, 0, None), + } + })) + .await; + let Some(entity) = results.iter().find_map(|r| r.2.clone()) else { return Card::new(Some(RED)).text(&format!("### ❌ Not found\nLast.fm doesn't know that {kind}.")).build() }; + let mut listeners: Vec<(u64, u64)> = results.iter().filter(|r| r.1 > 0).map(|r| (r.0, r.1)).collect(); + listeners.sort_by_key(|l| std::cmp::Reverse(l.1)); + let display = entity["name"].as_str().unwrap_or(name).to_string(); + let entity_artist = if kind != "artist" { entity["artist"].as_str().or_else(|| entity["artist"]["name"].as_str()).or(artist).map(str::to_string) } else { None }; + let image = match kind { + "artist" => artist_image(&ctx.state, &display).await, + "album" => best_image(&entity["image"]), + _ => best_image(&entity["album"]["image"]), + }; + let medals = ["🥇", "🥈", "🥉"]; + let lines: Vec = listeners.iter().take(15).enumerate().map(|(i, (u, c))| format!("{} <@{u}> — **{}** plays", medals.get(i).map_or(format!("`{}.`", i + 1), |m| m.to_string()), crate::converters::thousands(*c))).collect(); + let guild_name = ctx.state.cache.guild(guild).map(|g| g.name().to_string()).unwrap_or_default(); + let subtitle = match &entity_artist { + Some(a) => format!("by **{}**", escape(a)), + None => format!("in {}", escape(&guild_name)), + }; + let accent = colors::accent(&ctx.state, image.as_deref(), GREEN).await; + let total: u64 = listeners.iter().map(|l| l.1).sum(); + Card::new(Some(accent)) + .header(&[&format!("-# 🏆 Who knows this {kind}?"), &format!("### {}\n{subtitle}", link(&truncate(&display, 90), entity["url"].as_str()))], image.as_deref()) + .separator(true, false) + .text(&if lines.is_empty() { "*No one here has played this yet.*".to_string() } else { lines.join("\n") }) + .footer(&format!("{} listener{} · {} plays · {} linked members", listeners.len(), if listeners.len() != 1 { "s" } else { "" }, crate::converters::thousands(total), members.len())) + .build() +} + +async fn run_whoknows(ctx: &Arc, kind: &str, query: Option<&str>) -> Result<()> { + ctx.guild()?; + let api = super::lfm(&ctx.state)?; + ctx.defer().await?; + let username = linked(ctx.user_id.get()); + let (mut name, mut artist): (Option, Option) = (None, None); + match query.map(str::trim).filter(|q| !q.is_empty()) { + Some(q) if kind == "artist" => name = Some(q.to_string()), + Some(q) if q.contains(" - ") => { + let (a, n) = q.split_once(" - ").unwrap(); + (artist, name) = (Some(a.trim().to_string()), Some(n.trim().to_string())); + } + q => { + if let Some(u) = &username { + if let Some(track) = api.recent(u, 1).await.ok().and_then(|t| t.into_iter().next()) { + artist = track["artist"]["#text"].as_str().map(str::to_string); + name = match kind { + "artist" => artist.clone(), + "track" => q.map(str::to_string).or_else(|| track["name"].as_str().map(str::to_string)), + _ => q.map(str::to_string).or_else(|| track["album"]["#text"].as_str().map(str::to_string)), + }; + } + } + } + } + let (Some(n), true) = (name, kind == "artist" || artist.is_some()) else { + if username.is_none() { + return ctx.reply(super::link_prompt(None)).await; + } + let example = match kind { "artist" => "Artist", "track" => "Artist - Track", _ => "Artist - Album" }; + return super::error(ctx, &format!("Tell me what to look up (`{example}`) or play something first.")).await; + }; + ctx.reply(whoknows_card(ctx, &api, kind, &n, artist.as_deref()).await).await +} + +async fn wk(ctx: Arc) -> Result<()> { + let query = ctx.args.str("query").map(str::to_string); + run_whoknows(&ctx, "artist", query.as_deref()).await +} + +async fn wkt(ctx: Arc) -> Result<()> { + let q = ctx.args.str("query").map(str::to_string); + run_whoknows(&ctx, "track", q.as_deref()).await +} + +async fn wka(ctx: Arc) -> Result<()> { + let q = ctx.args.str("query").map(str::to_string); + run_whoknows(&ctx, "album", q.as_deref()).await +} + +// ---- chart ----------------------------------------------------------------------------------------------------------------------- + +/// "4x4" / "weekly" words → (rows, cols, period). +pub fn parse_chart_args(args: &[&str]) -> Result<(usize, usize, &'static str), String> { + let re = regex::Regex::new(r"^(\d{1,2})x(\d{1,2})$").unwrap(); + let (mut rows, mut cols, mut period) = (3usize, 3usize, "7day"); + for a in args.iter().map(|a| a.to_lowercase()).filter(|a| !a.is_empty()) { + if let Some(m) = re.captures(&a) { + rows = m[1].parse().unwrap_or(3); + cols = m[2].parse().unwrap_or(3); + } else if let Some(p) = period_of(&a) { + period = p; + } else { + return Err(format!("I don't understand `{}`. Use a size like `4x4` and a period like `weekly`, `monthly`, `yearly` or `alltime`.", escape(&truncate(&a, 30)))); + } + } + if !(1..=10).contains(&rows) || !(1..=10).contains(&cols) { + return Err("Charts can be at most 10x10.".into()); + } + Ok((rows, cols, period)) +} + +/// The collage. Missing covers become a dark tile with the album and artist name. +pub fn compose_chart(covers: &[Option>], albums: &[Value], rows: usize, cols: usize) -> (Vec, &'static str) { + let cell = (1080 / rows.max(cols)).max(100) as i32; + let pad = 4; + let mut canvas = RgbaImage::from_pixel((cols as i32 * cell) as u32, (rows as i32 * cell) as u32, Rgba([18, 18, 18, 255])); + let look = Look::new(None, false, [220, 220, 220]); + let size = ((cell / 11).max(11)) as f32; + for (i, album) in albums.iter().enumerate().take(rows * cols) { + let (x, y) = ((i % cols) as i32 * cell, (i / cols) as i32 * cell); + let inner = (cell - 2 * pad) as u32; + if let Some(img) = covers.get(i).and_then(|c| c.as_deref()).and_then(pix::decode) { + let resized = image::imageops::resize(&img, inner, inner, image::imageops::FilterType::Lanczos3); + image::imageops::overlay(&mut canvas, &resized, (x + pad) as i64, (y + pad) as i64); + continue; + } + pix::rounded_rect(&mut canvas, x + pad, y + pad, cell - 2 * pad, cell - 2 * pad, 0, Rgba([40, 40, 40, 255])); + let label = format!("{}\n\n{}", album["name"].as_str().unwrap_or("?"), album["artist"]["name"].as_str().unwrap_or("")); + let para = text::layout(&label, size, &look, Some((cell - 2 * pad - 12) as f32), Align::Left); + para.draw(&mut canvas, x + pad + 6, y + pad + 6); + } + if rows * cols > 9 { + let rgb = image::DynamicImage::ImageRgba8(canvas).to_rgb8(); + let mut out = std::io::Cursor::new(Vec::new()); + let _ = rgb.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 88)); + (out.into_inner(), "chart.jpg") + } else { + (pix::encode_png(&canvas), "chart.png") + } +} + +async fn chart(ctx: Arc) -> Result<()> { + let words: Vec = if ctx.is_slash() { [ctx.args.str("size"), ctx.args.str("period")].into_iter().flatten().map(str::to_string).collect() } else { ctx.args.str("args").unwrap_or("").split_whitespace().map(str::to_string).collect() }; + let refs: Vec<&str> = words.iter().map(String::as_str).collect(); + let (rows, cols, period) = match parse_chart_args(&refs) { + Ok(x) => x, + Err(e) => return super::error(&ctx, &e).await, + }; + let api = super::lfm(&ctx.state)?; + let Some(username) = super::username_or_prompt(&ctx, ctx.user_id).await? else { return Ok(()) }; + ctx.defer().await?; + let albums = match api.top(&username, "albums", period, rows * cols).await { + Ok(a) => a, + Err(e) => return super::error(&ctx, &e.to_string()).await, + }; + if albums.is_empty() { + return super::error(&ctx, &format!("No albums scrobbled in this period ({}).", period_label(period).to_lowercase())).await; + } + let cell = 1080 / rows.max(cols); + let slots = Arc::new(Semaphore::new(8)); + let covers: Vec>> = futures::future::join_all(albums.iter().map(|a| { + let (state, slots) = (ctx.state.clone(), slots.clone()); + let url = best_image(&a["image"]).map(|u| if cell <= 174 { u.replace("/300x300/", "/174s/") } else { u }); + async move { + let _p = slots.acquire().await.ok()?; + fetch_image(&state, &url?).await + } + })) + .await; + let (albums2, covers2) = (albums.clone(), covers.clone()); + let (bytes, name) = tokio::task::spawn_blocking(move || compose_chart(&covers2, &albums2, rows, cols)).await?; + let plays: u64 = albums.iter().map(|a| a["playcount"].as_str().and_then(|p| p.parse::().ok()).unwrap_or(0)).sum(); + let first = covers.iter().position(Option::is_some).and_then(|i| best_image(&albums[i]["image"])); + let accent = colors::accent(&ctx.state, first.as_deref(), GREEN).await; + let card = Card::new(Some(accent)).text(&format!("### 📊 {} album chart · {}\n-# {rows}x{cols} · {} albums · {} plays", period_label(period), escape(&username), albums.len(), crate::converters::thousands(plays))).gallery(&[&format!("attachment://{name}")]).build(); + ctx.reply_file(card, name, bytes).await +} + +// ---- pixel jumble ---------------------------------------------------------------------------------------------------------------- + +/// difflib's `SequenceMatcher.ratio()`: 2 × matching characters / total characters. +pub fn similarity(a: &str, b: &str) -> f64 { + fn matching(a: &[char], b: &[char]) -> usize { + if a.is_empty() || b.is_empty() { + return 0; + } + let (mut best, mut ai, mut bi) = (0, 0, 0); + let mut prev = vec![0usize; b.len() + 1]; + for i in 0..a.len() { + let mut cur = vec![0usize; b.len() + 1]; + for j in 0..b.len() { + if a[i] == b[j] { + cur[j + 1] = prev[j] + 1; + if cur[j + 1] > best { + (best, ai, bi) = (cur[j + 1], i + 1 - cur[j + 1], j + 1 - cur[j + 1]); + } + } + } + prev = cur; + } + if best == 0 { + return 0; + } + best + matching(&a[..ai], &b[..bi]) + matching(&a[ai + best..], &b[bi + best..]) + } + let (x, y): (Vec, Vec) = (a.chars().collect(), b.chars().collect()); + if x.is_empty() && y.is_empty() { + return 1.0; + } + 2.0 * matching(&x, &y) as f64 / (x.len() + y.len()) as f64 +} + +fn pixelate(cover: &RgbaImage, level: u32) -> Vec { + let block = ((6 - level.min(5)) * 6).max(1); + let small = image::imageops::resize(cover, (cover.width() / block).max(1), (cover.height() / block).max(1), image::imageops::FilterType::Triangle); + pix::encode_png(&image::imageops::resize(&small, 600, 600, image::imageops::FilterType::Nearest)) +} + +pub struct Pixel { + /// who ran the command: only they can use Hint and Give up (everyone can guess) + owner: u64, + album: String, + artist: String, + url: Option, + cover: RgbaImage, + level: u32, + started: Instant, + /// (title, body, accent) once the round is over + result: Option<(String, String, u32)>, +} + +const MAX_LEVEL: u32 = 5; + +impl Pixel { + fn answer_text(&self) -> String { + format!("The album was **{}** by **{}**.", link(&self.album, self.url.as_deref()), escape(&self.artist)) + } + + fn end(&mut self, title: String, body: String, accent: u32) { + self.result = Some((title, body, accent)); + } +} + +impl Game for Pixel { + fn players(&self) -> Vec { + vec![] // anyone can play + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(180) + } + + /// Every chat message in the channel is a guess — from anyone, linked or not. + fn chat(&mut self, who: u64, text: &str) -> bool { + if self.result.is_some() || text.chars().count() > 200 { + return false; + } + let (wanted, given) = (normalise_title(&self.album), normalise_title(text)); + if given.is_empty() || wanted.is_empty() { + return false; + } + if text.trim().to_lowercase() == self.album.to_lowercase() || given == wanted || similarity(&given, &wanted) >= 0.85 { + let secs = self.started.elapsed().as_secs(); + let body = format!("{}\n-# Solved in {secs}s at level {}/{MAX_LEVEL}", self.answer_text(), self.level); + self.end(format!("### 🎉 <@{who}> got it!"), body, GREEN); + return true; + } + false + } + + fn render(&self, t: u32) -> Rendered { + let (title, body, accent, file) = match &self.result { + Some((ti, bo, ac)) => (ti.clone(), bo.clone(), *ac, ("answer.png".to_string(), pix::encode_png(&self.cover))), + None => (format!("### 🧩 Pixel Jumble · Level {}/{MAX_LEVEL}", self.level), "-# Type your guess in chat (or press Guess) — anyone can answer.".to_string(), GREEN, (format!("pixel{}.png", self.level), pixelate(&self.cover, self.level))), + }; + let mut card = Card::new(Some(accent)).text(&title).text(&body).gallery(&[&format!("attachment://{}", file.0)]); + if self.result.is_none() { + card = card.row(vec![btn(t, "guess", "Guess", "🎯", ButtonStyle::Success, false), btn(t, "hint", "Hint", "💡", ButtonStyle::Primary, self.level >= MAX_LEVEL), btn(t, "giveup", "Give up", "🏳️", ButtonStyle::Secondary, false)]); + } + Rendered { card, file: Some(file) } + } + + fn click(&mut self, who: u64, action: &str, _: &[String], fields: &HashMap) -> Reply { + if matches!(action, "hint" | "giveup") && who != self.owner { + return Reply::Private(format!("Only <@{}> can use that — you can still guess in chat or with **Guess**.", self.owner)); + } + match action { + "guess" => Reply::Modal { action: "guesssub".into(), title: "Your guess".into(), fields: vec![interact::text_field("guess", "Album name", None, "", 200, false, None)] }, + "hint" => { + if self.level >= MAX_LEVEL { + return Reply::Private("🤷 That's already the clearest picture!".into()); + } + self.level += 1; + Reply::Update + } + "giveup" => { + let body = self.answer_text(); + self.end("### 🏳️ Gave up".into(), body, RED); + Reply::Update + } + "guesssub" => { + if self.result.is_some() { + return Reply::Private("This round is already over.".into()); + } + let guess = fields.get("guess").cloned().unwrap_or_default(); + let (wanted, given) = (normalise_title(&self.album), normalise_title(&guess)); + let ratio = if wanted.is_empty() { 0.0 } else { similarity(&given, &wanted) }; + if guess.trim().to_lowercase() == self.album.to_lowercase() || (!given.is_empty() && (given == wanted || ratio >= 0.85)) { + let secs = self.started.elapsed().as_secs(); + let body = format!("{}\n-# Solved in {secs}s at level {}/{MAX_LEVEL}", self.answer_text(), self.level); + self.end(format!("### 🎉 <@{who}> got it!"), body, GREEN); + return Reply::Update; + } + let hint = if ratio >= 0.7 { "🔍 You're **very close**!" } else if ratio >= 0.45 { "🤔 Getting warmer…" } else { "❌ Not quite!" }; + Reply::Private(format!("{hint} Try again.")) + } + _ => Reply::Ignore, + } + } + + fn is_over(&self) -> bool { + self.result.is_some() + } + + fn abandon(&mut self) { + let body = self.answer_text(); + self.end("### ⏱️ Time's up!".into(), body, LOSE); + } +} + +async fn pixel(ctx: Arc) -> Result<()> { + ctx.guild()?; + let api = super::lfm(&ctx.state)?; + // only people with a linked Last.fm can start a round: the album comes from their own profile + let Some(username) = super::username_or_prompt(&ctx, ctx.user_id).await? else { return Ok(()) }; + ctx.defer().await?; + let mut albums = Vec::new(); + for period in ["7day", "1month", "overall"] { // fall back when they were quiet this week + albums = match api.top(&username, "albums", period, 100).await { + Ok(a) => a.into_iter().filter(|a| best_image(&a["image"]).is_some()).collect(), + Err(e) => return super::error(&ctx, &e.to_string()).await, + }; + if albums.len() >= 3 { + break; + } + } + let Some(album) = albums.choose(&mut rand::rng()).cloned() else { return super::error(&ctx, "Couldn't find any albums with cover art in your history.").await }; + let Some(cover) = async { pix::decode(&fetch_image(&ctx.state, &best_image(&album["image"])?).await?) }.await else { return super::error(&ctx, "Couldn't download the album cover — try again.").await }; + let game = Pixel { owner: ctx.user_id.get(), album: album["name"].as_str().unwrap_or("?").into(), artist: album["artist"]["name"].as_str().unwrap_or("?").into(), url: album["url"].as_str().map(str::to_string), cover, level: 1, started: Instant::now(), result: None }; + super::super::games::launch(&ctx, Box::new(game), None).await +} + +// ---- lyrics ----------------------------------------------------------------------------------------------------------------------- + +async fn fetch_lyrics(state: &State, artist: Option<&str>, title: &str) -> Option<(String, String, String)> { + let get = |url: String, q: Vec<(&'static str, String)>| { + let web = state.web.clone(); + async move { + let r = web.get(url).query(&q).timeout(Duration::from_secs(10)).send().await.ok()?; + r.status().is_success().then_some(())?; + r.json::().await.ok() + } + }; + if let Some(a) = artist { + if let Some(d) = get("https://lrclib.net/api/get".into(), vec![("artist_name", a.into()), ("track_name", title.into())]).await { + if let Some(l) = d["plainLyrics"].as_str().filter(|l| !l.is_empty()) { + return Some((l.into(), d["artistName"].as_str().unwrap_or(a).into(), d["trackName"].as_str().unwrap_or(title).into())); + } + if d["instrumental"].as_bool() == Some(true) { + return Some(("🎼 *This track is instrumental.*".into(), a.into(), title.into())); + } + } + } + let query = artist.map_or(title.to_string(), |a| format!("{a} {title}")); + if let Some(Value::Array(items)) = get("https://lrclib.net/api/search".into(), vec![("q", query)]).await { + for item in items { + if let Some(l) = item["plainLyrics"].as_str().filter(|l| !l.is_empty()) { + return Some((l.into(), item["artistName"].as_str().or(artist).unwrap_or("?").into(), item["trackName"].as_str().unwrap_or(title).into())); + } + } + } + if let Some(a) = artist { + let clean = |s: &str| regex::Regex::new(r"\s\(.*\)").unwrap().replace(®ex::Regex::new(r"[^\w\s()-]").unwrap().replace_all(s, ""), "").trim().to_string(); + let url = format!("https://api.lyrics.ovh/v1/{}/{}", urlencoding::encode(&clean(a)), urlencoding::encode(&clean(title))); + if let Some(d) = get(url, vec![]).await { + if let Some(l) = d["lyrics"].as_str().map(str::trim).filter(|l| !l.is_empty()) { + return Some((l.into(), a.into(), title.into())); + } + } + } + None +} + +pub fn paginate(lyrics: &str, size: usize) -> Vec { + let (mut pages, mut current) = (Vec::new(), String::new()); + for stanza in regex::Regex::new(r"\n\s*\n").unwrap().split(lyrics.trim()) { + let stanza: String = stanza.trim().chars().take(size).collect(); + if !current.is_empty() && current.chars().count() + stanza.chars().count() + 2 > size { + pages.push(std::mem::take(&mut current)); + current = stanza; + } else if current.is_empty() { + current = stanza; + } else { + current = format!("{current}\n\n{stanza}"); + } + } + if !current.is_empty() { + pages.push(current); + } + if pages.is_empty() { vec!["*(empty)*".into()] } else { pages } +} + +async fn lyrics(ctx: Arc) -> Result<()> { + let api = super::lfm(&ctx.state)?; + ctx.defer().await?; + let (mut artist, mut title, mut cover): (Option, String, Option) = (None, String::new(), None); + match ctx.args.str("song").map(str::to_string) { + Some(song) if song.contains(" - ") => { + let (a, t) = song.split_once(" - ").unwrap(); + (artist, title) = (Some(a.trim().into()), t.trim().into()); + } + Some(song) => { + title = song.trim().into(); + if let Ok(d) = api.call("track.search", 3600, &[("track", title.clone()), ("limit", "1".into())]).await { + if let Some(m) = as_list(&d["results"]["trackmatches"]["track"]).first() { + artist = m["artist"].as_str().filter(|a| !a.is_empty()).map(str::to_string); + title = m["name"].as_str().filter(|n| !n.is_empty()).unwrap_or(&title).to_string(); + } + } + } + None => { + let Some(username) = super::username_or_prompt(&ctx, ctx.user_id).await? else { return Ok(()) }; + let track = match api.recent(&username, 1).await { + Ok(t) => t.into_iter().next(), + Err(e) => return super::error(&ctx, &e.to_string()).await, + }; + let Some(track) = track else { return super::error(&ctx, "You haven't scrobbled anything yet — give me a song (`Artist - Title`).").await }; + artist = track["artist"]["#text"].as_str().map(str::to_string); + title = track["name"].as_str().unwrap_or("").to_string(); + cover = best_image(&track["image"]); + } + } + let Some((text, artist, title)) = fetch_lyrics(&ctx.state, artist.as_deref(), &title).await else { + let who = artist.map(|a| format!(" by **{}**", escape(&a))).unwrap_or_default(); + return super::error(&ctx, &format!("Couldn't find lyrics for **{}**{who}.", escape(&title))).await; + }; + let pages = paginate(&text, 2400); + let accent = colors::accent(&ctx.state, cover.as_deref(), GREEN).await; + let total = pages.len(); + let cards: Vec = pages.into_iter().enumerate().map(|(i, body)| { + let (title, artist, cover) = (title.clone(), artist.clone(), cover.clone()); + Arc::new(move || { + Card::new(Some(accent)) + .header(&[&format!("### 🎤 {}", escape(&truncate(&title, 90))), &format!("by **{}**", escape(&artist))], cover.as_deref()) + .separator(true, false) + .text(&escape(&body)) + .footer(&format!("Lyrics from LRCLIB / lyrics.ovh{}", if total > 1 { format!(" · Page {}/{total}", i + 1) } else { String::new() })) + }) as pager::Page + }).collect(); + pager::start(&ctx, cards, Duration::from_secs(300)).await +} + +// ---- the Listen button ---------------------------------------------------------------------------------------------------------- + +const LISTEN_SECONDS: u64 = 14 * 60; +const CACHE_SECONDS: u64 = 3600; +const CACHE_FILES: usize = 12; + +struct Song { + path: std::path::PathBuf, + title: String, + duration: Option, + youtube: Option, + bitrate: i64, +} + +fn cache_dir() -> std::path::PathBuf { + paths::data(&["cache", "listen", "x"]).parent().map(std::path::Path::to_path_buf).unwrap_or_default() +} + +fn safe_filename(text: &str) -> String { + let cleaned: String = text.chars().map(|c| if matches!(c, '\\' | '/' | ':' | '*' | '?' | '"' | '<' | '>' | '|') || c.is_control() { ' ' } else { c }).collect(); + let words = cleaned.split_whitespace().collect::>().join(" "); + let t = words.trim_matches(|c| c == ' ' || c == '.'); + if t.is_empty() { "song".into() } else { t.chars().take(90).collect() } +} + +fn prune() { + let Ok(rd) = std::fs::read_dir(cache_dir()) else { return }; + let mut files: Vec<(std::path::PathBuf, std::time::SystemTime)> = rd.flatten().filter(|e| e.path().extension().is_some_and(|x| x == "opus")).filter_map(|e| Some((e.path(), e.metadata().ok()?.modified().ok()?))).collect(); + files.sort_by_key(|f| std::cmp::Reverse(f.1)); + for (i, (p, t)) in files.iter().enumerate() { + if i >= CACHE_FILES || t.elapsed().map_or(false, |a| a.as_secs() > CACHE_SECONDS) { + let _ = std::fs::remove_file(p); + let _ = std::fs::remove_file(p.with_extension("txt")); + } + } +} + +async fn make_song(artist: &str, title: &str, limit: u64) -> Result { + use sha2::{Digest, Sha256}; + use std::fmt::Write as _; + let digest = Sha256::digest(format!("{}\0{}\0{limit}", artist.to_lowercase(), title.to_lowercase())); + let key = digest.iter().take(10).fold(String::new(), |mut s, b| { let _ = write!(s, "{b:02x}"); s }); + let dir = cache_dir(); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let (out, meta) = (dir.join(format!("{key}.opus")), dir.join(format!("{key}.txt"))); + if let (Ok(m), Ok(text)) = (std::fs::metadata(&out), std::fs::read_to_string(&meta)) { + if m.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|a| a.as_secs() < CACHE_SECONDS) { + let mut l = text.lines(); + let (t, d, y, b) = (l.next().unwrap_or(""), l.next().unwrap_or(""), l.next().unwrap_or(""), l.next().unwrap_or("")); + return Ok(Song { path: out, title: t.into(), duration: d.parse().ok(), youtube: (!y.is_empty()).then(|| y.into()), bitrate: b.parse().unwrap_or(96) }); + } + } + let lookup = || async { + let info = super::super::music::ytdl::extract(&format!("ytsearch1:{artist} - {title} audio"), super::super::music::ytdl::Mode::Resolve).await.map_err(|e| format!("YouTube lookup failed: {}", e.chars().take(150).collect::()))?; + info["entries"].as_array().and_then(|a| a.iter().find(|e| !e.is_null() && e["url"].is_string()).cloned()).ok_or_else(|| format!("Couldn't find **{title}** on YouTube.")) + }; + let mut entry = lookup().await?; + let duration = entry["duration"].as_f64().filter(|d| *d > 0.0).map(|d| d as u64); + if duration.is_some_and(|d| d > 30 * 60) { + return Err("That's longer than 30 minutes — too long to send here.".into()); + } + let mut bitrate = 96i64; + if let Some(d) = duration { + bitrate = bitrate.min((limit as f64 * 8.0 * 0.95 / d as f64 / 1000.0) as i64); + if bitrate < 32 { + return Err("That song is too long to fit in one upload here.".into()); + } + } + let encode = |entry: Value| { + let (out, artist, title) = (out.clone(), artist.to_string(), title.to_string()); + async move { + let mut cmd = tokio::process::Command::new("nice"); + cmd.args(["-n", "10"]).arg(super::super::media::download::tool("ffmpeg")).args(["-nostdin", "-hide_banner", "-loglevel", "error", "-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_delay_max", "5"]); + if let Some(h) = entry["http_headers"].as_object() { + cmd.arg("-headers").arg(h.iter().filter_map(|(k, v)| Some(format!("{k}: {}\r\n", v.as_str()?))).collect::()); + } + cmd.arg("-i").arg(entry["url"].as_str().unwrap_or("")).args(["-vn", "-map_metadata", "-1", "-map", "0:a:0", "-c:a", "libopus", "-b:a", &format!("{bitrate}k"), "-vbr", "on", "-application", "audio", "-metadata", &format!("title={title}"), "-metadata", &format!("artist={artist}"), "-f", "ogg", "-y"]).arg(&out); + cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped()).kill_on_drop(true); + let r = tokio::time::timeout(Duration::from_secs(180), cmd.output()).await.map_err(|_| "Encoding took too long — try again in a bit.".to_string())?; + let ok = r.map(|o| o.status.success()).unwrap_or(false) && std::fs::metadata(&out).map(|m| m.len() > 1024).unwrap_or(false); + if ok { Ok(()) } else { let _ = std::fs::remove_file(&out); Err("Couldn't get the audio from YouTube.".to_string()) } + } + }; + if encode(entry.clone()).await.is_err() { + entry = lookup().await?; // stream URLs randomly 403: one more go with a fresh lookup + encode(entry.clone()).await?; + } + if std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0) > limit { + let _ = std::fs::remove_file(&out); + return Err("The audio came out too big to upload here.".into()); + } + let youtube = entry["webpage_url"].as_str().map(str::to_string).or_else(|| entry["id"].as_str().map(|i| format!("https://youtu.be/{i}"))); + let song = Song { path: out, title: entry["title"].as_str().unwrap_or(title).into(), duration, youtube: youtube.clone(), bitrate }; + let _ = std::fs::write(&meta, format!("{}\n{}\n{}\n{}", song.title, duration.map_or(String::new(), |d| d.to_string()), youtube.unwrap_or_default(), bitrate)); + tokio::task::spawn_blocking(prune); + Ok(song) +} + +pub async fn listen_button(state: &Arc, i: &Interaction) { + let Some(InteractionData::MessageComponent(_)) = i.data.as_ref() else { return }; + let mut song_url: Option = None; + if let Some(m) = &i.message { + fn walk(v: &Value, out: &mut Option) { + match v { + Value::Object(o) => { + if let Some(u) = o.get("url").and_then(Value::as_str).filter(|u| u.contains("last.fm/music/")) { + out.get_or_insert_with(|| u.to_string()); + } + o.values().for_each(|x| walk(x, out)); + } + Value::Array(a) => a.iter().for_each(|x| walk(x, out)), + _ => {} + } + } + walk(&serde_json::to_value(&m.components).unwrap_or(Value::Null), &mut song_url); + } + let Some((artist, title)) = song_url.as_deref().and_then(track_from_url) else { + return interact::private_text(state, i, "❌ Can't tell which song this card is about.").await; + }; + interact::defer_private(state, i).await; + let limit = i.guild_id.and_then(|g| state.cache.guild(g).map(|g| u8::from(g.premium_tier()))).map_or(10, |t| match t { 2 => 50, 3 => 100, _ => 10 }) * 1024 * 1024; + let limit = limit.min(10 * 1024 * 1024); + let song = match make_song(&artist, &title, limit).await { + Ok(s) => s, + Err(e) => return interact::followup_text(state, i, &format!("❌ {e}")).await, + }; + let mut buttons: Vec = Vec::new(); + let mk = |label: &str, emoji: &str, url: &str| twilight_model::channel::message::component::Button { id: None, custom_id: None, disabled: false, emoji: Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: emoji.into() }), label: Some(label.into()), style: ButtonStyle::Link, url: Some(url.into()), sku_id: None }; + if let Some(u) = &song_url { + buttons.push(mk("Go to song", "🎵", u)); + } + if let Some(y) = &song.youtube { + buttons.push(mk("YouTube", "▶️", y)); + } + let row = vec![Component::ActionRow(twilight_model::channel::message::component::ActionRow { id: None, components: buttons.into_iter().map(Component::Button).collect() })]; + let gone = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()) + LISTEN_SECONDS; + let length = song.duration.map(|d| format!(" · {}:{:02}", d / 60, d % 60)).unwrap_or_default(); + let text = format!("🎧 **{}** — {}\n-# Opus {} kbit/s{length} · only you can see this · disappears ", escape(&truncate(&title, 80)), escape(&truncate(&artist, 60)), song.bitrate); + let Ok(bytes) = std::fs::read(&song.path) else { return interact::followup_text(state, i, "❌ The audio file went missing.").await }; + let files = [Attachment::from_bytes(crate::ui::file_name(&format!("{}.opus", safe_filename(&format!("{artist} - {title}")))), bytes, 1)]; + // A plain message (not a V2 card): Discord only shows its audio player for normal attachments. + let client = state.http.interaction(state.app_id()); + let no_pings = AllowedMentions::default(); + let mut req = client.create_followup(&i.token).content(&text).attachments(&files).flags(MessageFlags::EPHEMERAL).allowed_mentions(Some(&no_pings)); + if !row_is_empty(&row) { + req = req.components(&row); + } + match req.await { + Ok(r) => { + if let Ok(m) = r.model().await { + let (state, token, id) = (state.clone(), i.token.clone(), m.id); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(LISTEN_SECONDS)).await; + let _ = state.http.interaction(state.app_id()).delete_followup(&token, id).await; + }); + } + } + Err(e) => { + tracing::warn!("couldn't send the Listen file: {e}"); + interact::followup_text(state, i, "❌ Discord refused the upload.").await; + } + } +} + +fn row_is_empty(row: &[Component]) -> bool { + matches!(row.first(), Some(Component::ActionRow(r)) if r.components.is_empty()) +} + +pub fn commands() -> Vec { + vec![ + Command::new("wk", "lastfm", "Who in this server listens to an artist, album or track the most (default: what you're playing).", |c| wk(c).boxed()) + .aliases(&["whoknows"]) + .usage("[artist]") + .opt(Opt::opt("query", "Artist. Empty = what you're playing", OptKind::String)) + .guild_only() + .prefix_only(), + Command::new("wkt", "lastfm", "Who in this server plays a track the most (default: what you're playing).", |c| wkt(c).boxed()) + .usage("[Artist - Track]") + .opt(Opt::opt("query", "Artist - Track", OptKind::String)) + .guild_only() + .prefix_only(), + Command::new("wka", "lastfm", "Who in this server plays an album the most (default: what you're playing).", |c| wka(c).boxed()) + .usage("[Artist - Album]") + .opt(Opt::opt("query", "Artist - Album", OptKind::String)) + .guild_only() + .prefix_only(), + Command::new("chart", "lastfm", "Make a collage of your top albums: `D!chart 4x4 monthly`.", |c| chart(c).boxed()) + .aliases(&["charts"]) + .usage("[size] [period]") + .opt(Opt::opt("args", "A size like 4x4 and a period like monthly", OptKind::String)) + .prefix_only(), + Command::new("px", "lastfm", "Pixel Jumble: guess the album from a pixelated cover.", |c| pixel(c).boxed()).aliases(&["pixel"]).guild_only().prefix_only(), + Command::new("lyrics", "lastfm", "Lyrics for a song (default: what you're playing on Last.fm).", |c| lyrics(c).boxed()) + .usage("[Artist - Title]") + .opt(Opt::opt("song", "Artist - Title (leave empty for your current Last.fm track)", OptKind::String)), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn chart_arguments() { + assert_eq!(parse_chart_args(&[]), Ok((3, 3, "7day"))); + assert_eq!(parse_chart_args(&["4x5", "Monthly"]), Ok((4, 5, "1month"))); + assert_eq!(parse_chart_args(&["yearly", "2x2"]), Ok((2, 2, "12month"))); + assert!(parse_chart_args(&["11x3"]).unwrap_err().contains("10x10")); + assert!(parse_chart_args(&["wat"]).unwrap_err().contains("don't understand")); + } + + #[test] + fn the_chart_is_drawn_with_and_without_covers() { + let cover = pix::encode_png(&RgbaImage::from_pixel(64, 64, Rgba([200, 50, 50, 255]))); + let albums: Vec = (0..4).map(|i| serde_json::json!({"name": format!("Album {i} with a long 日本語 name"), "artist": {"name": "Some Artist"}})).collect(); + let (png, name) = compose_chart(&[Some(cover.clone()), None, Some(cover), None], &albums, 2, 2); + assert_eq!(name, "chart.png"); + let img = image::load_from_memory(&png).unwrap(); + assert_eq!((img.width(), img.height()), (1080, 1080)); + let (jpg, name) = compose_chart(&[], &albums, 4, 4); + assert_eq!((name, &jpg[..2]), ("chart.jpg", &[0xff, 0xd8][..])); + } + + #[test] + fn similarity_matches_difflib() { + assert!((similarity("abcd", "abcd") - 1.0).abs() < 1e-9); + assert!((similarity("abcd", "bcde") - 0.75).abs() < 1e-9); + assert!((similarity("abc", "xyz")).abs() < 1e-9); + assert!(similarity("abbey road", "abbey rd") > 0.85); + } + + #[test] + fn lyrics_split_on_stanzas() { + let text = format!("{}\n\n{}\n\n{}", "a".repeat(1500), "b".repeat(1500), "c".repeat(100)); + let pages = paginate(&text, 2400); + assert_eq!(pages.len(), 2); + assert!(pages[1].contains('b') && pages[1].contains('c')); + assert_eq!(paginate(" ", 100), vec!["*(empty)*"]); + } + + #[test] + fn pixelation_gets_clearer() { + let cover = RgbaImage::from_fn(300, 300, |x, y| Rgba([(x % 256) as u8, (y % 256) as u8, 90, 255])); + let blocky = image::load_from_memory(&pixelate(&cover, 1)).unwrap().to_rgba8(); + let clear = image::load_from_memory(&pixelate(&cover, 5)).unwrap().to_rgba8(); + assert_eq!((blocky.width(), clear.height()), (600, 600)); + let distinct = |i: &RgbaImage| i.pixels().step_by(97).collect::>().len(); + assert!(distinct(&clear) > distinct(&blocky)); + } + + #[test] + fn file_names_are_safe() { + assert_eq!(safe_filename("AC/DC: Back In Black?"), "AC DC Back In Black"); + assert_eq!(safe_filename("???"), "song"); + } + + #[test] + fn pixel_listens_to_everyone_in_chat() { + let mut g = Pixel { owner: 1, album: "Abbey Road (Remastered)".into(), artist: "The Beatles".into(), url: None, cover: RgbaImage::new(30, 30), level: 1, started: Instant::now(), result: None }; + assert!(!g.chat(9_200_000_001, "revolver")); + assert!(g.result.is_none()); + assert!(g.chat(9_200_000_001, "abbey road")); + assert!(g.is_over() && g.result.as_ref().unwrap().0.contains("9200000001")); + assert!(!g.chat(9_200_000_002, "abbey road"), "already solved"); + } +} + +#[cfg(test)] +mod listen_request_tests { + use super::*; + + /// The Listen follow-up must pass twilight's own checks (they ran client-side and refused it live). + #[tokio::test] + async fn the_listen_followup_is_valid() { + let _ = rustls::crypto::ring::default_provider().install_default(); + let client = twilight_http::Client::new("x".into()); + let api = client.interaction(twilight_model::id::Id::new(1)); + let btn = |l: &str, u: &str| Component::Button(twilight_model::channel::message::component::Button { id: None, custom_id: None, disabled: false, emoji: Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "🎵".into() }), label: Some(l.into()), style: ButtonStyle::Link, url: Some(u.into()), sku_id: None }); + let row = vec![Component::ActionRow(twilight_model::channel::message::component::ActionRow { id: None, components: vec![btn("Go to song", "https://www.last.fm/music/A/_/B"), btn("YouTube", "https://www.youtube.com/watch?v=abc")] })]; + let files = [Attachment::from_bytes(crate::ui::file_name(&format!("{}.opus", safe_filename("Artist - Title"))), vec![1, 2, 3], 1)]; + let no_pings = AllowedMentions::default(); + let req = api.create_followup("token").content("hello").attachments(&files).flags(MessageFlags::EPHEMERAL).allowed_mentions(Some(&no_pings)).components(&row); + let err = req.await.err().map(|e| format!("{e:?}")); + assert!(err.as_deref().is_none_or(|e| !e.contains("Validation")), "{err:?}"); + } +} diff --git a/src/commands/lastfm/mod.rs b/src/commands/lastfm/mod.rs new file mode 100644 index 0000000..c2a8749 --- /dev/null +++ b/src/commands/lastfm/mod.rs @@ -0,0 +1,318 @@ +//! Last.fm: now playing, recent & top stats, WhoKnows, album charts, Pixel Jumble and lyrics. +//! +//! Prefix: `D!fm [top|recent|profile] [@user]` · `D!ta` / `D!tab` / `D!tt` · `D!recent` · `D!fmprofile` · `D!fmset ` +//! `D!wk` / `D!wkt` / `D!wka` · `D!chart [size] [period]` · `D!px` · `D!lyrics` +//! Slash: `/fm [user] [mode] [kind] [period]` · `/whoknows` · `/chart` · `/pixel` · `/lyrics` +//! +//! Every card is public; only the person who ran the command can flip pages or switch views. The now-playing card has +//! "Go to song" (the track on Last.fm) and "Listen to song" (anyone can press it: they get the song from YouTube as a +//! 96 kbit/s Opus file in a message only they can see, which deletes itself after ~14 minutes). +mod api; +mod extras; +mod views; + +use self::api::{as_list, best_image, fm_url, Lfm}; +use super::info::display_name_of; +use crate::bail_user; +use crate::cmd::{Command, Ctx, Opt, OptKind, Origin}; +use crate::converters::find_member; +use crate::interact; +use crate::state::State; +use crate::ui::{button, escape, truncate, Card, GREEN, RED}; +use anyhow::Result; +use futures::FutureExt; +use serde_json::Value; +use std::sync::Arc; +use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_model::channel::message::component::{ButtonStyle, Component}; +use twilight_model::id::marker::UserMarker; +use twilight_model::id::Id; + +pub const PLAYING_EMOJI: &str = ""; +pub const PERIODS: [(&str, &str); 6] = [("overall", "All time"), ("7day", "Weekly"), ("1month", "Monthly"), ("3month", "Quarterly"), ("6month", "Half-year"), ("12month", "Yearly")]; + +pub fn period_label(key: &str) -> &'static str { + PERIODS.iter().find(|p| p.0 == key).map_or("All time", |p| p.1) +} + +pub fn period_of(word: &str) -> Option<&'static str> { + let w = word.to_lowercase(); + if let Some(p) = PERIODS.iter().find(|p| p.0 == w) { + return Some(p.0); + } + Some(match w.as_str() { + "alltime" | "all" => "overall", + "7d" | "week" | "weekly" => "7day", + "1m" | "month" | "monthly" => "1month", + "3m" | "quarterly" => "3month", + "6m" => "6month", + "12m" | "year" | "yearly" => "12month", + _ => return None, + }) +} + +pub fn kind_of(word: &str) -> Option<&'static str> { + Some(match word.to_lowercase().as_str() { + "artists" | "artist" | "ar" | "a" => "artists", + "albums" | "album" | "al" | "ab" => "albums", + "tracks" | "track" | "songs" | "song" | "t" => "tracks", + _ => return None, + }) +} + +pub fn link(text: &str, url: Option<&str>) -> String { + let t = escape(text).replace('[', "(").replace(']', ")"); + match url { + Some(u) if !u.is_empty() => format!("[{t}](<{u}>)"), + _ => t, + } +} + +pub fn normalise_title(title: &str) -> String { + let lower = title.to_lowercase(); + let no_brackets = regex::Regex::new(r"[\(\[][^)\]]*[\)\]]").unwrap().replace_all(&lower, "").to_string(); + let no_suffix = regex::Regex::new(r"\s+-\s+(single|ep|remaster.*|deluxe.*)$").unwrap().replace(&no_brackets, "").to_string(); + regex::Regex::new(r"[^\w\s]").unwrap().replace_all(&no_suffix, "").trim().to_string() +} + +fn lfm(ctx_state: &State) -> Result, crate::error::UserError> { + Lfm::get(ctx_state).ok_or_else(|| crate::error::UserError::new("Last.fm isn't set up on this bot (LASTFM_API_KEY is missing).")) +} + +async fn error(ctx: &Ctx, text: &str) -> Result<()> { + ctx.reply_private(Card::new(Some(RED)).text(&format!("❌ {text}")).build()).await +} + +/// The linked Last.fm name (for the dashboard). +pub fn linked_name(user: u64) -> Option { + api::linked(user) +} + +pub fn unlink(user: u64) { + api::set_link(user, None); +} + +fn link_prompt(who: Option) -> Component { + let text = match who { + None => "You haven't linked a Last.fm account yet.".to_string(), + Some(u) => format!("<@{u}> hasn't linked a Last.fm account yet."), + }; + let mut b = button("fm:link", "Link Last.fm", ButtonStyle::Success); + b.emoji = Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "🔗".into() }); + Card::new(Some(RED)).text(&format!("### ❌ Last.fm not linked\n{text}")).row(vec![b]).build() +} + +/// The Last.fm name for a person, or None after showing a "link your account" prompt. +async fn username_or_prompt(ctx: &Ctx, user: Id) -> Result> { + if let Some(n) = api::linked(user.get()) { + return Ok(Some(n)); + } + let own = user == ctx.user_id; + let card = link_prompt(if own { None } else { Some(user.get()) }); + if own && ctx.is_slash() { ctx.reply_private(card).await? } else { ctx.reply(card).await? } + Ok(None) +} + +pub(crate) async fn link_account(state: &State, user: u64, username: &str) -> String { + let Some(api) = Lfm::get(state) else { return "❌ Last.fm isn't set up on this bot.".into() }; + match api.user_info(username).await { + Err(api::Error::NotFound(_)) => format!("❌ There's no Last.fm user called **{}**.", escape(username)), + Err(e) => format!("❌ {e}"), + Ok(info) => { + let name = info["name"].as_str().unwrap_or(username).to_string(); + api::set_link(user, Some(&name)); + format!("✅ Linked to **{}** ({} scrobbles).", escape(&name), crate::converters::thousands(info["playcount"].as_str().and_then(|p| p.parse().ok()).unwrap_or(0))) + } + } +} + +async fn who_is(ctx: &Ctx, text: &str) -> Result> { + if text.trim().is_empty() { + return Ok(ctx.reply_to.unwrap_or(ctx.user_id)); + } + if let Some(u) = ctx.guild_id.and_then(|g| find_member(&ctx.state.cache, g, text.trim())) { + return Ok(u); + } + match crate::converters::parse_id(text.trim()).and_then(Id::new_checked) { + Some(u) => Ok(u), + None => bail_user!("I couldn't find `{}`.", escape(&truncate(text, 50))), + } +} + +// ---- /fm and friends ------------------------------------------------------------------------------------------- + +async fn show(ctx: &Arc, mode: &str, user: Id, kind: &str, period: &str) -> Result<()> { + let state = &ctx.state; + let api = lfm(state)?; + let Some(username) = username_or_prompt(ctx, user).await? else { return Ok(()) }; + ctx.defer().await?; + let name = display_name_of(state, ctx.guild_id, user).await; + let avatar = super::media::avatar(state, user, 256).await; + let base = views::Base { state: state.clone(), api: api.clone(), owner: ctx.user_id.get(), user: user.get(), name, avatar, username: username.clone() }; + if mode == "nowplaying" { + return match views::now_playing(&base).await { + Ok(card) => ctx.reply(card).await, + Err(e) => error(ctx, &e.to_string()).await, + }; + } + let game = match mode { + "top" => views::Top::load(base, kind.to_string(), period.to_string()).await.map(|g| Box::new(g) as Box), + "recent" => views::Recent::load(base).await.map(|g| Box::new(g) as Box), + _ => views::Profile::load(base).await.map(|g| Box::new(g) as Box), + }; + match game { + Ok(g) => super::games::launch(ctx, g, None).await, + Err(e) => error(ctx, &e.to_string()).await, + } +} + +async fn prefix_mode(ctx: &Arc, mode: &str, args: &str) -> Result<()> { + let (mut kind, mut period, mut rest) = ("artists", "overall", Vec::new()); + for word in args.split_whitespace() { + if mode == "top" { + if let Some(k) = kind_of(word) { + kind = k; + continue; + } + if let Some(p) = period_of(word) { + period = p; + continue; + } + } + rest.push(word); + } + let user = who_is(ctx, &rest.join(" ")).await?; + show(ctx, mode, user, kind, period).await +} + +async fn fm(ctx: Arc) -> Result<()> { + if ctx.is_slash() { + let mode = ctx.args.str("mode").unwrap_or("nowplaying").to_string(); + if mode == "link" { + return open_link_modal(&ctx).await; + } + let user = ctx.args.user("user").unwrap_or(ctx.user_id); + return show(&ctx, &mode, user, ctx.args.str("kind").unwrap_or("artists"), ctx.args.str("period").unwrap_or("overall")).await; + } + let args = ctx.args.str("args").unwrap_or("").to_string(); + let (first, rest) = args.split_once(char::is_whitespace).map_or((args.as_str(), ""), |(a, b)| (a, b)); + let mode = match first.to_lowercase().as_str() { + "top" | "t" => Some("top"), + "recent" | "rc" | "r" => Some("recent"), + "profile" | "p" | "me" => Some("profile"), + "np" => Some("nowplaying"), + _ => None, + }; + match mode { + Some(m) => prefix_mode(&ctx, m, rest).await, + None => prefix_mode(&ctx, "nowplaying", &args).await, + } +} + +async fn shortcut(ctx: Arc) -> Result<()> { + let args = ctx.args.str("args").unwrap_or("").to_string(); + match ctx.invoked { + "ta" => prefix_mode(&ctx, "top", &format!("artists {args}")).await, + "tab" => prefix_mode(&ctx, "top", &format!("albums {args}")).await, + "tt" => prefix_mode(&ctx, "top", &format!("tracks {args}")).await, + "recent" => prefix_mode(&ctx, "recent", &args).await, + _ => prefix_mode(&ctx, "profile", &args).await, + } +} + +fn link_form() -> Vec { + vec![interact::text_field("username", "Last.fm username", None, "", 30, false, Some("e.g. rj"))] +} + +async fn open_link_modal(ctx: &Ctx) -> Result<()> { + let Origin::Interaction { id, token, responded, .. } = &ctx.origin else { bail_user!("Use `/fm mode:link`.") }; + responded.store(true, std::sync::atomic::Ordering::SeqCst); + use twilight_model::http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType}; + let data = InteractionResponseData { custom_id: Some("fm:linkform".into()), title: Some("Link your Last.fm".into()), components: Some(link_form()), ..Default::default() }; + ctx.state.http.interaction(ctx.state.app_id()).create_response(*id, token, &InteractionResponse { kind: InteractionResponseType::Modal, data: Some(data) }).await?; + Ok(()) +} + +async fn fmset(ctx: Arc) -> Result<()> { + let Some(name) = ctx.args.str("username").map(str::to_string) else { + if let Some(current) = api::linked(ctx.user_id.get()) { + return ctx.say(&format!("Linked to **{}**. Use `{}fmset ` to change it.", escape(¤t), ctx.state.prefix(ctx.guild_id))).await; + } + return ctx.reply(link_prompt(None)).await; + }; + ctx.defer().await?; + let text = link_account(&ctx.state, ctx.user_id.get(), &name).await; + ctx.say(&text).await +} + +pub async fn on_component(state: &Arc, i: &Interaction) { + match i.data.as_ref() { + Some(InteractionData::MessageComponent(d)) if d.custom_id == "fm:link" => interact::modal(state, i, "fm:linkform", "Link your Last.fm", link_form()).await, + Some(InteractionData::MessageComponent(d)) if d.custom_id == "fm:listen" => extras::listen_button(state, i).await, + Some(InteractionData::ModalSubmit(d)) if d.custom_id == "fm:linkform" => { + let Some(user) = i.author() else { return }; + let name = interact::modal_values(d).get("username").map(|s| s.trim().to_string()).unwrap_or_default(); + if name.len() < 2 { + return interact::private_text(state, i, "Type your Last.fm username.").await; + } + interact::defer_private(state, i).await; + let text = link_account(state, user.id.get(), &name).await; + interact::followup_text(state, i, &text).await; + } + _ => {} + } +} + +// ---- registration ----------------------------------------------------------------------------------------------------- + +pub fn commands() -> Vec { + let periods: &'static [&'static str] = Box::leak(PERIODS.iter().map(|p| p.0).collect::>().into_boxed_slice()); + let modes: &'static [&'static str] = &["nowplaying", "top", "recent", "profile", "link"]; + let who = |c: Command| c.opt(Opt::opt("args", "A user, and for top lists a kind and period", OptKind::String).prefix_only()); + vec![ + Command::new("fm", "lastfm", "What you (or someone) are listening to. `fm top albums monthly`, `fm recent`, `fm profile @friend` for stats — reply to someone with `fm` to see theirs.", |c| fm(c).boxed()) + .usage("[top|recent|profile] [artists|albums|tracks] [weekly|monthly|…] [@user]") + .opt(Opt::opt("args", "What to show and for whom", OptKind::String).prefix_only()) + .opt(Opt::opt("user", "Whose profile (defaults to you)", OptKind::User).slash_only()) + .opt(Opt::opt("mode", "What to show — or 'link' to connect your account", OptKind::String).choices(modes).slash_only()) + .opt(Opt::opt("kind", "Top list: artists, albums or tracks", OptKind::String).choices(&["artists", "albums", "tracks"]).slash_only()) + .opt(Opt::opt("period", "Top list: time period", OptKind::String).choices(periods).slash_only()), + who(Command::new("ta", "lastfm", "Your top Last.fm artists.", |c| shortcut(c).boxed()).aliases(&["topartists"]).usage("[period] [@user]").prefix_only()), + who(Command::new("tab", "lastfm", "Your top Last.fm albums.", |c| shortcut(c).boxed()).aliases(&["topalbums"]).usage("[period] [@user]").prefix_only()), + who(Command::new("tt", "lastfm", "Your top Last.fm tracks.", |c| shortcut(c).boxed()).aliases(&["toptracks"]).usage("[period] [@user]").prefix_only()), + who(Command::new("recent", "lastfm", "Your last 50 Last.fm scrobbles.", |c| shortcut(c).boxed()).aliases(&["rc", "recenttracks"]).usage("[@user]").prefix_only()), + who(Command::new("fmprofile", "lastfm", "Last.fm profile: scrobbles, library size, daily average and this week's favourites.", |c| shortcut(c).boxed()).aliases(&["fmp", "fmstats"]).usage("[@user]").prefix_only()), + Command::new("fmset", "lastfm", "Link your Last.fm account: `D!fmset `.", |c| fmset(c).boxed()) + .aliases(&["fmlogin", "setfm"]) + .usage("") + .opt(Opt::opt("username", "Your Last.fm username", OptKind::String)) + .prefix_only(), + ] + .into_iter() + .chain(extras::commands()) + .collect() +} + +pub use self::api::as_list as _as_list; +#[allow(dead_code)] +fn _unused(_: &Value) { + let _ = (as_list, best_image, fm_url, GREEN); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn words_map_to_periods_and_kinds() { + assert_eq!((period_of("weekly"), period_of("12m"), period_of("alltime"), period_of("nope")), (Some("7day"), Some("12month"), Some("overall"), None)); + assert_eq!((kind_of("songs"), kind_of("al"), kind_of("x")), (Some("tracks"), Some("albums"), None)); + } + + #[test] + fn album_names_are_compared_without_noise() { + assert_eq!(normalise_title("Abbey Road (Remastered 2019)"), "abbey road"); + assert_eq!(normalise_title("Thriller - Deluxe Edition"), "thriller"); + assert_eq!(normalise_title("OK Computer [Special]"), "ok computer"); + } +} diff --git a/src/commands/lastfm/views.rs b/src/commands/lastfm/views.rs new file mode 100644 index 0000000..7770644 --- /dev/null +++ b/src/commands/lastfm/views.rs @@ -0,0 +1,383 @@ +//! The Last.fm cards: now playing, top lists, recent tracks and profile (paged, switchable, owner-only). +use super::super::games::{btn, Game, Rendered, Reply}; +use super::api::{as_list, best_image, fm_url, track_from_url, Error, Lfm}; +use super::{link, period_label, PERIODS, PLAYING_EMOJI}; +use crate::colors; +use crate::converters::thousands; +use crate::state::State; +use crate::ui::{button, escape, select_menu, select_option, truncate, Card, GREEN, RED}; +use futures::FutureExt; +use serde_json::Value; +use std::collections::HashMap; +use std::sync::Arc; +use std::time::Duration; +use twilight_model::channel::message::component::{ButtonStyle, Component}; + +const KINDS: [(&str, &str); 3] = [("artists", "🎤"), ("albums", "💿"), ("tracks", "🎵")]; +const PER_PAGE: usize = 10; + +/// Who the card is about and who may press its buttons. +#[derive(Clone)] +pub struct Base { + pub state: Arc, + pub api: Arc, + pub owner: u64, + pub user: u64, + pub name: String, + pub avatar: String, + pub username: String, +} + +fn bar(value: u64, top: u64) -> String { + let filled = (((value as f64 / top.max(1) as f64) * 8.0).round() as usize).clamp(1, 8); + format!("{}{}", "▰".repeat(filled), "▱".repeat(8 - filled)) +} + +fn num(v: &Value, key: &str) -> u64 { + v[key].as_str().and_then(|s| s.parse().ok()).or_else(|| v[key].as_u64()).unwrap_or(0) +} + +fn owner_only(owner: u64, who: u64) -> Result<(), String> { + if who == owner { Ok(()) } else { Err("These buttons belong to whoever ran the command — use `/fm` or `D!fm` for your own.".into()) } +} + +// ---- now playing ---------------------------------------------------------------------------------------------------- + +pub async fn now_playing(b: &Base) -> Result { + let (tracks, info) = tokio::join!(b.api.recent(&b.username, 2), b.api.user_info(&b.username)); + let (tracks, info) = (tracks?, info?); + let Some(track) = tracks.first() else { + return Ok(Card::new(Some(RED)).text(&format!("### No scrobbles yet\n{} hasn't scrobbled anything.", escape(&b.username))).build()); + }; + let artist = track["artist"]["#text"].as_str().unwrap_or("Unknown artist"); + let title = track["name"].as_str().unwrap_or("Unknown track"); + let album = track["album"]["#text"].as_str().filter(|a| !a.is_empty()); + let playing = track["@attr"]["nowplaying"].as_str() == Some("true"); + let plays = b.api.entity("track", title, Some(artist), Some(&b.username)).await.ok().map(|d| num(&d, "userplaycount")).filter(|p| *p > 0); + let status = if playing { + format!("-# {PLAYING_EMOJI} Now playing · {}", escape(&b.name)) + } else { + match track["date"]["uts"].as_str() { + Some(uts) => format!("-# ⏮️ Last played · {}", escape(&b.name)), + None => format!("-# ⏮️ Last played · {}", escape(&b.name)), + } + }; + let mut body = format!("### {}\n**{}**", link(&truncate(title, 90), track["url"].as_str()), link(artist, Some(&fm_url(&[artist])))); + if let Some(a) = album { + body.push_str(&format!(" · *{}*", escape(&truncate(a, 80)))); + } + let cover = best_image(&track["image"]); + let accent = colors::accent(&b.state, cover.as_deref(), GREEN).await; + let mut footer = vec![format!("[{}]()", escape(&b.username), b.username), format!("{} scrobbles", thousands(num(&info, "playcount")))]; + if let Some(p) = plays { + footer.push(format!("{} play{} of this track", thousands(p), if p != 1 { "s" } else { "" })); + } + let mut card = Card::new(Some(accent)).header(&[&status, &body], cover.as_deref()).footer(&footer.join(" · ")); + if let (Some(prev), true) = (tracks.get(1), playing) { + card = card.footer(&format!("Previous: {} — {}", escape(&truncate(prev["name"].as_str().unwrap_or("?"), 60)), escape(prev["artist"]["#text"].as_str().unwrap_or("?")))); + } + if let Some(url) = track["url"].as_str().filter(|u| track_from_url(u).is_some()) { + let go = twilight_model::channel::message::component::Button { id: None, custom_id: None, disabled: false, emoji: Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "🎵".into() }), label: Some("Go to song".into()), style: ButtonStyle::Link, url: Some(url.into()), sku_id: None }; + let mut listen = button("fm:listen", "Listen to song", ButtonStyle::Primary); + listen.emoji = Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "🎧".into() }); + card = card.row(vec![go, listen]); + } + Ok(card.build()) +} + +// ---- shared card pieces ------------------------------------------------------------------------------------------------- + +fn nav(t: u32, page: usize, pages: usize) -> Vec { + if pages <= 1 { + return vec![]; + } + vec![btn(t, "prev", "", "◀️", ButtonStyle::Secondary, page == 0), btn(t, "next", "", "▶️", ButtonStyle::Secondary, page + 1 >= pages)] +} + +fn go(t: u32, action: &str, label: &str, emoji: &str) -> twilight_model::channel::message::component::Button { + btn(t, action, label, emoji, ButtonStyle::Secondary, false) +} + +fn defer_load(f: F) -> Reply +where + F: std::future::Future, Error>> + Send + 'static, +{ + Reply::Defer(async move { + match f.await { + Ok(g) => Reply::Replace(g), + Err(e) => Reply::Private(format!("❌ {e}")), + } + }.boxed()) +} + +// ---- top lists --------------------------------------------------------------------------------------------------------------- + +pub struct Top { + b: Base, + kind: String, + period: String, + items: Vec, + total: u64, + thumbnail: Option, + accent: u32, + page: usize, + over: bool, +} + +impl Top { + pub async fn load(b: Base, kind: String, period: String) -> Result { + let raw = b.api.top_raw(&b.username, &kind, &period, 50).await?; + let block = &raw[format!("top{kind}")]; + let items = as_list(&block[&kind[..kind.len() - 1]]); + let total = block["@attr"]["total"].as_str().and_then(|t| t.parse().ok()).unwrap_or(items.len() as u64); + let thumbnail = match items.first() { + Some(first) => super::extras::cover_for(&b.state, &kind, first).await, + None => None, + }; + let accent = colors::accent(&b.state, thumbnail.as_deref().or(Some(&b.avatar)), GREEN).await; + Ok(Self { b, kind, period, items, total, thumbnail, accent, page: 0, over: false }) + } + + fn pages(&self) -> usize { + self.items.len().div_ceil(PER_PAGE).max(1) + } +} + +impl Game for Top { + fn players(&self) -> Vec { + vec![self.b.owner] + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(600) + } + + fn allowed(&self, who: u64, _: &str) -> Result<(), String> { + owner_only(self.b.owner, who) + } + + fn render(&self, t: u32) -> Rendered { + let top = self.items.first().map_or(1, |i| num(i, "playcount")); + let lines: Vec = self.items.iter().enumerate().skip(self.page * PER_PAGE).take(PER_PAGE).map(|(idx, item)| { + let (i, name, plays) = (idx + 1, item["name"].as_str().unwrap_or("?"), num(item, "playcount")); + let entry = if self.kind == "artists" { + format!("**{}**", link(&truncate(name, 60), Some(item["url"].as_str().map(str::to_string).unwrap_or_else(|| fm_url(&[name])).as_str()))) + } else { + format!("**{}** — {}", link(&truncate(name, 55), item["url"].as_str()), escape(&truncate(item["artist"]["name"].as_str().unwrap_or("?"), 40))) + }; + let medal = match i { 1 => "🥇".to_string(), 2 => "🥈".to_string(), 3 => "🥉".to_string(), n => format!("`{n:>2}`") }; + format!("{medal} {entry}\n-# `{}` {} plays", bar(plays, top), thousands(plays)) + }).collect(); + let icon = KINDS.iter().find(|k| k.0 == self.kind).map_or("🎤", |k| k.1); + let mut footer = if self.total > 0 { format!("{} {} in this period", thousands(self.total), self.kind) } else { String::new() }; + if self.pages() > 1 { + footer.push_str(&format!("{}page {}/{}", if footer.is_empty() { "" } else { " · " }, self.page + 1, self.pages())); + } + let mut card = Card::new(Some(self.accent)) + .header(&[&format!("### {icon} Top {} · {}", self.kind, escape(&self.b.username)), &format!("-# {} · <@{}>", period_label(&self.period), self.b.user)], Some(self.thumbnail.as_deref().unwrap_or(&self.b.avatar))) + .separator(true, false) + .text(&if lines.is_empty() { format!("*No {} scrobbled in this period.*", self.kind) } else { lines.join("\n") }); + if !footer.is_empty() { + card = card.footer(&footer); + } + let options = PERIODS.iter().map(|(k, l)| { let mut o = select_option(l, k, "🕒", "", *k == self.period); o.emoji = None; o }).collect(); + let mut buttons: Vec<_> = KINDS.iter().map(|(k, e)| btn(t, &format!("kind_{k}"), &(k[..1].to_uppercase() + &k[1..]), e, if *k == self.kind { ButtonStyle::Primary } else { ButtonStyle::Secondary }, false)).collect(); + buttons.extend(nav(t, self.page, self.pages())); + card.select(select_menu(&format!("gm:{t}:period"), "Time period", options)).row(buttons).into() + } + + fn click(&mut self, _: u64, action: &str, values: &[String], _: &HashMap) -> Reply { + match action { + "prev" => self.page = self.page.saturating_sub(1), + "next" => self.page = (self.page + 1).min(self.pages() - 1), + "period" => { + let Some(p) = values.first().cloned() else { return Reply::Ignore }; + let (b, kind) = (self.b.clone(), self.kind.clone()); + return defer_load(async move { Ok(Box::new(Top::load(b, kind, p).await?) as Box) }); + } + a if a.starts_with("kind_") => { + let (b, period, kind) = (self.b.clone(), self.period.clone(), a[5..].to_string()); + return defer_load(async move { Ok(Box::new(Top::load(b, kind, period).await?) as Box) }); + } + _ => return Reply::Ignore, + } + Reply::Update + } + + fn is_over(&self) -> bool { + self.over + } + + fn abandon(&mut self) { + self.over = true; + } +} + +// ---- recent tracks --------------------------------------------------------------------------------------------------------------- + +pub struct Recent { + b: Base, + tracks: Vec, + scrobbles: u64, + accent: u32, + page: usize, + over: bool, +} + +impl Recent { + pub async fn load(b: Base) -> Result { + let (tracks, info) = tokio::join!(b.api.recent(&b.username, 50), b.api.user_info(&b.username)); + let tracks: Vec = tracks?.into_iter().take(50).collect(); + let cover = tracks.first().and_then(|t| best_image(&t["image"])); + let accent = colors::accent(&b.state, cover.as_deref().or(Some(&b.avatar)), GREEN).await; + Ok(Self { scrobbles: num(&info?, "playcount"), b, tracks, accent, page: 0, over: false }) + } + + fn pages(&self) -> usize { + self.tracks.len().div_ceil(PER_PAGE).max(1) + } +} + +impl Game for Recent { + fn players(&self) -> Vec { + vec![self.b.owner] + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(600) + } + + fn allowed(&self, who: u64, _: &str) -> Result<(), String> { + owner_only(self.b.owner, who) + } + + fn render(&self, t: u32) -> Rendered { + let lines: Vec = self.tracks.iter().skip(self.page * PER_PAGE).take(PER_PAGE).map(|track| { + let artist = track["artist"]["#text"].as_str().unwrap_or("?"); + let entry = format!("**{}** — {}", link(&truncate(track["name"].as_str().unwrap_or("?"), 60), track["url"].as_str()), escape(&truncate(artist, 40))); + if track["@attr"]["nowplaying"].as_str() == Some("true") { + format!("{PLAYING_EMOJI} {entry}\n-# playing now") + } else { + match track["date"]["uts"].as_str() { + Some(uts) => format!("• {entry}\n-# "), + None => format!("• {entry}"), + } + } + }).collect(); + let cover = self.tracks.first().and_then(|t| best_image(&t["image"])); + let mut buttons = nav(t, self.page, self.pages()); + buttons.push(go(t, "top", "Top", "🏆")); + buttons.push(go(t, "profile", "Profile", "👤")); + Card::new(Some(self.accent)) + .header(&[&format!("### 🎧 Recent tracks · {}", escape(&self.b.username)), &format!("-# <@{}>", self.b.user)], Some(cover.as_deref().unwrap_or(&self.b.avatar))) + .separator(true, false) + .text(&if lines.is_empty() { "*No scrobbles yet.*".to_string() } else { lines.join("\n") }) + .footer(&format!("{} scrobbles in total{}", thousands(self.scrobbles), if self.pages() > 1 { format!(" · page {}/{}", self.page + 1, self.pages()) } else { String::new() })) + .row(buttons) + .into() + } + + fn click(&mut self, _: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + match action { + "prev" => self.page = self.page.saturating_sub(1), + "next" => self.page = (self.page + 1).min(self.pages() - 1), + "top" => { + let b = self.b.clone(); + return defer_load(async move { Ok(Box::new(Top::load(b, "artists".into(), "overall".into()).await?) as Box) }); + } + "profile" => { + let b = self.b.clone(); + return defer_load(async move { Ok(Box::new(Profile::load(b).await?) as Box) }); + } + _ => return Reply::Ignore, + } + Reply::Update + } + + fn is_over(&self) -> bool { + self.over + } + + fn abandon(&mut self) { + self.over = true; + } +} + +// ---- profile ------------------------------------------------------------------------------------------------------------------------ + +pub struct Profile { + b: Base, + info: Value, + week: Vec<(&'static str, &'static str, Option)>, + thumbnail: Option, + accent: u32, + over: bool, +} + +impl Profile { + pub async fn load(b: Base) -> Result { + let (info, artists, albums, tracks) = tokio::join!(b.api.user_info(&b.username), b.api.top(&b.username, "artists", "7day", 1), b.api.top(&b.username, "albums", "7day", 1), b.api.top(&b.username, "tracks", "7day", 1)); + let info = info?; + let thumbnail = best_image(&info["image"]); + let accent = colors::accent(&b.state, thumbnail.as_deref().or(Some(&b.avatar)), GREEN).await; + let week = vec![("artists", "🎤", artists?.into_iter().next()), ("albums", "💿", albums?.into_iter().next()), ("tracks", "🎵", tracks?.into_iter().next())]; + Ok(Self { b, info, week, thumbnail, accent, over: false }) + } +} + +impl Game for Profile { + fn players(&self) -> Vec { + vec![self.b.owner] + } + + fn idle_timeout(&self) -> Duration { + Duration::from_secs(600) + } + + fn allowed(&self, who: u64, _: &str) -> Result<(), String> { + owner_only(self.b.owner, who) + } + + fn render(&self, t: u32) -> Rendered { + let info = &self.info; + let scrobbles = num(info, "playcount"); + let since = num(&info["registered"], "unixtime").max(num(&info["registered"], "#text")); + let days = if since > 0 { ((std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()) as f64 - since as f64) / 86400.0).max(1.0) } else { 1.0 }; + let sub: Vec = [info["realname"].as_str().unwrap_or("").trim(), info["country"].as_str().unwrap_or("")].iter().filter(|x| !x.is_empty() && **x != "None").map(|x| escape(x)).collect(); + let mut stats = vec![format!("**{}** scrobbles", thousands(scrobbles)), format!("**{}** artists · **{}** albums · **{}** tracks", thousands(num(info, "artist_count")), thousands(num(info, "album_count")), thousands(num(info, "track_count")))]; + if since > 0 { + stats.push(format!("Scrobbling since · about **{}** a day", thousands((scrobbles as f64 / days).round() as u64))); + } + let week: Vec = self.week.iter().filter_map(|(kind, icon, item)| { + let item = item.as_ref()?; + let extra = if *kind != "artists" { format!(" — {}", escape(item["artist"]["name"].as_str().unwrap_or(""))) } else { String::new() }; + Some(format!("{icon} **{}**{extra} · {} plays", link(&truncate(item["name"].as_str().unwrap_or("?"), 50), item["url"].as_str()), thousands(num(item, "playcount")))) + }).collect(); + let profile_url = info["url"].as_str().map(str::to_string).unwrap_or_else(|| format!("https://www.last.fm/user/{}", self.b.username)); + let site = twilight_model::channel::message::component::Button { id: None, custom_id: None, disabled: false, emoji: None, label: Some("Last.fm".into()), style: ButtonStyle::Link, url: Some(profile_url), sku_id: None }; + Card::new(Some(self.accent)) + .header(&[&format!("### 👤 {}", escape(info["name"].as_str().unwrap_or(&self.b.username))), &format!("-# {}<@{}>", if sub.is_empty() { String::new() } else { format!("{} · ", sub.join(" · ")) }, self.b.user)], Some(self.thumbnail.as_deref().unwrap_or(&self.b.avatar))) + .separator(true, false) + .text(&stats.join("\n")) + .text(&format!("**This week**\n{}", if week.is_empty() { "*Nothing scrobbled this week.*".to_string() } else { week.join("\n") })) + .row(vec![go(t, "top", "Top", "🏆"), go(t, "recent", "Recent", "🎧"), site]) + .into() + } + + fn click(&mut self, _: u64, action: &str, _: &[String], _: &HashMap) -> Reply { + let b = self.b.clone(); + match action { + "top" => defer_load(async move { Ok(Box::new(Top::load(b, "artists".into(), "overall".into()).await?) as Box) }), + "recent" => defer_load(async move { Ok(Box::new(Recent::load(b).await?) as Box) }), + _ => Reply::Ignore, + } + } + + fn is_over(&self) -> bool { + self.over + } + + fn abandon(&mut self) { + self.over = true; + } +} diff --git a/src/commands/logs/events.rs b/src/commands/logs/events.rs new file mode 100644 index 0000000..24515e1 --- /dev/null +++ b/src/commands/logs/events.rs @@ -0,0 +1,1151 @@ +//! The event handlers of the logger: one function per kind of server event. +//! +//! The cache is updated *before* handlers run, so what an event changed is read from a [`Pre`] +//! snapshot taken just before the update. +use super::*; +use crate::audit::{changed, target_id, AuditFeed, Merged, Query}; +use twilight_model::channel::Channel; +use twilight_model::gateway::event::Event; +use twilight_model::guild::audit_log::{AuditLogChange, AuditLogEntry, AuditLogEventType as A}; +use twilight_model::guild::Role; +use twilight_model::id::marker::RoleMarker; + +const IMAGE_EXTS: &[&str] = &[".png", ".jpg", ".jpeg", ".gif", ".webp"]; + +// ---- snapshots of the cache taken before an event is applied ------------------------------- + +#[derive(Clone, Default)] +pub struct MemberSnap { + pub nick: Option, + pub roles: Vec>, + pub avatar: Option, + pub premium: bool, + pub pending: bool, + pub timeout: Option, + pub joined: Option, +} + +#[derive(Clone)] +pub struct MsgSnap { + pub id: u64, + pub author: Id, + pub content: String, + pub attachments: Vec<(String, String, String)>, // filename, url, proxy + pub stickers: Vec, + pub reply_to: Option, + pub created: i64, + pub bot: bool, +} + +#[derive(Clone)] +pub struct GuildSnap { + pub name: String, + pub description: Option, + pub icon: Option, + pub banner: Option, + pub splash: Option, + pub vanity: Option, + pub tier: String, + pub verification: String, + pub filter: String, + pub owner: Id, +} + +#[derive(Clone, Default)] +pub struct VoiceSnap { + pub channel: Option>, + pub flags: [bool; 6], // self_mute, self_deaf, mute, deaf, stream, video +} + +#[derive(Default, Clone)] +pub struct Pre { + pub member: Option, + pub channel: Option, + pub role: Option, + pub role_members: usize, + pub guild: Option, + pub user: Option, + pub message: Option, + pub messages: Vec, + pub voice: Option, + pub emojis: Vec<(u64, String)>, + pub stickers: Vec<(u64, String, String)>, +} + +fn snap_msg(m: &twilight_cache_inmemory::model::CachedMessage, state: &State) -> MsgSnap { + MsgSnap { + id: m.id().get(), + author: m.author(), + content: m.content().to_string(), + attachments: m.attachments().iter().map(|a| (a.filename.clone(), a.url.clone(), a.proxy_url.clone())).collect(), + stickers: m.sticker_items().iter().map(|s| s.name.clone()).collect(), + reply_to: m.reference().and_then(|r| r.message_id).map(|i| i.get()), + created: m.timestamp().as_secs(), + bot: state.cache.user(m.author()).is_some_and(|u| u.bot), + } +} + +fn snap_member(state: &State, guild: Id, user: Id) -> Option { + state.cache.member(guild, user).map(|m| MemberSnap { + nick: m.nick().map(str::to_string), + roles: m.roles().to_vec(), + avatar: m.avatar().map(|a| a.to_string()), + premium: m.premium_since().is_some(), + pending: m.pending(), + timeout: m.communication_disabled_until().map(|t| t.as_secs()), + joined: m.joined_at().map(|t| t.as_secs()), + }) +} + +fn snap_guild(g: &twilight_cache_inmemory::model::CachedGuild) -> GuildSnap { + GuildSnap { + name: g.name().to_string(), + description: g.description().map(str::to_string), + icon: g.icon().map(|i| i.to_string()), + banner: g.banner().map(|i| i.to_string()), + splash: g.splash().map(|i| i.to_string()), + vanity: g.vanity_url_code().map(str::to_string), + tier: format!("{:?}", g.premium_tier()), + verification: format!("{:?}", g.verification_level()), + filter: format!("{:?}", g.explicit_content_filter()), + owner: g.owner_id(), + } +} + +/// Take the snapshot an event needs, before the cache applies it. +pub fn capture(state: &State, event: &Event) -> Pre { + let mut p = Pre::default(); + match event { + Event::MemberUpdate(u) => { + p.member = snap_member(state, u.guild_id, u.user.id); + // Discord only tells bots about other people's profile changes through their member records + p.user = state.cache.user(u.user.id).map(|u| u.clone()); + } + Event::MemberRemove(r) => p.member = snap_member(state, r.guild_id, r.user.id), + Event::ChannelUpdate(c) => p.channel = state.cache.channel(c.id).map(|c| c.clone()), + Event::ThreadUpdate(c) => p.channel = state.cache.channel(c.id).map(|c| c.clone()), + Event::RoleUpdate(r) => p.role = state.cache.role(r.role.id).map(|r| r.resource().clone()), + Event::RoleDelete(r) => { + p.role = state.cache.role(r.role_id).map(|r| r.resource().clone()); + p.role_members = state + .cache + .guild_members(r.guild_id) + .map(|ms| ms.iter().filter(|&&u| state.cache.member(r.guild_id, u).is_some_and(|m| m.roles().contains(&r.role_id))).count()) + .unwrap_or(0); + } + Event::GuildUpdate(g) => p.guild = state.cache.guild(g.id).map(|g| snap_guild(&g)), + Event::MessageUpdate(m) => p.message = state.cache.message(m.id).map(|c| snap_msg(&c, state)), + Event::MessageDelete(m) => p.message = state.cache.message(m.id).map(|c| snap_msg(&c, state)), + Event::MessageDeleteBulk(b) => p.messages = b.ids.iter().filter_map(|i| state.cache.message(*i).map(|c| snap_msg(&c, state))).collect(), + Event::VoiceStateUpdate(v) => { + if let Some(g) = v.guild_id { + p.voice = state.cache.voice_state(v.user_id, g).map(|s| VoiceSnap { + channel: Some(s.channel_id()), + flags: [s.self_mute(), s.self_deaf(), s.mute(), s.deaf(), s.self_stream(), s.self_video()], + }); + } + } + Event::GuildEmojisUpdate(e) => { + p.emojis = state.cache.guild_emojis(e.guild_id).map(|ids| ids.iter().filter_map(|i| state.cache.emoji(*i).map(|e| (i.get(), e.name().to_string()))).collect()).unwrap_or_default(); + } + Event::GuildStickersUpdate(s) => { + p.stickers = state.cache.guild_stickers(s.guild_id).map(|ids| ids.iter().filter_map(|i| state.cache.sticker(*i).map(|s| (i.get(), s.name().to_string(), s.description().to_string()))).collect()).unwrap_or_default(); + } + _ => {} + } + p +} + +// ---- small helpers ------------------------------------------------------------------------- + +fn lg() -> &'static Logger { + logger() +} + +fn mention_name(state: &State, id: Id) -> String { + match state.cache.user(id) { + Some(u) => format!("<@{id}> (`{}`)", u.name), + None => format!("<@{id}>"), + } +} + +fn role_list(state: &State, roles: &[Id], guild: Id) -> String { + let mut ranked: Vec<_> = roles.iter().filter(|r| r.cast::() != guild).filter_map(|r| state.cache.role(*r).map(|x| (x.position, *r))).collect(); + ranked.sort_by_key(|(p, _)| std::cmp::Reverse(*p)); + if ranked.is_empty() { + return "None".into(); + } + let shown: Vec = ranked.iter().take(8).map(|(_, r)| format!("<@&{r}>")).collect(); + let extra = if ranked.len() > 8 { format!(" (+{} more)", ranked.len() - 8) } else { String::new() }; + shown.join(", ") + &extra +} + +fn banned_recently(guild: Id, user: Id) -> bool { + lg().recent_bans.lock().unwrap().get(&(guild, user)).is_some_and(|t| now() - t < 30.0) +} + +fn kind_name(k: twilight_model::channel::ChannelType) -> String { + let s = format!("{k:?}"); + let mut out = String::new(); + for (i, c) in s.chars().enumerate() { + if i > 0 && c.is_uppercase() { + out.push(' '); + } + out.push(c); + } + out +} + +fn yes(b: bool) -> &'static str { + if b { "Yes" } else { "No" } +} + +fn quoted(v: &Option) -> String { + format!("`{}`", v.as_deref().unwrap_or("None")) +} + +// ---- invites ------------------------------------------------------------------------------- + +pub async fn snapshot_invites(state: &Arc, guild: Id) -> Option)>> { + if !state.guild_permissions(guild, state.bot_id()).contains(Permissions::MANAGE_GUILD) { + return None; + } + let invites = state.http.guild_invites(guild).await.ok()?.models().await.ok()?; + let snap: HashMap<_, _> = invites.into_iter().map(|i| (i.code, (i.uses.unwrap_or(0), i.max_uses.unwrap_or(0), i.inviter.map(|u| u.id.get())))).collect(); + lg().invites.lock().unwrap().insert(guild, snap.clone()); + Some(snap) +} + +async fn used_invite(state: &Arc, guild: Id) -> Option { + let before = lg().invites.lock().unwrap().get(&guild).cloned(); + let after = snapshot_invites(state, guild).await; + let (before, after) = (before?, after?); + let mut used: Vec = after.iter().filter(|(c, (uses, _, _))| *uses > before.get(*c).map_or(0, |b| b.0)).map(|(c, _)| c.clone()).collect(); + if used.is_empty() { + // single-use / last-use invites vanish once used + used = before.iter().filter(|(c, (uses, max, _))| !after.contains_key(*c) && *max > 0 && uses + 1 >= *max).map(|(c, _)| c.clone()).collect(); + } + if used.len() == 1 { + let code = &used[0]; + let (uses, _, inviter) = after.get(code).or_else(|| before.get(code)).copied()?; + let mut text = format!("`discord.gg/{code}`"); + if let Some(i) = inviter.and_then(Id::new_checked) { + text += &format!(" by {}", who(state, Some(i))); + } + let uses = uses.max(1); + return Some(format!("{text} · {uses} use{}", if uses != 1 { "s" } else { "" })); + } + None +} + +// ---- the dispatcher ------------------------------------------------------------------------ + +pub async fn handle(state: Arc, event: Event, pre: Pre) { + let s = &state; + match event { + Event::GuildAuditLogEntryCreate(e) => { + s.audit.push(s, e.0.clone()); + audit_entry(s, e.0).await; + } + Event::InviteCreate(i) => invite_create(s, *i).await, + Event::InviteDelete(i) => invite_delete(s, i).await, + Event::BanAdd(b) => ban_add(s, b.guild_id, b.user).await, + Event::BanRemove(b) => ban_remove(s, b.guild_id, b.user).await, + Event::MemberAdd(m) => member_join(s, m.guild_id, m.member.user, m.member.pending).await, + Event::MemberRemove(r) => member_remove(s, r.guild_id, r.user, pre).await, + Event::AutoModerationActionExecution(x) => automod(s, x).await, + Event::MessageDelete(d) => message_delete(s, d.guild_id, d.channel_id, d.id, pre).await, + Event::MessageDeleteBulk(b) => message_bulk(s, b.guild_id, b.channel_id, b.ids.len(), pre).await, + Event::MessageUpdate(m) => message_edit(s, m.0, pre).await, + Event::MemberUpdate(u) => { + user_update(s, u.user.clone(), Pre { user: pre.user.clone(), ..Default::default() }).await; + member_update(s, *u, pre).await + } + Event::VoiceStateUpdate(v) => voice_update(s, v.0, pre).await, + Event::ChannelCreate(c) => channel_create(s, c.0).await, + Event::ChannelDelete(c) => channel_delete(s, c.0).await, + Event::ChannelUpdate(c) => channel_update(s, pre.channel, c.0).await, + Event::ThreadCreate(t) => thread_create(s, t.0).await, + Event::ThreadDelete(t) => thread_delete(s, t).await, + Event::ThreadUpdate(t) => thread_update(s, pre.channel, t.0).await, + Event::StageInstanceCreate(x) => stage(s, x.0.guild_id, "Stage started", &x.0.topic, x.0.channel_id), + Event::StageInstanceDelete(x) => stage(s, x.0.guild_id, "Stage ended", &x.0.topic, x.0.channel_id), + Event::WebhooksUpdate(w) => webhooks_update(s, w.guild_id, w.channel_id).await, + Event::RoleCreate(r) => role_create(s, r.guild_id, r.role).await, + Event::RoleDelete(r) => role_delete(s, r.guild_id, r.role_id, pre).await, + Event::RoleUpdate(r) => role_update(s, r.guild_id, pre.role, r.role).await, + Event::GuildEmojisUpdate(e) => emojis_update(s, e.guild_id, pre.emojis, e.emojis).await, + Event::GuildStickersUpdate(st) => stickers_update(s, st.guild_id, pre.stickers, st.stickers).await, + Event::GuildUpdate(g) => guild_update(s, pre.guild, g.0).await, + Event::GuildScheduledEventCreate(e) => sched_create(s, e.0), + Event::GuildScheduledEventDelete(e) => sched_delete(s, e.0).await, + _ => {} + } +} + +/// Take the first-look snapshots for servers the logger is set up in (invites, delete counters). +pub async fn warm_up(state: Arc, guild: Id) { + if lg().enabled(&state, guild, "join_leave") { + snapshot_invites(&state, guild).await; + } + if lg().enabled(&state, guild, "message") { + state.audit.prime(&state, guild, A::MessageDelete).await; + } +} + +// ---- invites ------------------------------------------------------------------------------- + +async fn invite_create(s: &Arc, i: twilight_model::gateway::payload::incoming::InviteCreate) { + lg().invites.lock().unwrap().entry(i.guild_id).or_default().insert(i.code.clone(), (0, i.max_uses, i.inviter.as_ref().map(|u| u.id.get()))); + let expires = if i.max_age > 0 { dt(i.created_at.as_secs() + i.max_age as i64, 'R') } else { "Never".into() }; + let inviter = i.inviter.as_ref().map_or("Unknown".to_string(), |u| format!("<@{}>", u.id)); + let e = LogEntry::new("invite", "Invite created", &format!("`{}` by {inviter}", i.code)) + .author(i.inviter.as_ref().map(author_from_user)) + .field("Channel", format!("<#{}>", i.channel_id)) + .field("Max uses", if i.max_uses > 0 { i.max_uses.to_string() } else { "∞".into() }) + .field("Expires", expires) + .field("Temporary", yes(i.temporary)); + lg().send(s, i.guild_id, e); +} + +async fn invite_delete(s: &Arc, i: twilight_model::gateway::payload::incoming::InviteDelete) { + if !lg().enabled(s, i.guild_id, "invite") { + return; + } + let code = i.code.clone(); + let q = Query::new("invite", &[A::InviteDelete]).check(move |e| e.changes.iter().any(|c| matches!(c, AuditLogChange::Code { old, .. } if old.as_deref() == Some(code.as_str())))); + let actor = s.audit.find(s, i.guild_id, q).await; + let mut fields = vec![("Channel".to_string(), format!("<#{}>", i.channel_id))]; + match actor { + Some(_) => fields.extend(by(s, actor.as_ref(), "By", Reason::Show, None)), + None => fields.push(("Why".into(), "Expired or used up".into())), + } + lg().send(s, i.guild_id, LogEntry::new("invite", "Invite deleted", &format!("`{}`", i.code)).fields(fields)); +} + +// ---- moderation / join-leave --------------------------------------------------------------- + +async fn ban_add(s: &Arc, guild: Id, user: twilight_model::user::User) { + lg().recent_bans.lock().unwrap().insert((guild, user.id), now()); + let moderation = lg().enabled(s, guild, "moderation"); + if !(moderation || lg().enabled(s, guild, "join_leave")) { + return; + } + let actor = s.audit.find(s, guild, Query::new("ban", &[A::MemberBanAdd]).target(user.id.get()).timeout(4.0)).await; + let mut fields = by(s, actor.as_ref(), "By", Reason::Always, None); + if fields.is_empty() { + fields = unknown(s, guild); + } + let e = LogEntry::new(if moderation { "moderation" } else { "join_leave" }, "Member banned", &format!("<@{}> (`{}`) was banned", user.id, user.name)) + .author(Some(author_from_user(&user))).fields(fields); + lg().send(s, guild, e); +} + +async fn ban_remove(s: &Arc, guild: Id, user: twilight_model::user::User) { + lg().recent_bans.lock().unwrap().remove(&(guild, user.id)); + if !lg().enabled(s, guild, "moderation") { + return; + } + let actor = s.audit.find(s, guild, Query::new("unban", &[A::MemberBanRemove]).target(user.id.get()).timeout(4.0)).await; + let mut fields = by(s, actor.as_ref(), "By", Reason::Show, None); + if fields.is_empty() { + fields = unknown(s, guild); + } + lg().send(s, guild, LogEntry::new("moderation", "Member unbanned", &format!("<@{}> (`{}`) was unbanned", user.id, user.name)).author(Some(author_from_user(&user))).fields(fields)); +} + +async fn member_join(s: &Arc, guild: Id, user: twilight_model::user::User, _pending: bool) { + if !lg().enabled(s, guild, "join_leave") { + return; + } + let created = ((user.id.get() >> 22) + 1_420_070_400_000) / 1000; + let age = now() - created as f64; + let mut fields = vec![("Account created".to_string(), dt(created as i64, 'R'))]; + if age < 7.0 * 86400.0 { + fields.push(("⚠️ New account".into(), format!("only {} old", fmt_secs(age)))); + } + if user.bot { + let actor = s.audit.find(s, guild, Query::new("join", &[A::BotAdd]).target(user.id.get()).timeout(3.0)).await; + fields.extend(by(s, actor.as_ref(), "Added by", Reason::Never, None)); + } else if let Some(inv) = used_invite(s, guild).await { + fields.push(("Invite".into(), inv)); + } + let count = s.cache.guild(guild).and_then(|g| g.member_count()).unwrap_or(0); + fields.push(("Member count".into(), count.to_string())); + let e = LogEntry::new("join_leave", if user.bot { "Bot added" } else { "Member joined" }, &format!("<@{}> joined", user.id)) + .author(Some(author_from_user(&user))).fields(fields); + lg().send(s, guild, e); +} + +async fn member_remove(s: &Arc, guild: Id, user: twilight_model::user::User, pre: Pre) { + let moderation = lg().enabled(s, guild, "moderation"); + if !(moderation || lg().enabled(s, guild, "join_leave")) { + return; + } + let uid = user.id.get(); + let entry = if AuditFeed::can_read(s, guild) { + let q = Query::new("remove", &[A::MemberKick, A::MemberBanAdd, A::MemberPrune]).claim_key(uid).timeout(3.0) + .check(move |e| e.action_type == A::MemberPrune || target_id(e) == Some(uid)); + s.audit.find_entry(s, guild, q).await + } else { + tokio::time::sleep(Duration::from_millis(1500)).await; // give the ban handler a moment to record the ban + None + }; + if entry.as_ref().is_some_and(|e| e.action_type == A::MemberBanAdd) || banned_recently(guild, user.id) { + return; // the ban handler reports it + } + if entry.as_ref().is_some_and(|e| e.action_type == A::MemberPrune) { + return; // one summary entry is logged for the whole prune + } + let member = pre.member.unwrap_or_default(); + let stay = ("Joined".to_string(), member.joined.map_or("Unknown".into(), |j| dt(j, 'R'))); + let roles = ("Roles".to_string(), role_list(s, &member.roles, guild)); + let author = Some(author_from_user(&user)); + if let Some(k) = entry.filter(|e| e.action_type == A::MemberKick) { + let actor = s.audit.actor(s, Some(&k)); + let mut fields = by(s, actor.as_ref(), "By", Reason::Always, None); + fields.extend([stay, roles]); + let e = LogEntry::new(if moderation { "moderation" } else { "join_leave" }, "Member kicked", &format!("<@{}> (`{}`) was kicked", user.id, user.name)).author(author).fields(fields); + return lg().send(s, guild, e); + } + let count = s.cache.guild(guild).and_then(|g| g.member_count()).unwrap_or(0); + let e = LogEntry::new("join_leave", "Member left", &format!("<@{}> (`{}`) left", user.id, user.name)).author(author) + .fields(vec![stay, roles, ("Member count".into(), count.to_string())]); + lg().send(s, guild, e); +} + +async fn automod(s: &Arc, x: twilight_model::gateway::payload::incoming::AutoModerationActionExecution) { + use twilight_model::guild::auto_moderation::AutoModerationActionType as T; + let guild = x.guild_id; + if !lg().enabled(s, guild, "moderation") { + return; + } + let what = match x.action.kind { + T::BlockMessage => "message blocked".to_string(), + T::SendAlertMessage => "alert sent".to_string(), + T::Timeout => x.action.metadata.as_ref().and_then(|m| m.duration_seconds).map_or("timed out".into(), |d| format!("timed out for {}", fmt_secs(d as f64))), + other => format!("{other:?}").to_lowercase(), + }; + // one AutoMod trigger fires an event per action (block, alert, timeout); merge them into one entry + let key = (guild.get(), x.rule_id.get(), x.user_id.get(), x.content.clone()); + { + let mut pending = lg().automod_pending.lock().unwrap(); + if let Some(list) = pending.get_mut(&key) { + list.push(what); + return; + } + pending.insert(key.clone(), vec![what]); + } + tokio::time::sleep(Duration::from_secs(1)).await; + let actions = lg().automod_pending.lock().unwrap().remove(&key).unwrap_or_default(); + let rule = rule_name(s, guild, x.rule_id.get()).await; + let mut fields = vec![("Rule".to_string(), rule), ("Action".to_string(), actions.join(", "))]; + if let Some(c) = x.channel_id { + fields.push(("Channel".into(), format!("<#{c}>"))); + } + if let Some(k) = &x.matched_keyword { + fields.push(("Matched".into(), format!("`{}`", truncate(k, 100)))); + } + if !x.content.is_empty() { + fields.push(("Content".into(), escape(&truncate(&x.content, 900)))); + } + lg().send(s, guild, LogEntry::new("moderation", "AutoMod action", &format!("<@{}> triggered AutoMod", x.user_id)).author(author_of(s, x.user_id)).fields(fields)); +} + +async fn rule_name(s: &Arc, guild: Id, rule: u64) -> String { + if let Some(n) = lg().rule_names.lock().unwrap().get(&rule) { + return n.clone(); + } + let Some(id) = Id::new_checked(rule) else { return format!("Rule `{rule}`") }; + match s.http.auto_moderation_rule(guild, id).await { + Ok(r) => match r.model().await { + Ok(m) => { + let name = escape(&m.name); + lg().rule_names.lock().unwrap().insert(rule, name.clone()); + name + } + Err(_) => format!("Rule `{rule}`"), + }, + Err(_) => format!("Rule `{rule}`"), + } +} + +/// Things that only the audit log tells us about. +async fn audit_entry(s: &Arc, e: AuditLogEntry) { + let Some(guild) = e.guild_id else { return }; + let actor = s.audit.actor(s, Some(&e)); + match e.action_type { + A::MessagePin | A::MessageUnpin if lg().enabled(s, guild, "message") => { + let (Some(channel), Some(message)) = (e.options.as_ref().and_then(|o| o.channel_id), e.options.as_ref().and_then(|o| o.message_id)) else { return }; + let pinned = e.action_type == A::MessagePin; + let link = format!("https://discord.com/channels/{guild}/{channel}/{message}"); + let mut fields = by(s, actor.as_ref(), if pinned { "Pinned by" } else { "Unpinned by" }, Reason::Never, None); + let cached = s.cache.message(message).map(|m| (m.author(), m.content().to_string(), !m.attachments().is_empty())); + let mut author = None; + if let Some((a, content, att)) = cached { + if !content.is_empty() || att { + fields.push(("Content".into(), if content.is_empty() { "*attachment*".into() } else { escape(&truncate(&content, 600)) })); + } + author = author_of(s, a); + } + let by_user = target_id(&e).map_or("?".to_string(), |a| format!("<@{a}>")); + lg().send(s, guild, LogEntry::new("message", if pinned { "Message pinned" } else { "Message unpinned" }, + &format!("Message by {by_user} in <#{channel}> · [Jump to message](<{link}>)")).fields(fields).author(author)); + } + A::MemberPrune if lg().enabled(s, guild, "moderation") => { + let o = e.options.as_ref(); + let removed: u64 = o.and_then(|o| o.members_removed.as_deref()).and_then(|v| v.parse().ok()).unwrap_or(0); + let days = o.and_then(|o| o.delete_member_days.as_deref()).unwrap_or("0").to_string(); + let mut fields = vec![("Inactive for".to_string(), format!("{days} days"))]; + fields.extend(by(s, actor.as_ref(), "By", Reason::Show, None)); + lg().send(s, guild, LogEntry::new("moderation", "Members pruned", &format!("**{removed}** inactive member{} removed", if removed != 1 { "s" } else { "" })).fields(fields)); + } + _ => {} + } +} + +// ---- messages ------------------------------------------------------------------------------ + +async fn message_delete(s: &Arc, guild: Option>, channel: Id, id: Id, pre: Pre) { + let (Some(guild), Some(m)) = (guild, pre.message) else { return }; + if m.bot || !lg().enabled(s, guild, "message") { + return; + } + let (mut images, mut files) = (vec![], vec![]); + for (name, url, proxy) in &m.attachments { + if IMAGE_EXTS.iter().any(|x| name.to_lowercase().ends_with(x)) { + images.push(if proxy.is_empty() { url.clone() } else { proxy.clone() }); + } + files.push(format!("[{}](<{url}>)", escape(name))); + } + let mut fields = vec![]; + if !m.content.is_empty() { + fields.push(("Content".to_string(), escape(&m.content))); + } + if !files.is_empty() { + fields.push(("Attachments".into(), files.join("\n"))); + } + if !m.stickers.is_empty() { + fields.push(("Stickers".into(), m.stickers.join(", "))); + } + if let Some(r) = m.reply_to { + fields.push(("Reply to".into(), format!("[message]()"))); + } + fields.push(("Sent".into(), dt(m.created, 'R'))); + match s.audit.deleted_by(s, guild, channel.get(), m.author.get()).await { + Merged::Unreadable => fields.extend(unknown(s, guild)), + Merged::Nobody if banned_recently(guild, m.author) => fields.push(("Deleted by".into(), "a ban (their recent messages were cleared)".into())), + Merged::Nobody => fields.push(("Deleted by".into(), "the author".into())), + Merged::By(a) => fields.extend(by(s, Some(&a), "Deleted by", Reason::Show, None)), + } + let _ = id; + lg().send(s, guild, LogEntry::new("message", "Message deleted", &format!("Message by <@{}> deleted in <#{channel}>", m.author)).author(author_of(s, m.author)).fields(fields).images(images)); +} + +async fn message_bulk(s: &Arc, guild: Option>, channel: Id, total: usize, pre: Pre) { + let Some(guild) = guild else { return }; + if !lg().enabled(s, guild, "message") { + return; + } + let mut cached = pre.messages; + cached.sort_by_key(|m| m.created); + let file = (!cached.is_empty()).then(|| { + let lines: Vec = cached.iter().map(|m| { + let who = s.cache.user(m.author).map_or(m.author.to_string(), |u| format!("{} ({})", u.name, m.author)); + let att: Vec<&str> = m.attachments.iter().map(|a| a.1.as_str()).collect(); + format!("[{}] {who}: {} {}", m.created, m.content, att.join(" ")).trim_end().to_string() + }).collect(); + ("deleted-messages.txt".to_string(), lines.join("\n").into_bytes()) + }); + let mut description = format!("**{total}** messages were deleted in <#{channel}>"); + if !cached.is_empty() { + description += &format!("\n-# Transcript of the {} I had cached is attached.", cached.len()); + } + let actor = s.audit.find(s, guild, Query::new("bulk", &[A::MessageBulkDelete]).target(channel.get())).await; + let mut fields = by(s, actor.as_ref(), "Deleted by", Reason::Show, None); + if fields.is_empty() && AuditFeed::can_read(s, guild) { + let authors: HashSet<_> = cached.iter().map(|m| m.author).collect(); + if authors.len() == 1 && banned_recently(guild, *authors.iter().next().unwrap()) { + fields = vec![("Deleted by".into(), "a ban (their recent messages were cleared)".into())]; + } + } + let mut e = LogEntry::new("message", "Messages bulk deleted", &description).fields(fields); + e.file = file.map(|(n, b)| (crate::ui::file_name(&n), b)); + lg().send(s, guild, e); +} + +async fn message_edit(s: &Arc, m: twilight_model::channel::Message, pre: Pre) { + let (Some(guild), Some(before)) = (m.guild_id, pre.message) else { return }; + if before.bot || m.author.bot || before.content == m.content || !lg().enabled(s, guild, "message") { + return; + } + let link = format!("https://discord.com/channels/{guild}/{}/{}", m.channel_id, m.id); + let show = |t: &str| if t.is_empty() { "*empty*".to_string() } else { escape(&truncate(t, 900)) }; + lg().send(s, guild, LogEntry::new("message", "Message edited", &format!("By <@{}> in <#{}> · [Jump to message](<{link}>)", before.author, m.channel_id)) + .author(Some(author_from_user(&m.author))) + .field("Before", show(&before.content)).field("After", show(&m.content)).field("Sent", dt(before.created, 'R'))); +} + +// ---- members ------------------------------------------------------------------------------- + +async fn user_update(s: &Arc, after: twilight_model::user::User, pre: Pre) { + let Some(before) = pre.user else { return }; + if after.bot { + return; + } + let mut changes: Vec<(String, String, Vec<(String, String)>, Vec)> = vec![]; + let mention = format!("<@{}>", after.id); + if before.avatar != after.avatar { + changes.push(("Avatar updated".into(), format!("{mention} changed their avatar"), vec![], vec![ui::avatar_url(after.id, after.avatar.as_ref())])); + } + if before.name != after.name { + changes.push(("Username changed".into(), mention.clone(), vec![("Before".into(), format!("`{}`", before.name)), ("After".into(), format!("`{}`", after.name))], vec![])); + } + if before.global_name != after.global_name { + changes.push(("Display name changed".into(), mention.clone(), vec![("Before".into(), quoted(&before.global_name)), ("After".into(), quoted(&after.global_name))], vec![])); + } + if changes.is_empty() { + return; + } + let guilds: Vec<_> = s.cache.user_guilds(after.id).map(|g| g.iter().copied().collect()).unwrap_or_default(); + for guild in guilds { + if lg().enabled(s, guild, "member") { + for (title, desc, fields, images) in &changes { + lg().send(s, guild, LogEntry::new("member", title, desc).author(Some(author_from_user(&after))).fields(fields.clone()).images(images.clone())); + } + } + } +} + +async fn member_update(s: &Arc, u: twilight_model::gateway::payload::incoming::MemberUpdate, pre: Pre) { + let guild = u.guild_id; + let Some(before) = pre.member else { return }; + let user = u.user.clone(); + let author = Some(author_from_user(&user)); + let mention = format!("<@{}>", user.id); + let after_timeout = u.communication_disabled_until.map(|t| t.as_secs()); + if before.timeout != after_timeout && lg().enabled(s, guild, "moderation") { + let q = Query::new("timeout", &[A::MemberUpdate, A::AutoModerationUserCommunicationDisabled]).target(user.id.get()) + .check(|e| e.action_type == A::AutoModerationUserCommunicationDisabled || changed(e, |c| matches!(c, AuditLogChange::CommunicationDisabledUntil { .. }))); + let actor = s.audit.find(s, guild, q).await; + let n = now(); + let name = format!("{mention} (`{}`)", user.name); + match after_timeout.filter(|t| *t as f64 > n) { + Some(t) => { + let mut fields = vec![("Duration".to_string(), fmt_secs(t as f64 - n)), ("Until".to_string(), dt(t, 'F'))]; + let mut b = by(s, actor.as_ref(), "By", Reason::Always, None); + if b.is_empty() { + b = unknown(s, guild); + } + fields.extend(b); + lg().send(s, guild, LogEntry::new("moderation", "Member timed out", &name).author(author.clone()).fields(fields)); + } + None => { + let mut b = by(s, actor.as_ref(), "By", Reason::Show, None); + if b.is_empty() { + b = unknown(s, guild); + } + lg().send(s, guild, LogEntry::new("moderation", "Timeout removed", &name).author(author.clone()).fields(b)); + } + } + } + if !lg().enabled(s, guild, "member") { + return; + } + if before.nick != u.nick { + let actor = s.audit.find(s, guild, Query::new("nick", &[A::MemberUpdate]).target(user.id.get()).check(|e| changed(e, |c| matches!(c, AuditLogChange::Nick { .. })))).await; + let show = |n: &Option| n.as_ref().map_or("*none*".to_string(), |n| format!("`{n}`")); + let mut fields = vec![("Before".to_string(), show(&before.nick)), ("After".to_string(), show(&u.nick))]; + fields.extend(by(s, actor.as_ref(), "By", Reason::Show, Some(user.id))); + lg().send(s, guild, LogEntry::new("member", "Nickname changed", &mention).author(author.clone()).fields(fields)); + } + if before.roles != u.roles { + let added: Vec = u.roles.iter().filter(|r| !before.roles.contains(r)).map(|r| format!("<@&{r}>")).collect(); + let removed: Vec = before.roles.iter().filter(|r| !u.roles.contains(r)).map(|r| format!("<@&{r}>")).collect(); + if !(added.is_empty() && removed.is_empty()) { + let actor = s.audit.find(s, guild, Query::new("roles", &[A::MemberRoleUpdate]).target(user.id.get())).await; + let mut fields = vec![]; + if !added.is_empty() { + fields.push(("Added".to_string(), added.join(", "))); + } + if !removed.is_empty() { + fields.push(("Removed".to_string(), removed.join(", "))); + } + fields.extend(by(s, actor.as_ref(), "By", Reason::Show, Some(user.id))); + lg().send(s, guild, LogEntry::new("member", "Roles updated", &mention).author(author.clone()).fields(fields)); + } + } + let new_avatar = u.avatar.map(|a| a.to_string()); + if before.avatar != new_avatar { + let images = u.avatar.map(|a| vec![format!("https://cdn.discordapp.com/guilds/{guild}/users/{}/avatars/{a}.png", user.id)]).unwrap_or_default(); + lg().send(s, guild, LogEntry::new("member", "Server avatar changed", &mention).author(author.clone()).images(images)); + } + if before.premium != u.premium_since.is_some() { + if u.premium_since.is_some() { + let g = s.cache.guild(guild); + let boosts = g.as_ref().and_then(|g| g.premium_subscription_count()).unwrap_or(0); + let tier = g.map_or("?".into(), |g| format!("{:?}", g.premium_tier())); + lg().send(s, guild, LogEntry::new("member", "Boosted the server 💎", &format!("{mention} boosted the server")).author(author.clone()).field("Boosts", format!("{boosts} · {tier}"))); + } else { + lg().send(s, guild, LogEntry::new("member", "Stopped boosting", &format!("{mention} is no longer boosting")).author(author.clone())); + } + } + if before.pending && !u.pending { + lg().send(s, guild, LogEntry::new("member", "Passed membership screening", &format!("{mention} accepted the server rules")).author(author)); + } +} + +// ---- voice --------------------------------------------------------------------------------- + +async fn voice_update(s: &Arc, v: twilight_model::voice::VoiceState, pre: Pre) { + let Some(guild) = v.guild_id else { return }; + if v.member.as_ref().is_some_and(|m| m.user.bot) { + return; + } + let user = v.user_id; + let before = pre.voice.unwrap_or_default(); + let key = (guild, user); + let mut joined = None; + match (before.channel, v.channel_id) { + (None, Some(_)) => { + lg().voice_since.lock().unwrap().insert(key, now()); + } + (Some(_), None) => joined = lg().voice_since.lock().unwrap().remove(&key), + _ => {} + } + if !lg().enabled(s, guild, "voice") { + return; + } + let author = v.member.as_ref().map(|m| author_from_user(&m.user)).or_else(|| author_of(s, user)); + let mention = format!("<@{user}>"); + match (before.channel, v.channel_id) { + (None, Some(after)) => { + let n = s.cache.voice_channel_states(after).map_or(0, |it| it.count()); + lg().send(s, guild, LogEntry::new("voice", "Joined voice", &format!("{mention} joined <#{after}>")).author(author).field("Members", format!("{n} in channel"))); + } + (Some(b), None) => { + let mut fields = vec![("Time in voice".to_string(), joined.map_or("Unknown".into(), |j| fmt_secs(now() - j)))]; + let actor = match s.audit.merged(s, guild, A::MemberDisconnect, None, None).await { + Merged::By(a) => Some(a), + _ => None, + }; + if let Some(a) = &actor { + fields.extend(by(s, Some(a), "Disconnected by", Reason::Never, None)); + } + lg().send(s, guild, LogEntry::new("voice", if actor.is_some() { "Disconnected from voice" } else { "Left voice" }, &format!("{mention} left <#{b}>")).author(author).fields(fields)); + } + (Some(b), Some(a)) if b != a => { + let actor = match s.audit.merged(s, guild, A::MemberMove, Some(a.get()), None).await { + Merged::By(x) => Some(x), + _ => None, + }; + let fields = actor.as_ref().map(|a| by(s, Some(a), "Moved by", Reason::Never, None)).unwrap_or_default(); + lg().send(s, guild, LogEntry::new("voice", "Moved voice channel", &format!("{mention}: <#{b}> → <#{a}>")).author(author).fields(fields)); + } + (Some(_), Some(after)) => { + let now_flags = [v.self_mute, v.self_deaf, v.mute, v.deaf, v.self_stream, v.self_video]; + let labels = [ + ("Self mute", "🔇 on", "🔊 off"), ("Self deafen", "🔇 on", "🔊 off"), ("Server mute", "🔇 on", "🔊 off"), + ("Server deafen", "🔇 on", "🔊 off"), ("Streaming", "📺 started", "⏹️ stopped"), ("Camera", "📹 on", "⏹️ off"), + ]; + let mut changes: Vec<(String, String)> = (0..6).filter(|&i| before.flags[i] != now_flags[i]) + .map(|i| (labels[i].0.to_string(), (if now_flags[i] { labels[i].1 } else { labels[i].2 }).to_string())).collect(); + if changes.is_empty() { + return; + } + if before.flags[2] != now_flags[2] || before.flags[3] != now_flags[3] { + let q = Query::new("voice", &[A::MemberUpdate]).target(user.get()).check(|e| changed(e, |c| matches!(c, AuditLogChange::Mute { .. } | AuditLogChange::Deaf { .. }))); + let actor = s.audit.find(s, guild, q).await; + changes.extend(by(s, actor.as_ref(), "By", Reason::Never, None)); + } + lg().send(s, guild, LogEntry::new("voice", "Voice state changed", &format!("{mention} in <#{after}>")).author(author).fields(changes)); + } + (None, None) => {} + } +} + +// ---- channels & threads -------------------------------------------------------------------- + +fn category_name(s: &State, c: &Channel) -> Option { + c.parent_id.and_then(|p| s.cache.channel(p).and_then(|p| p.name.clone())) +} + +async fn channel_create(s: &Arc, c: Channel) { + let Some(guild) = c.guild_id else { return }; + if !lg().enabled(s, guild, "channel") { + return; + } + let mut fields = vec![("Type".to_string(), kind_name(c.kind))]; + if let Some(cat) = category_name(s, &c) { + fields.push(("Category".into(), escape(&cat))); + } + let actor = s.audit.find(s, guild, Query::new("channel", &[A::ChannelCreate]).target(c.id.get())).await; + fields.extend(by(s, actor.as_ref(), "By", Reason::Show, None)); + lg().send(s, guild, LogEntry::new("channel", "Channel created", &format!("<#{}> (`{}`)", c.id, c.name.as_deref().unwrap_or("?"))).fields(fields)); +} + +async fn channel_delete(s: &Arc, c: Channel) { + let Some(guild) = c.guild_id else { return }; + if !lg().enabled(s, guild, "channel") { + return; + } + let mut fields = vec![("Type".to_string(), kind_name(c.kind))]; + if let Some(cat) = category_name(s, &c) { + fields.push(("Category".into(), escape(&cat))); + } + let actor = s.audit.find(s, guild, Query::new("channel", &[A::ChannelDelete]).target(c.id.get())).await; + fields.extend(by(s, actor.as_ref(), "By", Reason::Show, None)); + lg().send(s, guild, LogEntry::new("channel", "Channel deleted", &format!("`#{}`", c.name.as_deref().unwrap_or("?"))).fields(fields)); +} + +fn perm_names(p: Permissions) -> Vec { + p.iter_names().map(|(n, _)| n.to_lowercase().replace('_', " ")).collect() +} + +fn overwrite_text(allow: Permissions, deny: Permissions) -> String { + let names = |p: Permissions| { + let v = perm_names(p); + if v.is_empty() { "—".to_string() } else { v.join(", ") } + }; + format!("✅ {}\n❌ {}", names(allow), names(deny)) +} + +async fn channel_update(s: &Arc, before: Option, after: Channel) { + let (Some(guild), Some(before)) = (after.guild_id, before) else { return }; + if !lg().enabled(s, guild, "channel") { + return; + } + let target_name = |kind: twilight_model::channel::permission_overwrite::PermissionOverwriteType, id: u64| { + if matches!(kind, twilight_model::channel::permission_overwrite::PermissionOverwriteType::Role) { format!("<@&{id}>") } else { format!("<@{id}>") } + }; + let (old, new) = (before.permission_overwrites.clone().unwrap_or_default(), after.permission_overwrites.clone().unwrap_or_default()); + if old != new { + let mut changes = vec![]; + for o in &new { + match old.iter().find(|x| x.id == o.id && x.kind == o.kind) { + None => changes.push((format!("Added: {}", target_name(o.kind, o.id.get())), overwrite_text(o.allow, o.deny))), + Some(x) if x != o => changes.push((format!("Changed: {}", target_name(o.kind, o.id.get())), overwrite_text(o.allow, o.deny))), + _ => {} + } + } + for o in &old { + if !new.iter().any(|x| x.id == o.id && x.kind == o.kind) { + changes.push((format!("Removed: {}", target_name(o.kind, o.id.get())), "overwrite removed".into())); + } + } + if !changes.is_empty() { + let q = Query::new("overwrite", &[A::ChannelOverwriteCreate, A::ChannelOverwriteUpdate, A::ChannelOverwriteDelete]).target(after.id.get()); + let actor = s.audit.find(s, guild, q).await; + changes.truncate(8); + changes.extend(by(s, actor.as_ref(), "By", Reason::Show, None)); + lg().send(s, guild, LogEntry::new("channel", "Channel permissions changed", &format!("<#{}>", after.id)).fields(changes)); + } + } + let mut details = vec![]; + if before.name != after.name { + details.push(("Name".to_string(), format!("`{}` → `{}`", before.name.as_deref().unwrap_or("?"), after.name.as_deref().unwrap_or("?")))); + } + let pair = |label: &str, a: String, b: String, out: &mut Vec<(String, String)>| { + if a != b { + out.push((label.to_string(), format!("`{}` → `{}`", truncate(&a, 300), truncate(&b, 300)))); + } + }; + pair("Topic", format!("{:?}", before.topic), format!("{:?}", after.topic), &mut details); + pair("Slowmode", format!("{:?}", before.rate_limit_per_user), format!("{:?}", after.rate_limit_per_user), &mut details); + pair("NSFW", format!("{:?}", before.nsfw), format!("{:?}", after.nsfw), &mut details); + pair("User limit", format!("{:?}", before.user_limit), format!("{:?}", after.user_limit), &mut details); + pair("Bitrate", format!("{:?}", before.bitrate), format!("{:?}", after.bitrate), &mut details); + if before.parent_id != after.parent_id { + let name = |c: &Channel| category_name(s, c).unwrap_or_else(|| "None".into()); + details.push(("Category".into(), format!("`{}` → `{}`", name(&before), name(&after)))); + } + if !details.is_empty() { + let actor = s.audit.find(s, guild, Query::new("channel", &[A::ChannelUpdate]).target(after.id.get())).await; + details.extend(by(s, actor.as_ref(), "By", Reason::Show, None)); + lg().send(s, guild, LogEntry::new("channel", "Channel updated", &format!("<#{}>", after.id)).fields(details)); + } +} + +async fn thread_create(s: &Arc, t: Channel) { + let Some(guild) = t.guild_id else { return }; + if !lg().enabled(s, guild, "channel") { + return; + } + let mut fields = vec![("Type".to_string(), if t.kind == twilight_model::channel::ChannelType::PrivateThread { "Private" } else { "Public" }.to_string())]; + if let Some(o) = t.owner_id { + fields.push(("Owner".into(), format!("<@{o}>"))); + } + let parent = t.parent_id.map_or("unknown channel".to_string(), |p| format!("<#{p}>")); + lg().send(s, guild, LogEntry::new("channel", "Thread created", &format!("<#{}> in {parent}", t.id)).fields(fields)); +} + +async fn thread_delete(s: &Arc, t: twilight_model::gateway::payload::incoming::ThreadDelete) { + if !lg().enabled(s, t.guild_id, "channel") { + return; + } + let actor = s.audit.find(s, t.guild_id, Query::new("thread", &[A::ThreadDelete]).target(t.id.get())).await; + lg().send(s, t.guild_id, LogEntry::new("channel", "Thread deleted", &format!("a thread in <#{}>", t.parent_id)).fields(by(s, actor.as_ref(), "By", Reason::Show, None))); +} + +async fn thread_update(s: &Arc, before: Option, after: Channel) { + let (Some(guild), Some(before)) = (after.guild_id, before) else { return }; + if !lg().enabled(s, guild, "channel") { + return; + } + let (bm, am) = (before.thread_metadata.clone(), after.thread_metadata.clone()); + let mut details = vec![]; + if before.name != after.name { + details.push(("Name".to_string(), format!("`{}` → `{}`", before.name.as_deref().unwrap_or("?"), after.name.as_deref().unwrap_or("?")))); + } + if let (Some(b), Some(a)) = (&bm, &am) { + if b.archived != a.archived { + details.push(("Archived".into(), format!("`{}` → `{}`", b.archived, a.archived))); + } + if b.locked != a.locked { + details.push(("Locked".into(), format!("`{}` → `{}`", b.locked, a.locked))); + } + } + if before.rate_limit_per_user != after.rate_limit_per_user { + details.push(("Slowmode".into(), format!("`{:?}` → `{:?}`", before.rate_limit_per_user, after.rate_limit_per_user))); + } + if details.len() == 1 && details[0].0 == "Archived" && details[0].1.ends_with("`true`") { + return; // auto-archiving after inactivity is just noise + } + if !details.is_empty() { + let actor = s.audit.find(s, guild, Query::new("thread", &[A::ThreadUpdate]).target(after.id.get()).timeout(1.5)).await; + details.extend(by(s, actor.as_ref(), "By", Reason::Show, None)); + let parent = after.parent_id.map_or("unknown channel".to_string(), |p| format!("<#{p}>")); + lg().send(s, guild, LogEntry::new("channel", "Thread updated", &format!("<#{}> in {parent}", after.id)).fields(details)); + } +} + +fn stage(s: &Arc, guild: Id, title: &str, topic: &str, channel: Id) { + lg().send(s, guild, LogEntry::new("channel", title, &format!("**{}** in <#{channel}>", escape(topic)))); +} + +async fn webhooks_update(s: &Arc, guild: Id, channel: Id) { + lg().forget_webhook(channel); // our cached webhook may have been deleted + if !lg().enabled(s, guild, "channel") { + return; + } + let q = Query::new("webhook", &[A::WebhookCreate, A::WebhookUpdate, A::WebhookDelete]).claim_key(channel.get()); + let Some(entry) = s.audit.find_entry(s, guild, q).await else { + return lg().send(s, guild, LogEntry::new("channel", "Webhooks updated", &format!("Webhooks in <#{channel}> were changed"))); + }; + let name = entry.changes.iter().find_map(|c| match c { + AuditLogChange::Name { new, old } => new.clone().or_else(|| old.clone()), + _ => None, + }).unwrap_or_else(|| "a webhook".into()); + if entry.user_id == Some(s.bot_id()) && name == WEBHOOK_NAME { + return; // our own logger webhook + } + let verb = match entry.action_type { A::WebhookCreate => "created", A::WebhookUpdate => "updated", _ => "deleted" }; + let actor = s.audit.actor(s, Some(&entry)); + lg().send(s, guild, LogEntry::new("channel", &format!("Webhook {verb}"), &format!("**{}** in <#{channel}>", escape(&name))).fields(by(s, actor.as_ref(), "By", Reason::Show, None))); +} + +// ---- roles --------------------------------------------------------------------------------- + +fn colour(c: u32) -> String { + format!("`#{c:06x}`") +} + +async fn role_create(s: &Arc, guild: Id, role: Role) { + if !lg().enabled(s, guild, "role") { + return; + } + let actor = s.audit.find(s, guild, Query::new("role", &[A::RoleCreate]).target(role.id.get())).await; + let mut fields = vec![("Colour".to_string(), colour(role.color)), ("Hoisted".into(), yes(role.hoist).into()), ("Mentionable".into(), yes(role.mentionable).into())]; + fields.extend(by(s, actor.as_ref(), "By", Reason::Show, None)); + lg().send(s, guild, LogEntry::new("role", "Role created", &format!("<@&{}> (`{}`)", role.id, role.name)).fields(fields)); +} + +async fn role_delete(s: &Arc, guild: Id, id: Id, pre: Pre) { + if !lg().enabled(s, guild, "role") { + return; + } + let actor = s.audit.find(s, guild, Query::new("role", &[A::RoleDelete]).target(id.get())).await; + let (name, color) = pre.role.map_or(("?".to_string(), 0), |r| (r.name, r.color)); + let mut fields = vec![("Members".to_string(), pre.role_members.to_string())]; + fields.extend(by(s, actor.as_ref(), "By", Reason::Show, None)); + lg().send(s, guild, LogEntry::new("role", "Role deleted", &format!("`{name}` ({})", colour(color))).fields(fields)); +} + +async fn role_update(s: &Arc, guild: Id, before: Option, after: Role) { + let Some(before) = before else { return }; + if !lg().enabled(s, guild, "role") { + return; + } + let mut changes = vec![]; + if before.name != after.name { + changes.push(("Name".to_string(), format!("`{}` → `{}`", before.name, after.name))); + } + if before.color != after.color { + changes.push(("Colour".into(), format!("{} → {}", colour(before.color), colour(after.color)))); + } + if before.hoist != after.hoist { + changes.push(("Shown separately".into(), yes(after.hoist).into())); + } + if before.mentionable != after.mentionable { + changes.push(("Mentionable".into(), yes(after.mentionable).into())); + } + if before.icon != after.icon || before.unicode_emoji != after.unicode_emoji { + changes.push(("Icon".into(), if after.icon.is_some() || after.unicode_emoji.is_some() { "updated" } else { "removed" }.into())); + } + if before.permissions != after.permissions { + let list = |p: Permissions| perm_names(p).join(", "); + let (granted, revoked) = (after.permissions - before.permissions, before.permissions - after.permissions); + if !granted.is_empty() { + changes.push(("✅ Permissions granted".into(), list(granted))); + } + if !revoked.is_empty() { + changes.push(("❌ Permissions removed".into(), list(revoked))); + } + } + if !changes.is_empty() { + // position-only changes (dragging roles around) aren't worth a log entry + let actor = s.audit.find(s, guild, Query::new("role", &[A::RoleUpdate]).target(after.id.get())).await; + changes.extend(by(s, actor.as_ref(), "By", Reason::Show, None)); + lg().send(s, guild, LogEntry::new("role", "Role updated", &format!("<@&{}>", after.id)).fields(changes)); + } +} + +// ---- emoji & stickers ---------------------------------------------------------------------- + +async fn emojis_update(s: &Arc, guild: Id, before: Vec<(u64, String)>, after: Vec) { + if !lg().enabled(s, guild, "emoji_sticker") { + return; + } + let url = |id: u64, animated: bool| format!("https://cdn.discordapp.com/emojis/{id}.{}", if animated { "gif" } else { "png" }); + for e in after.iter().filter(|e| !before.iter().any(|b| b.0 == e.id.get())) { + let actor = s.audit.find(s, guild, Query::new("emoji", &[A::EmojiCreate]).target(e.id.get())).await; + let shown = format!("<{}:{}:{}>", if e.animated { "a" } else { "" }, e.name, e.id); + lg().send(s, guild, LogEntry::new("emoji_sticker", "Emoji added", &format!("{shown} `:{}:`", e.name)).thumb(Some(url(e.id.get(), e.animated))).fields(by(s, actor.as_ref(), "By", Reason::Show, None))); + } + for (id, name) in before.iter().filter(|b| !after.iter().any(|e| e.id.get() == b.0)) { + let actor = s.audit.find(s, guild, Query::new("emoji", &[A::EmojiDelete]).target(*id)).await; + lg().send(s, guild, LogEntry::new("emoji_sticker", "Emoji removed", &format!("`:{name}:`")).thumb(Some(url(*id, false))).fields(by(s, actor.as_ref(), "By", Reason::Show, None))); + } + for e in &after { + if let Some((_, old)) = before.iter().find(|b| b.0 == e.id.get()).filter(|b| b.1 != e.name) { + let actor = s.audit.find(s, guild, Query::new("emoji", &[A::EmojiUpdate]).target(e.id.get())).await; + let shown = format!("<{}:{}:{}>", if e.animated { "a" } else { "" }, e.name, e.id); + lg().send(s, guild, LogEntry::new("emoji_sticker", "Emoji renamed", &format!("{shown} `:{old}:` → `:{}:`", e.name)).thumb(Some(url(e.id.get(), e.animated))).fields(by(s, actor.as_ref(), "By", Reason::Show, None))); + } + } +} + +async fn stickers_update(s: &Arc, guild: Id, before: Vec<(u64, String, String)>, after: Vec) { + if !lg().enabled(s, guild, "emoji_sticker") { + return; + } + let url = |id: u64| format!("https://cdn.discordapp.com/stickers/{id}.png"); + for st in after.iter().filter(|x| !before.iter().any(|b| b.0 == x.id.get())) { + let actor = s.audit.find(s, guild, Query::new("sticker", &[A::StickerCreate]).target(st.id.get())).await; + lg().send(s, guild, LogEntry::new("emoji_sticker", "Sticker added", &format!("**{}**", escape(&st.name))).thumb(Some(url(st.id.get()))).fields(by(s, actor.as_ref(), "By", Reason::Show, None))); + } + for (id, name, _) in before.iter().filter(|b| !after.iter().any(|x| x.id.get() == b.0)) { + let actor = s.audit.find(s, guild, Query::new("sticker", &[A::StickerDelete]).target(*id)).await; + lg().send(s, guild, LogEntry::new("emoji_sticker", "Sticker removed", &format!("**{}**", escape(name))).fields(by(s, actor.as_ref(), "By", Reason::Show, None))); + } + for st in &after { + if let Some((_, old_name, old_desc)) = before.iter().find(|b| b.0 == st.id.get()) { + let desc = st.description.clone().unwrap_or_default(); + if *old_name != st.name || *old_desc != desc { + let actor = s.audit.find(s, guild, Query::new("sticker", &[A::StickerUpdate]).target(st.id.get())).await; + let mut fields = vec![("Name".to_string(), format!("`{old_name}` → `{}`", st.name)), ("Description".to_string(), format!("`{old_desc}` → `{desc}`"))]; + fields.extend(by(s, actor.as_ref(), "By", Reason::Show, None)); + lg().send(s, guild, LogEntry::new("emoji_sticker", "Sticker updated", &format!("**{}**", escape(&st.name))).thumb(Some(url(st.id.get()))).fields(fields)); + } + } + } +} + +// ---- server -------------------------------------------------------------------------------- + +async fn guild_update(s: &Arc, before: Option, after: twilight_model::guild::PartialGuild) { + let Some(before) = before else { return }; + let guild = after.id; + if !lg().enabled(s, guild, "server") { + return; + } + let (icon, banner, splash) = (after.icon.map(|i| i.to_string()), after.banner.map(|i| i.to_string()), after.splash.map(|i| i.to_string())); + let mut changes = vec![]; + if before.name != after.name { + changes.push(("Name".to_string(), format!("`{}` → `{}`", before.name, after.name))); + } + if before.description != after.description { + changes.push(("Description".into(), format!("{} → {}", quoted(&before.description), quoted(&after.description)))); + } + for (label, b, a) in [("Icon", &before.icon, &icon), ("Banner", &before.banner, &banner), ("Invite splash", &before.splash, &splash)] { + if b != a { + changes.push((label.into(), if a.is_some() { "updated" } else { "removed" }.into())); + } + } + if before.vanity != after.vanity_url_code { + changes.push(("Vanity URL".into(), format!("{} → {}", quoted(&before.vanity), quoted(&after.vanity_url_code)))); + } + let tier = format!("{:?}", after.premium_tier); + if before.tier != tier { + changes.push(("Boost level".into(), format!("{} → {tier}", before.tier))); + } + let (ver, filter) = (format!("{:?}", after.verification_level), format!("{:?}", after.explicit_content_filter)); + if before.verification != ver { + changes.push(("Verification".into(), format!("{} → {ver}", before.verification))); + } + if before.filter != filter { + changes.push(("Content filter".into(), format!("{} → {filter}", before.filter))); + } + if before.owner != after.owner_id { + changes.push(("Owner".into(), format!("<@{}> → <@{}>", before.owner, after.owner_id))); + } + if changes.is_empty() { + return; + } + let mut fields = changes.clone(); + if changes.iter().any(|(n, _)| n != "Boost level") { + let actor = s.audit.find(s, guild, Query::new("guild", &[A::GuildUpdate]).target(guild.get())).await; + fields.extend(by(s, actor.as_ref(), "By", Reason::Show, None)); + } + let thumb = after.icon.map(|i| format!("https://cdn.discordapp.com/icons/{guild}/{i}.png")); + lg().send(s, guild, LogEntry::new("server", "Server updated", "").fields(fields).thumb(thumb)); +} + +fn sched_create(s: &Arc, e: twilight_model::guild::scheduled_event::GuildScheduledEvent) { + let creator = e.creator_id.map(|c| vec![("Created by".to_string(), who(s, Some(c)))]).unwrap_or_default(); + let place = e.channel_id.map_or_else(|| escape(e.entity_metadata.as_ref().and_then(|m| m.location.as_deref()).unwrap_or("External")), |c| format!("<#{c}>")); + let url = format!("https://discord.com/events/{}/{}", e.guild_id, e.id); + let images = e.image.map(|i| vec![format!("https://cdn.discordapp.com/guild-events/{}/{i}.png", e.id)]).unwrap_or_default(); + let mut fields = vec![ + ("Where".to_string(), place), + ("Starts".to_string(), dt(e.scheduled_start_time.as_secs(), 'F')), + ("Ends".to_string(), e.scheduled_end_time.map_or("—".into(), |t| dt(t.as_secs(), 'F'))), + ]; + fields.extend(creator); + lg().send(s, e.guild_id, LogEntry::new("server", "Event created", &format!("**{}** · [View](<{url}>)", escape(&e.name))).fields(fields).images(images)); +} + +async fn sched_delete(s: &Arc, e: twilight_model::guild::scheduled_event::GuildScheduledEvent) { + if !lg().enabled(s, e.guild_id, "server") { + return; + } + let actor = s.audit.find(s, e.guild_id, Query::new("event", &[A::GuildScheduledEventDelete]).target(e.id.get())).await; + lg().send(s, e.guild_id, LogEntry::new("server", "Event deleted", &format!("**{}**", escape(&e.name))).fields(by(s, actor.as_ref(), "By", Reason::Show, None))); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn channel_kinds_are_readable() { + assert_eq!(kind_name(twilight_model::channel::ChannelType::GuildText), "Guild Text"); + } + + #[test] + fn permission_text_lists_both_sides() { + let t = overwrite_text(Permissions::CONNECT, Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS); + assert!(t.contains("✅ connect") && t.contains("send messages") && t.contains("add reactions")); + assert_eq!(overwrite_text(Permissions::empty(), Permissions::empty()), "✅ —\n❌ —"); + } +} diff --git a/src/commands/logs/mod.rs b/src/commands/logs/mod.rs new file mode 100644 index 0000000..b047731 --- /dev/null +++ b/src/commands/logs/mod.rs @@ -0,0 +1,629 @@ +//! Server event logging (`/logging`). +//! +//! Events are rendered as Components V2 cards and posted through a "Dezio Logger" webhook in each log +//! channel. Bursts are batched: entries arriving within ~1.5 s share a message, so a purge or a mass +//! role change can't hit rate limits. Without Manage Webhooks the bot falls back to posting as itself. +//! +//! "Who did it" comes from the audit log (see audit.rs): bans, kicks, timeouts, deleted messages, +//! role/channel/emoji changes and voice disconnects all name the moderator, and actions Dezio performs +//! for someone credit that person. Joins show which invite was used. +//! +//! Config: data/logging.json — {guild_id: {log_type: channel_id}}. +use crate::audit::{now, Actor}; +use crate::cmd::{Command, Ctx}; +use crate::interact; +use crate::paths; +use crate::state::State; +use crate::storage::JsonStore; +use crate::ui::{self, button, cost, escape, select_menu, select_option, truncate, Card, BLURPLE}; +use anyhow::Result; +use base64::Engine as _; +use futures::FutureExt; +use serde_json::{json, Value}; +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Duration; +use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_model::channel::message::component::{ButtonStyle, Component, SelectDefaultValue, SelectMenu, SelectMenuType}; +use twilight_model::channel::message::{AllowedMentions, MessageFlags}; +use twilight_model::channel::ChannelType; +use twilight_model::guild::Permissions; +use twilight_model::http::attachment::Attachment; +use twilight_model::id::marker::{ChannelMarker, GuildMarker, UserMarker, WebhookMarker}; +use twilight_model::id::Id; + +pub mod events; + +pub const WEBHOOK_NAME: &str = "Dezio Logger"; +const MAX_COMPONENTS: usize = 40; +const MAX_TEXT: usize = 3900; + +/// (key, emoji, label, colour) +pub const LOG_TYPES: &[(&str, &str, &str, u32)] = &[ + ("member", "👤", "Member", 0x3498DB), + ("server", "🏠", "Server", 0x2ECC71), + ("voice", "🔊", "Voice", 0x9B59B6), + ("message", "💬", "Message", 0xE67E22), + ("join_leave", "🚪", "Join/Leave", 0xF1C40F), + ("moderation", "🛡️", "Moderation", 0xE74C3C), + ("emoji_sticker", "😃", "Emoji & Stickers", 0x1ABC9C), + ("channel", "📺", "Channel", 0x95A5A6), + ("role", "🎭", "Role", 0x8E44AD), + ("invite", "📩", "Invite", 0x16A085), +]; + +fn log_type(key: &str) -> (&'static str, &'static str, u32) { + LOG_TYPES.iter().find(|t| t.0 == key).map_or(("📝", "Log", BLURPLE), |t| (t.1, t.2, t.3)) +} + +// ---- log entries --------------------------------------------------------------------------- + +#[derive(Clone, Default)] +pub struct Author { + pub name: String, + pub id: u64, + pub avatar: String, +} + +#[derive(Clone)] +pub struct LogEntry { + pub kind: &'static str, + pub title: String, + pub description: String, + pub fields: Vec<(String, String)>, + pub author: Option, + pub thumbnail: Option, + pub images: Vec, + pub file: Option<(String, Vec)>, + pub created: u64, +} + +impl LogEntry { + pub fn new(kind: &'static str, title: &str, description: &str) -> Self { + Self { kind, title: title.into(), description: description.into(), fields: vec![], author: None, thumbnail: None, + images: vec![], file: None, created: now() as u64 } + } + pub fn field(mut self, k: &str, v: impl Into) -> Self { + self.fields.push((k.to_string(), v.into())); + self + } + pub fn fields(mut self, f: Vec<(String, String)>) -> Self { + self.fields.extend(f); + self + } + pub fn author(mut self, a: Option) -> Self { + self.author = a; + self + } + pub fn thumb(mut self, url: Option) -> Self { + self.thumbnail = url; + self + } + pub fn images(mut self, i: Vec) -> Self { + self.images = i; + self + } + + pub fn render(&self) -> Component { + let (emoji, _, colour) = log_type(self.kind); + let mut head = format!("**{emoji} {}**", self.title); + if !self.description.is_empty() { + head.push('\n'); + head.push_str(&truncate(&self.description, 1200)); + } + let thumb = self.thumbnail.clone().or_else(|| self.author.as_ref().map(|a| a.avatar.clone())) + .filter(|t| !t.split('?').next().unwrap_or("").ends_with(".json")); // Lottie stickers aren't images + let mut card = Card::new(Some(colour)).header(&[&head], thumb.as_deref()); + if !self.fields.is_empty() { + let lines: Vec = self.fields.iter().map(|(name, value)| { + let value = truncate(value, 1000); + if value.contains('\n') || value.chars().count() > 60 { format!("**{name}**\n{value}") } else { format!("**{name}:** {value}") } + }).collect(); + card = card.text(&truncate(&lines.join("\n"), 2400)); // keeps one entry well inside a message's limits + } + if !self.images.is_empty() { + let urls: Vec<&str> = self.images.iter().take(10).map(String::as_str).collect(); + card = card.gallery(&urls); + } + if let Some((name, _)) = &self.file { + card = card.push(ui::file_display(name)); + } + let mut footer = vec![]; + if let Some(a) = &self.author { + footer.push(format!("{} · ID {}", escape(&a.name), a.id)); + } + footer.push(format!("", self.created)); + card.footer(&footer.join(" · ")).build() + } +} + +// ---- the logger ---------------------------------------------------------------------------- + +#[derive(Clone)] +struct Hook { + id: Id, + token: String, +} + +pub struct Logger { + store: Arc, + queues: Mutex, Vec>>, + flushers: Mutex>>, + /// None = post as the bot + hooks: Mutex, Option>>, + drafts: Mutex, HashSet)>>, + pub voice_since: Mutex, Id), f64>>, + pub recent_bans: Mutex, Id), f64>>, + pub invites: Mutex, HashMap)>>>, + pub rule_names: Mutex>, + pub automod_pending: Mutex>>, + avatar: OnceLock>, +} + +pub fn logger() -> &'static Logger { + static L: OnceLock = OnceLock::new(); + L.get_or_init(|| Logger { + store: JsonStore::open(paths::data(&["logging.json"])), + queues: Default::default(), + flushers: Default::default(), + hooks: Default::default(), + drafts: Default::default(), + voice_since: Default::default(), + recent_bans: Default::default(), + invites: Default::default(), + rule_names: Default::default(), + automod_pending: Default::default(), + avatar: OnceLock::new(), + }) +} + +impl Logger { + /// {type: channel} for one server (only valid entries). + pub fn guild_config(&self, guild: Id) -> HashMap { + let raw = self.store.get(guild).unwrap_or(Value::Null); + LOG_TYPES.iter().filter_map(|t| Some((t.0.to_string(), raw[t.0].as_u64()?))).collect() + } + + /// Set (or clear, with None) the channel of each given log type — the dashboard's write path. + pub fn set_channels(&self, guild: Id, wanted: &[(String, Option)]) { + self.store.update(|all| { + let g = all.entry(guild.to_string()).or_insert_with(|| json!({})); + let g = g.as_object_mut().unwrap(); + for (k, v) in wanted { + match v { + Some(c) => { + g.insert(k.clone(), json!(c)); + } + None => { + g.shift_remove(k); + } + } + } + if g.is_empty() { + all.shift_remove(&guild.to_string()); + } + }); + } + + pub fn apply(&self, guild: Id, channel: Id, selected: &HashSet) { + self.store.update(|all| { + let g = all.entry(guild.to_string()).or_insert_with(|| json!({})); + let g = g.as_object_mut().unwrap(); + for t in LOG_TYPES { + if selected.contains(t.0) { + g.insert(t.0.to_string(), json!(channel.get())); + } else if g.get(t.0).and_then(Value::as_u64) == Some(channel.get()) { + g.shift_remove(t.0); + } + } + }); + } + + pub fn channel_for(&self, state: &State, guild: Id, kind: &str) -> Option> { + let id = self.guild_config(guild).get(kind).copied().and_then(Id::new_checked)?; + state.cache.channel(id).map(|_| id) + } + + pub fn enabled(&self, state: &State, guild: Id, kind: &str) -> bool { + self.channel_for(state, guild, kind).is_some() + } + + /// Queue an entry for the channel that receives this kind of log. + pub fn send(&self, state: &Arc, guild: Id, entry: LogEntry) { + let Some(channel) = self.channel_for(state, guild, entry.kind) else { return }; + self.enqueue(state, channel, entry); + } + + pub fn enqueue(&self, state: &Arc, channel: Id, entry: LogEntry) { + { + let mut q = self.queues.lock().unwrap(); + let queue = q.entry(channel).or_default(); + if queue.len() >= 250 { + queue.remove(0); // a flood we can't keep up with; keep the newest + } + queue.push(entry); + } + if self.flushers.lock().unwrap().insert(channel) { + let state = state.clone(); + tokio::spawn(async move { logger().flusher(state, channel).await }); + } + } + + async fn flusher(&self, state: Arc, channel: Id) { + let mut delay = 1.5; // gather a burst into one message + loop { + tokio::time::sleep(Duration::from_secs_f64(delay)).await; + let batch = { + let mut q = self.queues.lock().unwrap(); + match q.get_mut(&channel).filter(|v| !v.is_empty()) { + Some(queue) => Self::take_batch(queue), + None => { + q.remove(&channel); + self.flushers.lock().unwrap().remove(&channel); + return; + } + } + }; + self.deliver(&state, channel, batch).await; + delay = 0.5; + } + } + + fn take_batch(queue: &mut Vec) -> Vec<(LogEntry, Component)> { + let (mut batch, mut components, mut text) = (vec![], 0, 0); + while !queue.is_empty() { + let card = queue[0].render(); + let (c, t) = cost(&card); + let has_file = queue[0].file.is_some(); + if !batch.is_empty() && (components + c > MAX_COMPONENTS || text + t > MAX_TEXT || has_file) { + break; + } + batch.push((queue.remove(0), card)); + components += c; + text += t; + if has_file { + break; // files go alone + } + } + batch + } + + fn avatar_uri(&self) -> Option { + self.avatar + .get_or_init(|| { + let bytes = std::fs::read(paths::asset(&["images", "logger.png"])).ok()?; + Some(format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))) + }) + .clone() + } + + /// The channel messages go to (a thread's parent hosts the webhook) and whether it is a thread. + fn host(state: &State, channel: Id) -> (Id, bool) { + match state.cache.channel(channel) { + Some(c) if matches!(c.kind, ChannelType::PublicThread | ChannelType::PrivateThread | ChannelType::AnnouncementThread) => { + (c.parent_id.unwrap_or(channel), true) + } + _ => (channel, false), + } + } + + async fn webhook(&self, state: &State, host: Id) -> Option { + if let Some(h) = self.hooks.lock().unwrap().get(&host) { + return h.clone(); + } + let hook = self.find_or_create_webhook(state, host).await; + self.hooks.lock().unwrap().insert(host, hook.clone()); + hook + } + + async fn find_or_create_webhook(&self, state: &State, host: Id) -> Option { + let guild = state.cache.channel(host)?.guild_id?; + if !state.guild_permissions(guild, state.bot_id()).contains(Permissions::MANAGE_WEBHOOKS) { + return None; + } + let existing = state.http.channel_webhooks(host).await.ok()?.models().await.ok()?; + let mine = existing.into_iter().find(|w| w.name.as_deref() == Some(WEBHOOK_NAME) && w.user.as_ref().is_some_and(|u| u.id == state.bot_id())); + let hook = match mine { + Some(h) => h, + None => { + let mut req = state.http.create_webhook(host, WEBHOOK_NAME); + let uri = self.avatar_uri(); + if let Some(u) = uri.as_deref() { + req = req.avatar(u); + } + req.await.ok()?.model().await.ok()? + } + }; + Some(Hook { id: hook.id, token: hook.token? }) + } + + async fn deliver(&self, state: &Arc, channel: Id, batch: Vec<(LogEntry, Component)>) { + let cards: Vec = batch.iter().map(|(_, c)| c.clone()).collect(); + let attachments: Vec = batch.iter().filter_map(|(e, _)| e.file.as_ref()).enumerate() + .map(|(i, (name, bytes))| Attachment::from_bytes(name.clone(), bytes.clone(), i as u64)).collect(); + let (host, is_thread) = Self::host(state, channel); + let no_pings = AllowedMentions::default(); + for _attempt in 0..2 { + let hook = self.webhook(state, host).await; + let result = match &hook { + Some(h) => { + let mut req = state.http.execute_webhook(h.id, &h.token).username(WEBHOOK_NAME) + .flags(MessageFlags::IS_COMPONENTS_V2).components(&cards).allowed_mentions(Some(&no_pings)); + if is_thread { + req = req.thread_id(channel); + } + if !attachments.is_empty() { + req = req.attachments(&attachments); + } + req.await.map(|_| ()) + } + None => { + let mut req = state.http.create_message(channel).flags(MessageFlags::IS_COMPONENTS_V2).components(&cards) + .allowed_mentions(Some(&no_pings)); + if !attachments.is_empty() { + req = req.attachments(&attachments); + } + req.await.map(|_| ()) + } + }; + match result { + Ok(()) => return, + Err(e) => { + let status = match e.kind() { + twilight_http::error::ErrorType::Response { status, .. } => status.get(), + _ => 0, + }; + if status == 404 && hook.is_some() { + self.hooks.lock().unwrap().remove(&host); // the webhook was deleted; make a new one + } else if status == 403 { + if hook.is_none() { + return; // can't post here at all + } + self.hooks.lock().unwrap().insert(host, None); // fall back to posting as the bot + } else { + tracing::warn!("couldn't deliver {} log entries to {channel}: {e}", batch.len()); + return; + } + } + } + } + } + + pub fn forget_webhook(&self, channel: Id) { + self.hooks.lock().unwrap().remove(&channel); + } +} + +// ---- helpers used by the event handlers ---------------------------------------------------- + +/// "Who": a mention plus the username when known. +pub fn who(state: &State, user: Option>) -> String { + match user { + None => "Unknown".into(), + Some(id) => match state.cache.user(id) { + Some(u) => format!("<@{id}> (`{}`)", u.name), + None => format!("<@{id}>"), + }, + } +} + +#[derive(Clone, Copy, PartialEq)] +pub enum Reason { + Show, + Always, + Never, +} + +/// 'By' (+ 'Reason') fields. `Always` shows "No reason given" too. Changes people made to themselves +/// get no 'By' unless a bot did it for them. +pub fn by(state: &State, actor: Option<&Actor>, label: &str, reason: Reason, self_id: Option>) -> Vec<(String, String)> { + let Some(a) = actor else { return vec![] }; + let Some(uid) = a.user_id else { return vec![] }; + let mut fields = vec![]; + if self_id == Some(uid) { + if !a.via { + return vec![]; + } + fields.push((label.to_string(), "themselves · via Dezio".to_string())); + } else { + fields.push((label.to_string(), format!("{}{}", who(state, Some(uid)), if a.via { " · via Dezio" } else { "" }))); + } + match (&a.reason, reason) { + (Some(r), Reason::Show | Reason::Always) => fields.push(("Reason".into(), escape(&truncate(r, 500)))), + (None, Reason::Always) => fields.push(("Reason".into(), "No reason given".into())), + _ => {} + } + fields +} + +/// Shown when we can't read the audit log. +pub fn unknown(state: &State, guild: Id) -> Vec<(String, String)> { + if crate::audit::AuditFeed::can_read(state, guild) { + vec![] + } else { + vec![("By".into(), "Unknown — give me **View Audit Log** to see who".into())] + } +} + +pub fn fmt_secs(seconds: f64) -> String { + let s = seconds as u64; + let (d, r) = (s / 86400, s % 86400); + let (h, r) = (r / 3600, r % 3600); + let (m, sec) = (r / 60, r % 60); + let mut parts: Vec = [(d, "d"), (h, "h"), (m, "m")].iter().filter(|(v, _)| *v > 0).map(|(v, u)| format!("{v}{u}")).collect(); + if sec > 0 || parts.is_empty() { + parts.push(format!("{sec}s")); + } + parts.join(" ") +} + +pub fn author_of(state: &State, id: Id) -> Option { + state.cache.user(id).map(|u| Author { name: u.name.clone(), id: id.get(), avatar: ui::avatar_url(id, u.avatar.as_ref()) }) +} + +pub fn author_from_user(u: &twilight_model::user::User) -> Author { + Author { name: u.name.clone(), id: u.id.get(), avatar: ui::avatar_url(u.id, u.avatar.as_ref()) } +} + +pub fn dt(unix: i64, style: char) -> String { + format!("") +} + +// ---- setup panel (/logging) ---------------------------------------------------------------- + +fn setup_card(state: &State, guild: Id, channel: Id, selected: &HashSet, done: Option<&str>) -> Component { + let config = logger().guild_config(guild); + let mut card = Card::new(Some(BLURPLE)).text("### 📝 Logging setup\nPick a log channel, then the events it should receive."); + if let Some(done) = done { + return card.separator(true, false).text(done).build(); + } + let channel_select = SelectMenu { + id: None, + channel_types: Some(vec![ChannelType::GuildText, ChannelType::GuildAnnouncement, ChannelType::GuildVoice, ChannelType::PublicThread, ChannelType::PrivateThread]), + custom_id: "log:ch:x".into(), + default_values: Some(vec![SelectDefaultValue::Channel(channel)]), + disabled: false, + kind: SelectMenuType::Channel, + max_values: Some(1), + min_values: Some(1), + options: None, + placeholder: Some("Log channel".into()), + required: None, + }; + let options: Vec<_> = LOG_TYPES.iter().map(|t| select_option(t.2, t.0, t.1, "", selected.contains(t.0))).collect(); + let mut types = select_menu("log:types:x", "Events to log here", options); + types.min_values = Some(0); + types.max_values = Some(LOG_TYPES.len() as u8); + card = card.select(channel_select).select(types); + let lines: Vec = LOG_TYPES.iter().map(|t| { + if selected.contains(t.0) { + format!("✅ {} {} → <#{channel}>", t.1, t.2) + } else if let Some(target) = config.get(t.0) { + format!("↪️ {} {} → <#{target}>", t.1, t.2) + } else { + format!("▫️ {} {} — off", t.1, t.2) + } + }).collect(); + card = card.separator(true, false).text(&lines.join("\n")).footer("✅ this channel · ↪️ another channel · ▫️ off"); + let me = state.guild_permissions(guild, state.bot_id()); + let mut missing = vec![]; + if !me.contains(Permissions::VIEW_AUDIT_LOG) { + missing.push("**View Audit Log** — to show *who* banned, kicked, deleted or changed things"); + } + if !me.contains(Permissions::MANAGE_GUILD) { + missing.push("**Manage Server** — to show which invite new members used"); + } + if !missing.is_empty() { + card = card.text(&format!("⚠️ I'm missing:\n{}", missing.iter().map(|m| format!("• {m}")).collect::>().join("\n"))); + } + card.row(vec![ + ui::emoji_button("log:save:x", Some("Save"), "💾", false), + button("log:all:x", "Select all", ButtonStyle::Secondary), + button("log:cancel:x", "Cancel", ButtonStyle::Danger), + ]).build() +} + +pub fn commands() -> Vec { + vec![Command::new("logging", "server", "Pick a log channel and which server events it receives", |c| logging(c).boxed()) + .perm(Permissions::MANAGE_GUILD)] +} + +async fn logging(ctx: Arc) -> Result<()> { + let guild = ctx.guild()?; + let channel = ctx.channel_id; + let selected: HashSet = logger().guild_config(guild).into_iter().filter(|(_, c)| *c == channel.get()).map(|(k, _)| k).collect(); + let card = setup_card(&ctx.state, guild, channel, &selected, None); + ctx.reply_private(card).await?; + // the draft is keyed by the panel's message, which we only learn from the first click; remember by user too + logger().drafts.lock().unwrap().insert(ctx.user_id.get(), (channel, selected)); + Ok(()) +} + +/// The setup panel's menus and buttons: `log::x`. +pub async fn on_component(state: &Arc, i: &Interaction) { + let Some(InteractionData::MessageComponent(d)) = i.data.as_ref() else { return }; + let action = d.custom_id.split(':').nth(1).unwrap_or(""); + let (Some(guild), Some(user)) = (i.guild_id, i.author()) else { return }; + if !interact::can(i, Permissions::MANAGE_GUILD) { + return interact::private_text(state, i, "❌ You need **Manage Server**.").await; + } + let lg = logger(); + let mut draft = lg.drafts.lock().unwrap().get(&user.id.get()).cloned(); + let (mut channel, mut selected) = draft.take().unwrap_or_else(|| (i.channel.as_ref().map_or(Id::new(1), |c| c.id), HashSet::new())); + match action { + "ch" => { + channel = d.values.first().and_then(|v| v.parse().ok()).and_then(Id::new_checked).unwrap_or(channel); + selected = lg.guild_config(guild).into_iter().filter(|(_, c)| *c == channel.get()).map(|(k, _)| k).collect(); + } + "types" => selected = d.values.iter().cloned().collect(), + "all" => selected = LOG_TYPES.iter().map(|t| t.0.to_string()).collect(), + "cancel" => { + lg.drafts.lock().unwrap().remove(&user.id.get()); + return interact::update(state, i, setup_card(state, guild, channel, &selected, Some("❌ Cancelled — nothing was changed."))).await; + } + "save" => { + let perms = state.guild_permissions(guild, state.bot_id()); + if state.cache.channel(channel).is_none() { + return interact::private_text(state, i, "❌ I can't see that channel.").await; + } + if !(perms.contains(Permissions::MANAGE_WEBHOOKS) || perms.contains(Permissions::SEND_MESSAGES)) { + return interact::private_text(state, i, &format!("❌ I need **Manage Webhooks** (or at least **Send Messages**) in <#{channel}>.")).await; + } + lg.apply(guild, channel, &selected); + lg.forget_webhook(channel); + let names = LOG_TYPES.iter().filter(|t| selected.contains(t.0)).map(|t| t.2).collect::>().join(", "); + let names = if names.is_empty() { "nothing".to_string() } else { names }; + let mut done = format!("✅ Saved. <#{channel}> now logs: **{names}**."); + if !perms.contains(Permissions::MANAGE_WEBHOOKS) { + done.push_str("\n-# Tip: give me Manage Webhooks so logs post under the Dezio Logger name."); + } + lg.drafts.lock().unwrap().remove(&user.id.get()); + interact::update(state, i, setup_card(state, guild, channel, &selected, Some(&done))).await; + if !selected.is_empty() { + let e = LogEntry::new("server", "Logging enabled", &format!("This channel now receives: **{names}**")).author(Some(author_from_user(user))); + lg.enqueue(state, channel, e); + if selected.contains("join_leave") { + events::snapshot_invites(state, guild).await; + } + } + return; + } + _ => return, + } + lg.drafts.lock().unwrap().insert(user.id.get(), (channel, selected.clone())); + interact::update(state, i, setup_card(state, guild, channel, &selected, None)).await; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn durations() { + assert_eq!(fmt_secs(0.0), "0s"); + assert_eq!(fmt_secs(59.0), "59s"); + assert_eq!(fmt_secs(3661.0), "1h 1m 1s"); + assert_eq!(fmt_secs(90000.0), "1d 1h"); + } + + #[test] + fn entry_fits_limits_even_when_huge() { + let mut e = LogEntry::new("message", "Message deleted", &"x".repeat(5000)); + for i in 0..30 { + e = e.field(&format!("F{i}"), "y".repeat(2000)); + } + e.images = (0..20).map(|i| format!("https://x/{i}.png")).collect(); + let (c, t) = cost(&e.render()); + assert!(c <= MAX_COMPONENTS, "{c} components"); + assert!(t <= MAX_TEXT, "{t} chars"); + } + + #[test] + fn batches_respect_limits() { + let mut q: Vec = (0..60).map(|i| LogEntry::new("member", &format!("T{i}"), "d").field("a", "b")).collect(); + let first = Logger::take_batch(&mut q); + assert!(!first.is_empty() && q.len() + first.len() == 60); + let comps: usize = first.iter().map(|(_, c)| cost(c).0).sum(); + assert!(comps <= MAX_COMPONENTS); + } +} diff --git a/src/commands/media/download/flow.rs b/src/commands/media/download/flow.rs new file mode 100644 index 0000000..5888f8f --- /dev/null +++ b/src/commands/media/download/flow.rs @@ -0,0 +1,492 @@ +//! The download pipeline: audio, video (with convert-while-downloading) and image posts. +use super::job::{DlError, Job}; +use super::plan::*; +use super::tools::{self, Media}; +use serde_json::Value; +use std::future::Future; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +const NET_RETRIES: u32 = 2; + +pub struct VideoResult { + pub path: PathBuf, + pub title: String, + pub height: i64, + pub duration: Option, + pub codec: String, + pub size: u64, + pub url: String, +} + +pub struct AudioResult { + pub path: PathBuf, + pub title: String, + pub size: u64, + pub kbps: i64, +} + +pub struct GalleryResult { + pub images: Vec, + pub videos: Vec, + pub title: String, + pub url: String, + pub skipped: usize, +} + +pub enum Outcome { + Video(VideoResult), + Audio(AudioResult), + Gallery(GalleryResult), +} + +/// Retry a yt-dlp step once when the connection hiccups (yt-dlp has its own inner retries too). +async fn net_retry(job: &Job, mut f: F) -> Result +where + F: FnMut() -> Fut, + Fut: Future>, +{ + let mut attempt = 1; + loop { + match f().await { + Err(DlError::Ytdlp(raw)) => { + let low = clean(&raw).to_lowercase(); + if IMAGE_ONLY_HINTS.iter().any(|h| low.contains(h)) { + return Err(DlError::Ytdlp(raw)); + } + if attempt < NET_RETRIES && TRANSIENT_HINTS.iter().any(|h| low.contains(h)) { + job.with(|p| p.detail = format!("Connection hiccup - retrying ({attempt}/{})…", NET_RETRIES - 1)); + tokio::time::sleep(Duration::from_secs(3 * attempt as u64)).await; + attempt += 1; + continue; + } + return Err(DlError::Ytdlp(raw)); + } + other => return other, + } + } +} + +pub async fn pipeline(web: &reqwest::Client, job: &Job, cap: i64, workdir: &Path, cookie: Option<&Path>) -> Result { + job.set("Fetching info", "🔎", "", true); + if job.audio { + return audio_flow(job, workdir, cookie).await.map(Outcome::Audio); + } + match video_flow(web, job, cap, workdir, cookie).await { + Ok(v) => Ok(Outcome::Video(v)), + Err(DlError::ImageOnly(why)) => { + tracing::info!("falling back to gallery-dl ({}): {why}", job.url); + gallery_flow(job, workdir, cookie).await.map(Outcome::Gallery) + } + Err(DlError::Ytdlp(raw)) if IMAGE_ONLY_HINTS.iter().any(|h| clean(&raw).to_lowercase().contains(h)) => match gallery_flow(job, workdir, cookie).await { + Ok(g) => Ok(Outcome::Gallery(g)), + Err(DlError::User(..)) => Err(DlError::Ytdlp(raw)), // show the original yt-dlp error instead + Err(other) => Err(other), + }, + Err(e) => Err(e), + } +} + +fn is_live(info: &Value) -> bool { + info.get("is_live").and_then(Value::as_bool) == Some(true) || matches!(str_of(info, "live_status"), Some("is_live" | "is_upcoming")) +} + +fn too_long(what: &str, d: f64) -> DlError { + DlError::user("Too long", format!("That {what} is {} long; the limit is {}.", fmt_dur(Some(d)), fmt_dur(Some(MAX_DURATION_SECONDS)))) +} + +fn size_of(p: &Path) -> u64 { + std::fs::metadata(p).map(|m| m.len()).unwrap_or(0) +} + +async fn audio_flow(job: &Job, workdir: &Path, cookie: Option<&Path>) -> Result { + if !tools::have("ffmpeg") { + return Err(DlError::user("ffmpeg missing", "Audio mode needs ffmpeg installed on the bot's host.")); + } + let info = net_retry(job, || tools::probe(job, &job.url, cookie, false)).await?; + let title = str_of(&info, "title").or_else(|| str_of(&info, "id")).unwrap_or("Audio").to_string(); + job.set_title(&title); + if is_live(&info) { + return Err(DlError::user("Live stream", "Live streams can't be downloaded.")); + } + let dur = info.get("duration").and_then(Value::as_f64); + if let Some(d) = dur.filter(|d| *d > MAX_DURATION_SECONDS) { + return Err(too_long("audio", d)); + } + job.set("Downloading audio", "🎧", "Best available audio stream", true); + job.reset_streams(); + let audio_dir = workdir.join("audio"); + let src = net_retry(job, || tools::download_audio(job, &job.url, &audio_dir, cookie)).await?; + let probe = tools::inspect(&src).await; + let duration = probe.as_ref().map(|m| m.duration).filter(|d| *d > 0.0).or(dur); + let mut kbps = AUDIO_KBPS; + let budget = job.limit as f64 * SAFETY_MARGIN; + if let Some(d) = duration { + if d * kbps as f64 * 1000.0 / 8.0 > budget { + kbps = (budget * 8.0 / d / 1000.0) as i64; + if kbps < 24 { + return Err(DlError::TooLarge); + } + } + } + let dst = workdir.join(format!("{}.{AUDIO_EXT}", slug(&title, "audio"))); + job.set("Encoding Opus", "🎛️", &format!("{kbps} kbps{}", if kbps != AUDIO_KBPS { " (lowered to fit Discord's limit)" } else { "" }), true); + tools::encode_opus(job, &src, &dst, kbps, duration).await?; + let size = size_of(&dst); + if size > job.limit { + return Err(DlError::TooLarge); + } + Ok(AudioResult { path: dst, title, size, kbps }) +} + +async fn video_flow(web: &reqwest::Client, job: &Job, cap: i64, workdir: &Path, cookie: Option<&Path>) -> Result { + let mut info = net_retry(job, || tools::probe(job, &job.url, cookie, true)).await?; + let title = str_of(&info, "title").or_else(|| str_of(&info, "id")).unwrap_or("Video").to_string(); + job.set_title(&title); + if is_live(&info) { + return Err(DlError::user("Live stream", "Live streams can't be downloaded.")); + } + let dur = info.get("duration").and_then(Value::as_f64); + if let Some(d) = dur.filter(|d| *d > MAX_DURATION_SECONDS) { + return Err(too_long("video", d)); + } + job.set("Checking sizes", "📏", "Picking a version that fits Discord", true); + tools::probe_sizes(web, &mut info, cap).await; + let limit = job.limit as f64; + let mut banned: Vec = Vec::new(); + let mut found: Option<(PathBuf, Option, bool, i64, bool)> = None; // (path, media, compressed, height, native) + for attempt in 0..12 { + let plan = plan_download(&info, cap, job.limit, &banned); + tracing::info!("plan: stream={} {}p est={:?} fallback={} native={} banned={banned:?}", plan.sig, plan.height, plan.est, plan.fallback, plan.native); + if !banned.is_empty() && plan.sig.is_empty() { + return Err(DlError::TooLarge); + } + if !plan.fallback && plan.est.is_some_and(|e| e as f64 > limit * SAFETY_MARGIN) && dur.is_some_and(|d| d * MIN_TOTAL_BPS / 8.0 > limit * 0.94) { + return Err(DlError::user("Too long to fit", format!("A {} video can't be squeezed under **{}** at watchable quality. Nothing was downloaded.", fmt_dur(dur), fmt_bytes(limit)))); + } + let first = plan.selector.split('/').next().unwrap_or(""); + job.with(|p| { + p.budget = if plan.fallback { Job::budget_for(job.limit) } else { 0.0 }; + p.reserve = if first.contains('+') { dur.unwrap_or(0.0) * 16_000.0 } else { 0.0 }; + }); + job.reset_streams(); + job.set("Downloading", "⬇️", &format!("Up to {}p{}", plan.height, if plan.native { " • H.264" } else { "" }), true); + let outdir = workdir.join(format!("v{attempt}")); + let mut path: Option = None; + let mut compressed = false; + if !plan.native && tools::have("ffmpeg") { + if let Some(convert) = stream_convert_args(job.limit, dur) { + if let Some(streams) = tools::stream_inputs(job, &job.url, &plan.selector, cookie).await { + let saved = job.with(|p| (p.budget, p.reserve)); + job.with(|p| { + p.budget = 0.0; // the source's size says nothing about the output + p.reserve = 0.0; + }); + job.set("Downloading + converting", "🔄", &format!("Up to {}p • encoding to H.264 as it arrives", plan.height), true); + match tools::stream_convert(job, &streams, &convert, dur, &outdir.join("stream.mp4")).await { + Ok(p) => { + path = Some(p); + compressed = true; + } + Err(DlError::Cancelled) => return Err(DlError::Cancelled), + Err(e) => tracing::warn!("convert-while-downloading failed, using the two-step path: {}", super::job::err_text(&e)), + } + if path.is_none() { + job.with(|p| { + p.budget = saved.0; + p.reserve = saved.1; + }); + let _ = std::fs::remove_dir_all(&outdir); + job.reset_streams(); + job.set("Downloading", "⬇️", &format!("Up to {}p", plan.height), true); + } + } + } + } + if path.is_none() { + let merge = if plan.native { "mp4" } else { "mkv" }; + match net_retry(job, || tools::download_video(job, &job.url, &plan.selector, &outdir, cookie, merge)).await { + Ok(p) => path = Some(p), + Err(DlError::SizeExceeded) => { + banned.push(plan.sig.clone()); // silently drop to the next smaller stream + let _ = std::fs::remove_dir_all(&outdir); + continue; + } + Err(e) => return Err(e), + } + } + let path = path.unwrap(); + let media = tools::inspect(&path).await; + if let Some(m) = media.as_ref().filter(|m| !m.ok) { + tracing::info!("rejecting {}: {}", path.display(), m.reason); + return Err(DlError::ImageOnly(m.reason.clone())); + } + found = Some((path, media, compressed, plan.height, plan.native)); + break; + } + let Some((mut path, mut media, mut compressed, plan_height, native)) = found else { return Err(DlError::TooLarge) }; + job.with(|p| { + p.budget = 0.0; + p.finished_bytes = 0.0; + }); + let mut meta = media.clone().unwrap_or_default(); + if meta.duration <= 0.0 { + meta.duration = dur.unwrap_or(0.0); + } + if meta.height == 0 { + meta.height = plan_height; + } + // 1) make sure it will actually PLAY (H.264 + AAC in MP4) - converts only when it must + let force = !native && media.is_none(); + let (p, m, changed) = tools::ensure_playable(job, path, media.take(), &meta, force).await?; + path = p; + media = m; + compressed = compressed || changed; + if let Some(m) = &media { + meta = Media { duration: if m.duration > 0.0 { m.duration } else { meta.duration }, ..m.clone() }; + } + // 2) make sure it FITS - one fast encode, only if still over the limit + if size_of(&path) as f64 > limit * FINAL_MARGIN { + path = tools::compress(job, &path, &meta, false).await?; + compressed = true; + media = tools::inspect(&path).await.or(media); + } + let size = size_of(&path); + let nice = path.with_file_name(format!("{}{}", slug(&title, str_of(&info, "id").unwrap_or("video")), path.extension().and_then(|e| e.to_str()).map(|e| format!(".{}", e.to_lowercase())).unwrap_or_default())); + if nice != path && std::fs::rename(&path, &nice).is_ok() { + path = nice; + } + tracing::info!("download ready: {} ({} bytes, converted: {compressed})", path.display(), size); + let codec = media.as_ref().and_then(|m| m.codec.clone()).or_else(|| str_of(&info, "vcodec").map(str::to_string)); + Ok(VideoResult { + path, + title, + height: media.as_ref().map(|m| m.height).filter(|h| *h > 0).unwrap_or(plan_height), + duration: media.as_ref().map(|m| m.duration).filter(|d| *d > 0.0).or(dur), + codec: codec_label(codec.as_deref()), + size, + url: str_of(&info, "webpage_url").unwrap_or(&job.url).to_string(), + }) +} + +async fn gallery_flow(job: &Job, workdir: &Path, cookie: Option<&Path>) -> Result { + job.set("Image post detected", "🖼️", "Switching to gallery-dl", true); + let files = tools::gallery(job, &job.url, &workdir.join("gallery"), cookie).await?; + let (mut images, mut videos, mut skipped) = (Vec::new(), Vec::new(), 0usize); + for (i, p) in files.into_iter().enumerate() { + let ext = p.extension().and_then(|e| e.to_str()).unwrap_or("").to_lowercase(); + let is_image = IMAGE_EXT.contains(&ext.as_str()); + let new = p.with_file_name(format!("{}_{:02}.{ext}", if is_image { "img" } else { "vid" }, i + 1)); + let p = if std::fs::rename(&p, &new).is_ok() { new } else { p }; + if is_image { + let mut p = p; + if size_of(&p) as f64 > job.limit as f64 * SAFETY_MARGIN { + job.set("Shrinking oversized image", "🗜️", "", false); + let (src, limit) = (p.clone(), (job.limit as f64 * SAFETY_MARGIN) as u64); + match tokio::task::spawn_blocking(move || tools::shrink_image(&src, limit)).await.ok().flatten() { + Some(small) => p = small, + None => { + skipped += 1; + continue; + } + } + } + images.push(p); + } else { + let meta = tools::inspect(&p).await; + let base = meta.clone().unwrap_or_default(); + let (p, meta, _) = match tools::ensure_playable(job, p, meta, &base, false).await { + Ok(x) => x, + Err(DlError::TooLarge | DlError::User(..)) => { + skipped += 1; + continue; + } + Err(e) => return Err(e), + }; + let mut p = p; + if size_of(&p) as f64 > job.limit as f64 * FINAL_MARGIN { + match tools::compress(job, &p, &meta.unwrap_or_default(), false).await { + Ok(c) => p = c, + Err(DlError::TooLarge | DlError::User(..)) => { + skipped += 1; + continue; + } + Err(e) => return Err(e), + } + } + videos.push(p); + } + } + if images.is_empty() && videos.is_empty() { + return Err(DlError::TooLarge); + } + let title = job.snapshot().title; + Ok(GalleryResult { images, videos, title: if title.is_empty() { "Image post".into() } else { title }, url: job.url.clone(), skipped }) +} + +/// Image groups (≤10 per message, within the size budget), then each video on its own. +pub fn gallery_groups(res: &GalleryResult, limit: u64) -> Vec> { + let budget = (limit as f64 * SAFETY_MARGIN) as u64; + let (mut groups, mut cur, mut cur_size): (Vec>, Vec, u64) = (vec![], vec![], 0); + for p in &res.images { + let sz = size_of(p); + if !cur.is_empty() && (cur.len() >= 10 || cur_size + sz > budget) { + groups.push(std::mem::take(&mut cur)); + cur_size = 0; + } + cur.push(p.clone()); + cur_size += sz; + } + if !cur.is_empty() { + groups.push(cur); + } + groups.extend(res.videos.iter().map(|v| vec![v.clone()])); + groups +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::{Child, Command, Stdio}; + + /// A throwaway web server with a few generated clips (needs python3, ffmpeg, yt-dlp: run with `--ignored`). + struct Site { + dir: PathBuf, + server: Child, + port: u16, + } + + impl Site { + fn start() -> Self { + let dir = std::env::temp_dir().join(format!("dezio-site-{}-{:x}", std::process::id(), rand::random::())); + std::fs::create_dir_all(&dir).unwrap(); + let make = |name: &str, codec: &[&str]| { + let mut args = vec!["-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=640x360:rate=24", "-f", "lavfi", "-i", "sine=frequency=440", "-t", "4"]; + args.extend_from_slice(codec); + let out = dir.join(name); + args.push(out.to_str().unwrap()); + assert!(Command::new("ffmpeg").args(&args).status().unwrap().success()); + }; + make("h264.mp4", &["-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac"]); + make("vp9.webm", &["-c:v", "libvpx-vp9", "-deadline", "realtime", "-cpu-used", "8", "-c:a", "libopus"]); + let port = 20000 + (rand::random::() % 20000); + let server = Command::new("python3").args(["-m", "http.server", &port.to_string(), "--bind", "127.0.0.1"]).current_dir(&dir).stdout(Stdio::null()).stderr(Stdio::null()).spawn().unwrap(); + std::thread::sleep(Duration::from_millis(800)); + Self { dir, server, port } + } + fn url(&self, name: &str) -> String { + format!("http://127.0.0.1:{}/{name}", self.port) + } + } + + impl Drop for Site { + fn drop(&mut self) { + let _ = self.server.kill(); + let _ = std::fs::remove_dir_all(&self.dir); + } + } + + fn workdir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("dezio-work-{tag}-{}-{:x}", std::process::id(), rand::random::())); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[tokio::test] + #[ignore = "needs python3, ffmpeg and yt-dlp"] + async fn dl_live_h264_video_downloads_as_is() { + let site = Site::start(); + let job = Job::new(1, site.url("h264.mp4"), 10 << 20, false); + let work = workdir("h264"); + let Outcome::Video(v) = pipeline(&reqwest::Client::new(), &job, 1080, &work, None).await.unwrap_or_else(|e| panic!("{}", super::super::job::err_text(&e))) else { panic!("not a video") }; + assert_eq!(v.codec, "H.264"); + assert!(v.size > 10_000 && v.path.is_file(), "{}", v.path.display()); + assert!(v.path.extension().is_some_and(|e| e == "mp4")); + let _ = std::fs::remove_dir_all(work); + } + + #[tokio::test] + #[ignore = "needs python3, ffmpeg and yt-dlp"] + async fn dl_live_vp9_is_converted_so_it_plays() { + let site = Site::start(); + let job = Job::new(1, site.url("vp9.webm"), 10 << 20, false); + let work = workdir("vp9"); + let Outcome::Video(v) = pipeline(&reqwest::Client::new(), &job, 1080, &work, None).await.unwrap_or_else(|e| panic!("{}", super::super::job::err_text(&e))) else { panic!("not a video") }; + assert_eq!(v.codec, "H.264", "VP9 must come out as H.264"); + assert!(v.path.extension().is_some_and(|e| e == "mp4")); + let media = tools::inspect(&v.path).await.unwrap(); + assert!(media.ok && media.acodec.as_deref() == Some("aac"), "{media:?}"); + let _ = std::fs::remove_dir_all(work); + } + + #[tokio::test] + #[ignore = "needs python3, ffmpeg and yt-dlp"] + async fn dl_live_convert_while_downloading() { + let site = Site::start(); + let job = Job::new(1, site.url("vp9.webm"), 10 << 20, false); + let work = workdir("stream"); + let streams = tools::stream_inputs(&job, &job.url, "webm/b", None).await.expect("yt-dlp should hand over the stream"); + assert_eq!(streams.len(), 1); + let args = stream_convert_args(job.limit, Some(4.0)).unwrap(); + let out = tools::stream_convert(&job, &streams, &args, Some(4.0), &work.join("s").join("stream.mp4")).await.unwrap_or_else(|e| panic!("{}", super::super::job::err_text(&e))); + let media = tools::inspect(&out).await.unwrap(); + assert!(media.ok && media.codec.as_deref() == Some("h264") && media.duration > 3.0, "{media:?}"); + let _ = std::fs::remove_dir_all(work); + } + + #[tokio::test] + #[ignore = "needs python3, ffmpeg and yt-dlp"] + async fn dl_live_audio_becomes_opus() { + let site = Site::start(); + let job = Job::new(1, site.url("h264.mp4"), 10 << 20, true); + let work = workdir("audio"); + let Outcome::Audio(a) = pipeline(&reqwest::Client::new(), &job, 1080, &work, None).await.unwrap_or_else(|e| panic!("{}", super::super::job::err_text(&e))) else { panic!("not audio") }; + assert_eq!(a.kbps, 96); + assert!(a.path.extension().is_some_and(|e| e == "opus") && a.size > 1000); + let _ = std::fs::remove_dir_all(work); + } + + #[tokio::test] + #[ignore = "needs python3, ffmpeg and yt-dlp"] + async fn dl_live_too_big_is_squeezed_to_fit() { + let site = Site::start(); + let job = Job::new(1, site.url("h264.mp4"), 60_000, false); // a 60 KB limit for a 4 s clip + let work = workdir("squeeze"); + let Outcome::Video(v) = pipeline(&reqwest::Client::new(), &job, 1080, &work, None).await.unwrap_or_else(|e| panic!("{}", super::super::job::err_text(&e))) else { panic!("not a video") }; + assert!(v.size <= 60_000, "{} bytes", v.size); + let _ = std::fs::remove_dir_all(work); + } + + #[tokio::test] + #[ignore = "needs python3, ffmpeg and yt-dlp"] + async fn dl_live_cancel_stops_the_tools() { + let site = Site::start(); + let job = std::sync::Arc::new(Job::new(1, site.url("vp9.webm"), 10 << 20, false)); + let work = workdir("cancel"); + let j = job.clone(); + let task = tokio::spawn(async move { + let web = reqwest::Client::new(); + let w = work.clone(); + tokio::select! { r = pipeline(&web, &j, 1080, &w, None) => r.map(|_| ()), _ = j.cancelled() => Err(DlError::Cancelled) } + }); + tokio::time::sleep(Duration::from_millis(200)).await; + job.cancel(); + assert!(matches!(tokio::time::timeout(Duration::from_secs(5), task).await.unwrap().unwrap(), Err(DlError::Cancelled))); + } + + /// `DEZIO_TEST_URL=https://… cargo test dl_live_real_link -- --ignored --nocapture` + #[tokio::test] + #[ignore = "needs a link in DEZIO_TEST_URL"] + async fn dl_live_real_link() { + let Ok(url) = std::env::var("DEZIO_TEST_URL") else { return }; + let job = Job::new(1, url, 10 << 20, false); + let work = workdir("real"); + match pipeline(&reqwest::Client::new(), &job, 1080, &work, None).await { + Ok(Outcome::Video(v)) => println!("VIDEO {} {}p {} {} bytes {}", v.title, v.height, v.codec, v.size, v.path.display()), + Ok(Outcome::Audio(a)) => println!("AUDIO {} {} bytes", a.title, a.size), + Ok(Outcome::Gallery(g)) => println!("GALLERY {} images {} videos", g.images.len(), g.videos.len()), + Err(e) => panic!("{}", super::super::job::err_text(&e)), + } + let _ = std::fs::remove_dir_all(work); + } +} diff --git a/src/commands/media/download/job.rs b/src/commands/media/download/job.rs new file mode 100644 index 0000000..6c60fb9 --- /dev/null +++ b/src/commands/media/download/job.rs @@ -0,0 +1,246 @@ +//! One running download: what the progress card shows, the size watchdog, and cancelling. +use super::plan::{clean, SAFETY_MARGIN}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; +use tokio::sync::Notify; + +/// Why a step failed. `User` messages are safe to show as they are. +#[derive(Debug)] +pub enum DlError { + User(String, String), + /// The post has no real video → try gallery-dl. + ImageOnly(String), + /// Even compressed it won't fit. + TooLarge, + /// The stream we started is bigger than the limit; try a smaller one. + SizeExceeded, + Cancelled, + /// Raw text from yt-dlp, for [`super::plan::friendly_error`]. + Ytdlp(String), +} + +impl DlError { + pub fn user(title: &str, text: impl Into) -> Self { + Self::User(title.to_string(), text.into()) + } +} + +impl From for DlError { + fn from(e: std::io::Error) -> Self { + Self::user("Something broke", format!("```\n{e}\n```")) + } +} + +#[derive(Default, Clone)] +pub struct Progress { + pub phase: String, + pub emoji: String, + pub detail: String, + pub title: String, + pub percent: Option, + pub downloaded: f64, + pub total: f64, + pub speed: Option, + pub eta: Option, + pub stream_no: u32, + /// Max bytes we may download (0 = watchdog off). + pub budget: f64, + /// Bytes to keep free for the audio stream still to come. + pub reserve: f64, + pub finished_bytes: f64, + pub last_stream: String, +} + +pub struct Job { + pub owner: u64, + pub url: String, + pub limit: u64, + pub audio: bool, + state: Mutex, + cancelled: AtomicBool, + notify: Notify, +} + +impl Job { + pub fn new(owner: u64, url: String, limit: u64, audio: bool) -> Self { + let p = Progress { phase: "Queued".into(), emoji: "⏳".into(), ..Default::default() }; + Self { owner, url, limit, audio, state: Mutex::new(p), cancelled: AtomicBool::new(false), notify: Notify::new() } + } + + pub fn with(&self, f: impl FnOnce(&mut Progress) -> R) -> R { + f(&mut self.state.lock().unwrap_or_else(|e| e.into_inner())) + } + + pub fn snapshot(&self) -> Progress { + self.with(|p| p.clone()) + } + + /// New phase; `reset` clears the numbers. + pub fn set(&self, phase: &str, emoji: &str, detail: &str, reset: bool) { + self.with(|p| { + p.phase = phase.into(); + p.emoji = emoji.into(); + p.detail = detail.into(); + if reset { + p.percent = None; + p.downloaded = 0.0; + p.total = 0.0; + p.speed = None; + p.eta = None; + } + }); + } + + pub fn set_title(&self, title: &str) { + self.with(|p| p.title = title.into()); + } + + /// Forget which stream we were on (before a fresh download). + pub fn reset_streams(&self) { + self.with(|p| { + p.stream_no = 0; + p.last_stream.clear(); + p.finished_bytes = 0.0; + }); + } + + /// What changed visibly — the card is only edited when this differs. + pub fn signature(&self) -> String { + let p = self.snapshot(); + format!("{}|{}|{:?}|{}|{:?}|{}|{}", p.phase, p.detail, p.percent.map(|x| x as i64), (p.speed.unwrap_or(0.0) / 50_000.0) as i64, p.eta, p.title, self.is_cancelled()) + } + + pub fn cancel(&self) { + self.cancelled.store(true, Ordering::SeqCst); + self.notify.notify_waiters(); + } + + pub fn is_cancelled(&self) -> bool { + self.cancelled.load(Ordering::SeqCst) + } + + /// Resolves when someone presses Cancel. + pub async fn cancelled(&self) { + loop { + let waiter = self.notify.notified(); + if self.is_cancelled() { + return; + } + waiter.await; + } + } + + /// One `DLP status|downloaded|total|estimate|speed|eta|fragment|fragments|format` line from yt-dlp. + /// Errors when the stream can't fit (the watchdog) so the caller can stop it right away. + pub fn on_progress_line(&self, line: &str) -> Result<(), DlError> { + if self.is_cancelled() { + return Err(DlError::Cancelled); + } + let f: Vec<&str> = line.trim().split('|').collect(); + if f.len() < 9 { + return Ok(()); + } + let num = |i: usize| f[i].parse::().ok(); + let status = f[0]; + let mut p = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if status == "downloading" { + let stream = f[8].to_string(); + if stream != p.last_stream { + p.last_stream = stream; + p.stream_no += 1; + } + let (exact, guess) = (num(2).unwrap_or(0.0), num(3).unwrap_or(0.0)); + let total = if exact > 0.0 { exact } else { guess }; + let done = num(1).unwrap_or(0.0); + if p.budget > 0.0 { + let reserve = if p.stream_no <= 1 { p.reserve } else { 0.0 }; + if (exact > 0.0 && p.finished_bytes + exact + reserve > p.budget) + || (exact == 0.0 && guess > 0.0 && p.finished_bytes + guess + reserve > p.budget * 1.2) + || p.finished_bytes + done > p.budget + { + return Err(DlError::SizeExceeded); + } + } + if total > 0.0 { + p.percent = Some(done / total * 100.0); + } else if let (Some(i), Some(n)) = (num(6), num(7)) { + if n > 0.0 { + p.percent = Some(i / n * 100.0); + } + } + p.downloaded = done; + p.total = total; + p.speed = num(4); + p.eta = num(5).map(|e| e as i64); + p.phase = "Downloading".into(); + p.emoji = "⬇️".into(); + p.detail = format!("Stream {}", p.stream_no); + } else if status == "finished" { + p.percent = Some(100.0); + p.finished_bytes += num(2).filter(|n| *n > 0.0).or(num(1)).unwrap_or(0.0); + } + Ok(()) + } + + /// The most bytes a download may use while the size watchdog is on. + pub fn budget_for(limit: u64) -> f64 { + limit as f64 * super::plan::FINAL_MARGIN + } + + #[allow(dead_code)] + pub fn safe_bytes(&self) -> f64 { + self.limit as f64 * SAFETY_MARGIN + } +} + +pub fn err_text(e: &DlError) -> String { + match e { + DlError::Ytdlp(raw) => clean(raw), + DlError::User(t, x) => format!("{t}: {x}"), + other => format!("{other:?}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn progress_lines_update_the_card() { + let job = Job::new(1, "https://x".into(), 10 << 20, false); + job.on_progress_line("downloading|512|1024|NA|2048.0|3|NA|NA|137").unwrap(); + let p = job.snapshot(); + assert_eq!((p.percent, p.stream_no, p.phase.as_str()), (Some(50.0), 1, "Downloading")); + job.on_progress_line("finished|1024|1024|NA|NA|NA|NA|NA|137").unwrap(); + job.on_progress_line("downloading|10|100|NA|1.0|1|NA|NA|140").unwrap(); + assert_eq!(job.snapshot().stream_no, 2); + assert_eq!(job.snapshot().finished_bytes, 1024.0); + } + + #[test] + fn the_watchdog_stops_a_stream_that_cannot_fit() { + let job = Job::new(1, "u".into(), 1000, false); + job.with(|p| { + p.budget = 1000.0; + p.reserve = 100.0; + }); + assert!(matches!(job.on_progress_line("downloading|10|950|NA|1|1|NA|NA|a"), Err(DlError::SizeExceeded))); + let job2 = Job::new(1, "u".into(), 1000, false); + job2.with(|p| p.budget = 1000.0); + assert!(job2.on_progress_line("downloading|10|800|NA|1|1|NA|NA|a").is_ok()); + // an estimate is allowed 20% slack + assert!(job2.on_progress_line("downloading|10|NA|1100|1|1|NA|NA|a").is_ok()); + assert!(matches!(job2.on_progress_line("downloading|10|NA|1300|1|1|NA|NA|a"), Err(DlError::SizeExceeded))); + } + + #[tokio::test] + async fn cancel_wakes_waiters() { + let job = std::sync::Arc::new(Job::new(1, "u".into(), 1, false)); + let j = job.clone(); + let waiter = tokio::spawn(async move { j.cancelled().await }); + tokio::task::yield_now().await; + job.cancel(); + tokio::time::timeout(std::time::Duration::from_secs(2), waiter).await.unwrap().unwrap(); + assert!(matches!(job.on_progress_line("downloading|1|2|NA|1|1|NA|NA|a"), Err(DlError::Cancelled))); + } +} diff --git a/src/commands/media/download/mod.rs b/src/commands/media/download/mod.rs new file mode 100644 index 0000000..7941dc6 --- /dev/null +++ b/src/commands/media/download/mod.rs @@ -0,0 +1,536 @@ +//! `D!dl [audio] [best|1080|720|480|360]` · `/download` — videos, audio and slideshows from links. +//! +//! One message: a progress card that is edited in place into the finished upload (native video / audio +//! player). yt-dlp does the downloading (H.264 + AAC picked so nothing needs converting; sizes are checked +//! BEFORE downloading), and sites that only offer VP9/AV1/HEVC are converted to H.264 *while they download* +//! by one ffmpeg reading the streams directly. Image posts and carousels go through gallery-dl. +//! Built for flaky links and slow hosts: retries, one job at a time, throttled card edits, upload retries. +mod flow; +mod job; +mod plan; +pub(crate) mod tools; +pub use tools::tool; + +use self::flow::{gallery_groups, Outcome}; +use self::job::{DlError, Job}; +use self::plan::*; +use crate::cmd::{Command, Ctx, Opt, OptKind, Origin}; +use crate::paths; +use crate::state::State; +use crate::ui::escape; +use anyhow::Result; +use futures::FutureExt; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Duration; +use tokio::sync::Semaphore; +use twilight_http::request::AuditLogReason as _; +use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_model::channel::message::component::{ActionRow, Button, ButtonStyle, Component}; +use twilight_model::channel::message::{AllowedMentions, Embed, EmojiReactionType}; +use twilight_model::http::attachment::Attachment; +use twilight_model::id::marker::{ChannelMarker, MessageMarker}; +use twilight_model::id::Id; +use twilight_util::builder::embed::EmbedBuilder; + +const UI_TICK: Duration = Duration::from_secs(3); +const UPLOAD_RETRIES: u32 = 3; +const BLURPLE: u32 = 0x5865F2; + +fn active() -> &'static Mutex>> { + static A: OnceLock>>> = OnceLock::new(); + A.get_or_init(Default::default) +} + +/// Extra messages of a multi-message result, so Delete can remove them all. +fn extras() -> &'static Mutex, Id)>>> { + static E: OnceLock, Id)>>>> = OnceLock::new(); + E.get_or_init(Default::default) +} + +/// One download at a time: this is meant to run on a small machine. +fn slot() -> &'static Semaphore { + static S: OnceLock = OnceLock::new(); + S.get_or_init(|| Semaphore::new(1)) +} + +// ---- safety --------------------------------------------------------------------------------------------- + +fn is_global(ip: std::net::IpAddr) -> bool { + match ip { + std::net::IpAddr::V4(v4) => !(v4.is_private() || v4.is_loopback() || v4.is_link_local() || v4.is_unspecified() || v4.is_broadcast() || v4.octets()[0] == 0 || (v4.octets()[0] == 100 && (64..128).contains(&v4.octets()[1]))), + std::net::IpAddr::V6(v6) => !(v6.is_loopback() || v6.is_unspecified() || (v6.segments()[0] & 0xfe00) == 0xfc00 || (v6.segments()[0] & 0xffc0) == 0xfe80), + } +} + +/// Block requests to localhost and private networks (also after DNS lookup). +async fn url_is_safe(url: &str) -> bool { + let Some(parsed) = super::safe_url(url) else { return false }; + let Some(host) = parsed.host_str() else { return false }; + let host = host.trim_matches(|c| c == '[' || c == ']').to_lowercase(); + if host.ends_with(".lan") { + return false; + } + match tokio::time::timeout(Duration::from_secs(8), tokio::net::lookup_host((host.as_str(), 80))).await { + Ok(Ok(addrs)) => addrs.into_iter().all(|a| is_global(a.ip())), + _ => true, // can't resolve here → let yt-dlp report the real error + } +} + +/// Copy cookies per job so yt-dlp never touches your master file (Instagram only). +fn stage_cookie(url: &str, workdir: &Path) -> Option { + let host = super::safe_url(url)?.host_str()?.to_lowercase(); + if !(host == "instagram.com" || host.ends_with(".instagram.com")) { + return None; + } + let candidates: Vec = [std::env::var("IG_COOKIES").ok().map(PathBuf::from), Some(paths::data(&["cookies", "instagram.txt"]))].into_iter().flatten().collect(); + let Some(src) = candidates.into_iter().find(|p| p.is_file()) else { + tracing::warn!("Instagram link but no cookie file found (data/cookies/instagram.txt)"); + return None; + }; + let text = std::fs::read_to_string(&src).ok()?.replace("\r\n", "\n"); + let text = if text.trim_start().starts_with("# Netscape") || text.trim_start().starts_with("# HTTP Cookie File") { text } else { format!("# Netscape HTTP Cookie File\n{text}") }; + let dst = workdir.join("cookies.txt"); + std::fs::write(&dst, text).ok()?; + Some(dst) +} + +fn clean_old_downloads() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let root = paths::data(&["downloads", "x"]).parent().map(Path::to_path_buf); + let Some(root) = root else { return }; + let Ok(rd) = std::fs::read_dir(root) else { return }; + for e in rd.flatten() { + let old = e.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > Duration::from_secs(3600)); + if e.path().is_dir() && old { + let _ = std::fs::remove_dir_all(e.path()); + } + } + }); +} + +// ---- the message ------------------------------------------------------------------------------------------ + +fn status_embed(title: &str, text: &str, colour: u32) -> Embed { + EmbedBuilder::new().title(title).description(text.chars().take(4000).collect::()).color(colour).build() +} + +fn progress_embed(job: &Job) -> Embed { + let j = job.snapshot(); + let mut lines: Vec = Vec::new(); + if !j.title.is_empty() { + lines.push(format!("**{}**", escape(&j.title.chars().take(120).collect::()))); + } + if let Some(p) = j.percent { + lines.push(format!("`{}` **{p:.0}%**", bar(p))); + } + let mut stats = Vec::new(); + if j.total > 0.0 { + stats.push(format!("{} / {}", fmt_bytes(j.downloaded), fmt_bytes(j.total))); + } else if j.downloaded > 0.0 { + stats.push(fmt_bytes(j.downloaded)); + } + if let Some(s) = j.speed.filter(|s| *s > 0.0) { + stats.push(format!("{}/s", fmt_bytes(s))); + } + if let Some(e) = j.eta { + stats.push(format!("ETA {}", fmt_dur(Some(e as f64)))); + } + if !stats.is_empty() { + lines.push(stats.join(" • ")); + } + if !j.detail.is_empty() { + lines.push(format!("*{}*", j.detail)); + } + let mut b = EmbedBuilder::new().title(format!("{} {}", j.emoji, j.phase)).color(BLURPLE); + if !lines.is_empty() { + b = b.description(lines.join("\n")); + } + b.build() +} + +fn button(custom_id: &str, label: &str, emoji: &str, style: ButtonStyle, disabled: bool) -> Button { + Button { id: None, custom_id: Some(custom_id.into()), disabled, emoji: Some(EmojiReactionType::Unicode { name: emoji.into() }), label: Some(label.into()), style, url: None, sku_id: None } +} + +fn row(buttons: Vec