From 18ae300d3f0e326bc0aa3cb66d0e945f4d2ea76f Mon Sep 17 00:00:00 2001 From: felis Date: Sat, 18 Jul 2026 12:39:48 -0700 Subject: [PATCH] initial commit --- .dockerignore | 3 + .gitignore | 32 + Cargo.lock | 1595 +++++++++++++++++++++++++++ Cargo.toml | 42 + LICENSE | 675 ++++++++++++ README.md | 106 ++ src/auth.rs | 86 ++ src/bin/libilibili-analyze.rs | 85 ++ src/bin/libilibili-capture.rs | 189 ++++ src/client.rs | 308 ++++++ src/endpoints.rs | 628 +++++++++++ src/error.rs | 58 + src/lib.rs | 30 + src/wbi.rs | 130 +++ src/websocket.rs | 1935 +++++++++++++++++++++++++++++++++ 15 files changed, 5902 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 src/auth.rs create mode 100644 src/bin/libilibili-analyze.rs create mode 100644 src/bin/libilibili-capture.rs create mode 100644 src/client.rs create mode 100644 src/endpoints.rs create mode 100644 src/error.rs create mode 100644 src/lib.rs create mode 100644 src/wbi.rs create mode 100644 src/websocket.rs diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..9dd1cf8 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,3 @@ +target +.git +*.log diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..24fa97b --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +# Cargo 构建产物 +/target/ + +# Rust 工具与覆盖率产物 +**/*.rs.bk +*.profraw +*.profdata +/lcov.info + +# 本地环境与凭据(包括直播 Cookie) +.env +.env.* +!.env.example +/cookie.txt +/cookies.txt +/secrets/ + +# 本地抓包可能包含用户内容或标识信息 +/frames.jsonl +/captures/ + +# 日志与编辑器临时文件 +*.log +*.swp +*.swo +*~ + +# IDE 与操作系统生成的元数据 +/.idea/ +/.vscode/ +.DS_Store +Thumbs.db diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..71d8a60 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1595 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[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 = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[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 = "brotli" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc97b8f16f944bba54f0433f07e30be199b6dc2bd25937444bbad560bcea29bd" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a334ef7c9e23abf0ce748e8cd309037da93e606ad52eb372e4ce327a0dcfbdfd" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.2.67" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[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.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "rand_core 0.10.1", +] + +[[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.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "data-encoding" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[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 = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-macro", + "futures-sink", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[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", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[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 = "http" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425" +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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f41fd6a08e4d4ec69df65976da761afd5ad5e58a9d4acb46bd1c953a9e3ff2" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots 1.0.8", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[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 = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libilibili" +version = "0.1.0" +dependencies = [ + "base64", + "brotli", + "flate2", + "futures-util", + "md-5", + "reqwest", + "serde", + "serde_json", + "thiserror", + "tokio", + "tokio-tungstenite", + "url", +] + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[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 = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.2", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +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.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[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_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 = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots 1.0.8", +] + +[[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 = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "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 = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[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 = "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", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[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 = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[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 = "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.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d988bcd52dbe076d3d46903332f58c912b87a2c49b1428419a5845154762ffee" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6328af13490e73a9b4694030fafd93f8c8c6a9dede33e821c3fc63eddf8042ba" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[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", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tungstenite", + "webpki-roots 0.26.11", +] + +[[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", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "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 = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.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", + "rustls-pki-types", + "sha1", + "thiserror", + "utf-8", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[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", +] + +[[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 = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +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.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141" +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 = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.8", +] + +[[package]] +name = "webpki-roots" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7cbbc0a705a0fd05cc3676525980d2bf5a9bc4adac6d6475209a7887cf59d19" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e817b7b52d0c7358d3246da9d69935ebb18116b2b102b4230dac079b4862f5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[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.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..69f38b5 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "libilibili" +version = "0.1.0" +edition = "2021" +rust-version = "1.81" +description = "An async Bilibili Web and Live API client with Cookie, CSRF, WBI, and live WebSocket support." +license = "GPL-3.0-only" +repository = "https://github.com/feliscafra/libilibili" +keywords = ["bilibili", "live", "api", "wbi"] +categories = ["api-bindings", "web-programming::http-client"] + +[features] +default = ["websocket"] +websocket = ["dep:tokio", "dep:tokio-tungstenite", "dep:futures-util", "dep:flate2", "dep:brotli"] + +[[bin]] +name = "libilibili-capture" +path = "src/bin/libilibili-capture.rs" +required-features = ["websocket"] + +[[bin]] +name = "libilibili-analyze" +path = "src/bin/libilibili-analyze.rs" +required-features = ["websocket"] + +[dependencies] +base64 = "0.22" +md-5 = "0.10" +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +url = "2" + +brotli = { version = "7", optional = true } +flate2 = { version = "1", optional = true } +futures-util = { version = "0.3", optional = true } +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "time"], optional = true } +tokio-tungstenite = { version = "0.26", features = ["rustls-tls-webpki-roots"], optional = true } + +[dev-dependencies] +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..53d1f3d --- /dev/null +++ b/LICENSE @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..e98ccfd --- /dev/null +++ b/README.md @@ -0,0 +1,106 @@ +# libilibili + +异步 Rust Bilibili Web/直播 API 库,依据 [feliscafra/Bilibili-Live-API](https://github.com/feliscafra/Bilibili-Live-API) 的接口、鉴权与 WebSocket 文档实现。 + +## 功能 + +- 公开 GET、WBI GET、Cookie GET、带 CSRF 的 Cookie POST,以及 WBI+POST。 +- 从 `/x/web-interface/nav` 自动刷新和缓存 WBI key;参数排序、清洗、percent-encode、MD5 签名均在库内完成。 +- 登录 Cookie 存在内存;状态变更请求自动写入 `csrf` 与 `csrf_token`(取自 `bili_jct`)。 +- 高层分组:直播间/分区/播放/礼物/勋章、视频、空间与关系、评论、搜索。 +- 默认 `websocket` feature:直播弹幕认证、心跳和 JSON/zlib/brotli 协议包解析,并只连接 `*.chat.bilibili.com`。 +- 使用通用请求方法覆盖参考文档中尚未提供快捷封装的低频或易变端点。 + +## 使用 + +```toml +[dependencies] +libilibili = "0.1" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +``` + +```rust,no_run +use libilibili::{Client, Credentials}; + +#[tokio::main] +async fn main() -> Result<(), libilibili::Error> { + let anonymous = Client::anonymous()?; + let room = anonymous.live().room_detail(5050).await?; // 自动 WBI + println!("{room:#}"); + + let auth = Credentials::from_cookie_header("SESSDATA=...; bili_jct=..."); + let client = Client::with_credentials(auth)?; + client.video().like(170001, true).await?; // 自动 csrf + csrf_token + Ok(()) +} +``` + +不需要 WebSocket: + +```toml +libilibili = { version = "0.1", default-features = false } +``` + +## 通用端点调用与鉴权 + +| 鉴权类型 | 方法 | +| --- | --- | +| Public GET | `client.get(url, query)` | +| WBI GET | `client.get_wbi(url, query)` | +| Cookie POST | `client.post_form(url, form)` | +| Cookie + WBI POST | `client.post_form_wbi(url, query, form)` | + +`query`/`form` 是 `Vec<(String, String)>`;响应的 `data` 为泛型,快捷方法默认保留为 `serde_json::Value`,防止上游新增字段时信息丢失。 + +```rust,no_run +# use libilibili::Client; +# async fn example(client: Client) -> Result<(), libilibili::Error> { +let history: serde_json::Value = client.get( + "https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory", + vec![("roomid".into(), "5050".into()), ("room_type".into(), "0".into())], +).await?; +# Ok(()) } +``` + +## 弹幕 WebSocket + +```rust,no_run +use libilibili::{Client, Credentials, websocket::LiveWebSocket}; + +# async fn example() -> Result<(), libilibili::Error> { +let credentials = Credentials::from_cookie_header("SESSDATA=...; bili_jct=...; buvid3=..."); +let client = Client::with_credentials(credentials)?; +let mut ws = LiveWebSocket::connect(&client, 5050).await?; +ws.heartbeat().await?; // 应约每 30 秒调用 +while let Some(event) = ws.next_event().await? { println!("{event:?}"); } +# Ok(()) } +``` + +## 原始帧抓取 + +`libilibili-capture` 可连接一个已登录的直播间,并将收到的**原始 WebSocket 二进制帧** +写为 stdout 的 JSON Lines;连接状态与心跳日志只写入 stderr。每条输出含完整 +`frame_base64`,以及未解压协议包的版本、操作码和 `body_base64`,便于离线复现协议 +解析。 + +```sh +cargo run --bin libilibili-capture -- \ + --cookie 'SESSDATA=...; bili_jct=...; buvid3=...' \ + --room-id 5050 \ + --seconds 120 \ + > frames.jsonl +``` + +更安全的方式是通过标准输入提供 Cookie: + +```sh +printf '%s' "$BILI_COOKIE" | cargo run --bin libilibili-capture -- \ + --cookie-stdin --room-id 5050 --seconds 120 > frames.jsonl +``` + +Cookie 不会被工具输出,但命令行参数可能被同机其他用户读取;在共享机器上应使用 +`--cookie-stdin`、受限权限的启动器或 secret 管理器注入 Cookie。 + +## 安全边界 + +本库不自动化密码、验证码、二维码或 OAuth 登录,也不尝试绕过风控。通过 Bilibili 正常登录取得会话后,使用环境变量或 secret store 注入 `SESSDATA`/`bili_jct`;绝不要提交或记录这些值。`-352` 代表风控/上下文限制,不等价于接口下线。 diff --git a/src/auth.rs b/src/auth.rs new file mode 100644 index 0000000..c8c3591 --- /dev/null +++ b/src/auth.rs @@ -0,0 +1,86 @@ +use std::collections::BTreeMap; + +/// 浏览器会话凭据。 +/// +/// 凭据仅保存在内存中,且不会通过本 crate 的 `Debug` 输出泄露。 +#[derive(Clone, Debug, Default)] +pub struct Credentials { + cookies: BTreeMap, + csrf: Option, + access_key: Option, +} + +impl Credentials { + /// 创建凭据构建器。 + pub fn builder() -> CredentialsBuilder { + CredentialsBuilder::default() + } + + /// 从 `Cookie` 请求头文本解析凭据。 + /// + /// 若其中含有 `bili_jct`,它会同时被用作 CSRF token。 + pub fn from_cookie_header(header: impl AsRef) -> Self { + let mut result = Self::default(); + for pair in header.as_ref().split(';') { + if let Some((name, value)) = pair.trim().split_once('=') { + if !name.is_empty() { + result.cookies.insert(name.to_owned(), value.to_owned()); + } + } + } + result.csrf = result.cookies.get("bili_jct").cloned(); + result + } + + /// 生成可直接写入 HTTP `Cookie` 请求头的值;没有 Cookie 时返回 `None`。 + pub fn cookie_header(&self) -> Option { + (!self.cookies.is_empty()).then(|| { + self.cookies + .iter() + .map(|(name, value)| format!("{name}={value}")) + .collect::>() + .join("; ") + }) + } + /// 获取 CSRF token,通常等于 Cookie 中的 `bili_jct`。 + pub fn csrf(&self) -> Option<&str> { + self.csrf.as_deref() + } + /// 获取 APP 接口使用的 `access_key`。 + pub fn access_key(&self) -> Option<&str> { + self.access_key.as_deref() + } +} + +/// [`Credentials`] 的链式构建器。 +#[derive(Clone, Debug, Default)] +pub struct CredentialsBuilder(Credentials); + +impl CredentialsBuilder { + /// 添加任意名称的 Cookie。 + pub fn cookie(mut self, name: impl Into, value: impl Into) -> Self { + self.0.cookies.insert(name.into(), value.into()); + self + } + /// 设置登录会话 Cookie `SESSDATA`。 + pub fn sessdata(self, value: impl Into) -> Self { + self.cookie("SESSDATA", value) + } + /// 显式设置 CSRF token;未设置时会尝试使用 `bili_jct` Cookie。 + pub fn csrf(mut self, value: impl Into) -> Self { + self.0.csrf = Some(value.into()); + self + } + /// 设置移动端接口使用的 `access_key`。 + pub fn access_key(mut self, value: impl Into) -> Self { + self.0.access_key = Some(value.into()); + self + } + /// 构建凭据。 + pub fn build(mut self) -> Credentials { + if self.0.csrf.is_none() { + self.0.csrf = self.0.cookies.get("bili_jct").cloned(); + } + self.0 + } +} diff --git a/src/bin/libilibili-analyze.rs b/src/bin/libilibili-analyze.rs new file mode 100644 index 0000000..05c229b --- /dev/null +++ b/src/bin/libilibili-analyze.rs @@ -0,0 +1,85 @@ +//! `libilibili-capture` 产生的 JSONL 文件的离线类型分发统计工具。 +//! +//! 工具只输出事件类型、未知命令和解析错误数量,不输出弹幕、昵称或其他业务内容。 + +use base64::{engine::general_purpose::STANDARD, Engine}; +use libilibili::{ + websocket::{decode_events, LiveCommand, LiveEvent}, + Error, Result, +}; +use serde_json::Value; +use std::{collections::BTreeMap, env, fs}; + +fn main() -> Result<()> { + let path = env::args().nth(1).ok_or_else(|| { + Error::InvalidPacket( + "用法:libilibili-analyze ".into(), + ) + })?; + let input = fs::read_to_string(path)?; + let mut counts = BTreeMap::::new(); + let mut frames = 0_u64; + let mut decode_errors = 0_u64; + + for line in input.lines().filter(|line| !line.trim().is_empty()) { + let record: Value = serde_json::from_str(line)?; + let Some(frame_base64) = record.get("frame_base64").and_then(Value::as_str) else { + decode_errors += 1; + continue; + }; + frames += 1; + match STANDARD + .decode(frame_base64) + .ok() + .and_then(|frame| decode_events(&frame).ok()) + { + Some(events) => { + for event in events { + *counts.entry(event_name(&event)).or_default() += 1; + } + } + None => decode_errors += 1, + } + } + + println!("frames={frames}"); + println!("decode_errors={decode_errors}"); + for (name, count) in counts { + println!("{name}={count}"); + } + Ok(()) +} + +fn event_name(event: &LiveEvent) -> String { + match event { + LiveEvent::Popularity(_) => "Popularity".into(), + LiveEvent::Auth(_) => "Auth".into(), + LiveEvent::Unknown(_) => "PacketUnknown".into(), + LiveEvent::Command(command) => match command.as_ref() { + LiveCommand::Danmu(_) => "Danmu".into(), + LiveCommand::Gift(_) => "Gift".into(), + LiveCommand::ComboSend(_) => "ComboSend".into(), + LiveCommand::LikeClick(_) => "LikeClick".into(), + LiveCommand::LikeUpdate(_) => "LikeUpdate".into(), + LiveCommand::LikeNotice(_) => "LikeNotice".into(), + LiveCommand::OnlineRankCount(_) => "OnlineRankCount".into(), + LiveCommand::WatchedChange(_) => "WatchedChange".into(), + LiveCommand::StopLiveRoomList(_) => "StopLiveRoomList".into(), + LiveCommand::GiftStarProcess(_) => "GiftStarProcess".into(), + LiveCommand::OnlineRankV3(_) => "OnlineRankV3".into(), + LiveCommand::InteractWordV2(_) => "InteractWordV2".into(), + LiveCommand::GuardBuy(_) => "GuardBuy".into(), + LiveCommand::SuperChat(_) => "SuperChat".into(), + LiveCommand::InteractWord(_) => "InteractWord".into(), + LiveCommand::RoomChange(_) => "RoomChange".into(), + LiveCommand::Live(_) => "Live".into(), + LiveCommand::Preparing(_) => "Preparing".into(), + LiveCommand::Unknown { command, .. } => { + format!("Unknown:{}", command.as_deref().unwrap_or("")) + } + LiveCommand::Invalid { command, .. } => { + format!("Invalid:{}", command.as_deref().unwrap_or("")) + } + }, + } +} diff --git a/src/bin/libilibili-capture.rs b/src/bin/libilibili-capture.rs new file mode 100644 index 0000000..bc78ff4 --- /dev/null +++ b/src/bin/libilibili-capture.rs @@ -0,0 +1,189 @@ +//! 直播弹幕 WebSocket 原始帧抓取工具。 +//! +//! stderr 仅记录运行状态;stdout 输出 JSON Lines,每一行都是一个收到的原始 +//! WebSocket 二进制帧及其可选的协议包头摘要。Cookie 永远不会被输出。 + +use base64::{engine::general_purpose::STANDARD, Engine}; +use libilibili::{ + websocket::{decode_packets, LiveWebSocket}, + Client, Credentials, Error, Result, +}; +use serde_json::{json, Value}; +use std::{ + env, + io::{self, Read, Write}, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; + +struct Config { + cookie: String, + room_id: u64, + duration: Duration, +} + +#[tokio::main] +async fn main() -> Result<()> { + let Some(config) = parse_args()? else { + return Ok(()); + }; + + // Cookie 仅传给客户端;日志刻意不打印其值或长度。 + let client = Client::with_credentials(Credentials::from_cookie_header(&config.cookie))?; + eprintln!( + "正在连接直播间 {},抓取时长 {} 秒。", + config.room_id, + config.duration.as_secs() + ); + let mut socket = LiveWebSocket::connect(&client, config.room_id).await?; + eprintln!("WebSocket 已认证。原始帧将以 JSON Lines 输出到 stdout。"); + + let end = Instant::now() + config.duration; + let mut next_heartbeat = Instant::now() + Duration::from_secs(30); + let mut sequence = 0_u64; + let stdout = io::stdout(); + let mut output = io::BufWriter::new(stdout.lock()); + + while Instant::now() < end { + let now = Instant::now(); + if now >= next_heartbeat { + socket.heartbeat().await?; + next_heartbeat = now + Duration::from_secs(30); + eprintln!("已发送心跳。"); + } + + let deadline = end.min(next_heartbeat); + let timeout = deadline.saturating_duration_since(Instant::now()); + match tokio::time::timeout(timeout, socket.next_raw_frame()).await { + Err(_) => continue, + Ok(Ok(None)) => { + eprintln!("服务器已关闭 WebSocket 连接。"); + break; + } + Ok(Err(error)) => return Err(error), + Ok(Ok(Some(frame))) => { + sequence += 1; + let record = frame_record(sequence, &frame); + serde_json::to_writer(&mut output, &record)?; + output.write_all(b"\n")?; + output.flush()?; + } + } + } + + eprintln!("抓取结束,共输出 {sequence} 个 WebSocket 帧。"); + Ok(()) +} + +fn frame_record(sequence: u64, frame: &[u8]) -> Value { + let received_at_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis(); + match decode_packets(frame) { + Ok(packets) => json!({ + "sequence": sequence, + "received_at_ms": received_at_ms, + "frame_base64": STANDARD.encode(frame), + "packets": packets.into_iter().map(|packet| json!({ + "version": packet.version, + "operation": packet.operation, + "body_base64": STANDARD.encode(packet.body), + })).collect::>(), + }), + Err(error) => json!({ + "sequence": sequence, + "received_at_ms": received_at_ms, + "frame_base64": STANDARD.encode(frame), + "decode_error": error.to_string(), + }), + } +} + +fn parse_args() -> Result> { + let mut cookie = None; + let mut cookie_stdin = false; + let mut room_id = None; + let mut seconds = 60_u64; + let mut args = env::args().skip(1); + + while let Some(argument) = args.next() { + match argument.as_str() { + "--cookie" => cookie = Some(next_value(&mut args, "--cookie")?), + "--cookie-stdin" => cookie_stdin = true, + "--room-id" | "-r" => { + room_id = Some( + next_value(&mut args, "--room-id")? + .parse() + .map_err(|_| Error::InvalidPacket("直播间 ID 必须是无符号整数".into()))?, + ) + } + "--seconds" | "-s" => { + seconds = next_value(&mut args, "--seconds")? + .parse() + .map_err(|_| Error::InvalidPacket("抓取秒数必须是无符号整数".into()))? + } + "--help" | "-h" => { + print_usage(); + return Ok(None); + } + _ => { + return Err(Error::InvalidPacket(format!( + "未知参数:{argument};使用 --help 查看帮助" + ))) + } + } + } + + if cookie.is_some() && cookie_stdin { + return Err(Error::InvalidPacket( + "--cookie 与 --cookie-stdin 不能同时使用".into(), + )); + } + let cookie = match (cookie, cookie_stdin) { + (Some(cookie), false) => cookie, + (None, true) => { + let mut input = String::new(); + io::stdin().read_to_string(&mut input)?; + let cookie = input.trim().to_owned(); + if cookie.is_empty() { + return Err(Error::InvalidPacket("标准输入中的 Cookie 为空".into())); + } + cookie + } + (None, false) => { + return Err(Error::InvalidPacket( + "缺少 --cookie 或 --cookie-stdin 参数".into(), + )) + } + (Some(_), true) => unreachable!("前置条件已检查"), + }; + let room_id = room_id.ok_or_else(|| Error::InvalidPacket("缺少 --room-id 参数".into()))?; + Ok(Some(Config { + cookie, + room_id, + duration: Duration::from_secs(seconds), + })) +} + +fn next_value(args: &mut impl Iterator, name: &str) -> Result { + args.next() + .ok_or_else(|| Error::InvalidPacket(format!("{name} 需要一个值"))) +} + +fn print_usage() { + eprintln!( + "\ +用法: + libilibili-capture --cookie 'SESSDATA=...; bili_jct=...; buvid3=...' --room-id 5050 [--seconds 60] + +选项: + -r, --room-id 要监听的直播间 ID + -s, --seconds <秒> 抓取时长,默认 60 秒 + --cookie <文本> 完整 Cookie 请求头文本 + --cookie-stdin 从标准输入读取完整 Cookie(更安全) + -h, --help 显示本帮助 + +stdout 为 JSON Lines,包含原始帧和包体的 Base64。运行状态仅写入 stderr。 +注意:命令行参数可能被同机其他用户读取;优先使用 --cookie-stdin 或 secret 管理器注入 Cookie。" + ); +} diff --git a/src/client.rs b/src/client.rs new file mode 100644 index 0000000..0eb0084 --- /dev/null +++ b/src/client.rs @@ -0,0 +1,308 @@ +use crate::{wbi, ApiError, Credentials, Error, Result, WbiKey}; +use reqwest::{ + header::{ + HeaderMap, HeaderValue, ACCEPT, ACCEPT_LANGUAGE, COOKIE, ORIGIN, REFERER, USER_AGENT, + }, + Method, +}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::sync::{Arc, RwLock}; + +const WEB_ORIGIN: &str = "https://www.bilibili.com"; +const LIVE_ORIGIN: &str = "https://live.bilibili.com"; + +/// Bilibili HTTP API 客户端。 +/// +/// 客户端可廉价克隆,克隆后共享连接池与已缓存的 WBI key。 +#[derive(Clone)] +pub struct Client { + pub(crate) http: reqwest::Client, + pub(crate) credentials: Credentials, + wbi_key: Arc>>, +} + +impl std::fmt::Debug for Client { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Client") + .field("credentials", &"[redacted]") + .finish_non_exhaustive() + } +} + +/// [`Client`] 的构建器,用于设置凭据和 User-Agent。 +#[derive(Clone, Debug)] +pub struct ClientBuilder { + credentials: Credentials, + user_agent: String, +} + +impl Default for ClientBuilder { + fn default() -> Self { + Self { + credentials: Credentials::default(), + user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36".into(), + } + } +} + +impl ClientBuilder { + /// 设置客户端使用的浏览器会话凭据。 + pub fn credentials(mut self, credentials: Credentials) -> Self { + self.credentials = credentials; + self + } + /// 设置请求的 User-Agent。 + pub fn user_agent(mut self, user_agent: impl Into) -> Self { + self.user_agent = user_agent.into(); + self + } + /// 创建客户端及其 HTTP 连接池。 + pub fn build(self) -> Result { + let mut headers = HeaderMap::new(); + headers.insert( + USER_AGENT, + HeaderValue::from_str(&self.user_agent) + .map_err(|_| Error::InvalidPacket("invalid user agent".into()))?, + ); + headers.insert(ORIGIN, HeaderValue::from_static(WEB_ORIGIN)); + headers.insert( + ACCEPT, + HeaderValue::from_static("application/json, text/plain, */*"), + ); + headers.insert( + ACCEPT_LANGUAGE, + HeaderValue::from_static("zh-CN,zh;q=0.9,en;q=0.8"), + ); + headers.insert( + REFERER, + HeaderValue::from_static("https://www.bilibili.com/"), + ); + if let Some(cookie) = self.credentials.cookie_header() { + headers.insert( + COOKIE, + HeaderValue::from_str(&cookie) + .map_err(|_| Error::InvalidPacket("invalid cookie header".into()))?, + ); + } + Ok(Client { + http: reqwest::Client::builder() + .default_headers(headers) + .build()?, + credentials: self.credentials, + wbi_key: Arc::new(RwLock::new(None)), + }) + } +} + +/// Bilibili 常见的 JSON 响应包裹结构。 +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct Response { + /// 业务状态码;`0` 表示成功。 + pub code: i64, + /// 业务错误消息。 + #[serde(default, alias = "msg")] + pub message: String, + /// Bilibili 缓存控制字段。 + #[serde(default)] + pub ttl: i64, + /// 实际业务数据。 + /// + /// 非成功响应通常不包含该字段。 + #[serde(default)] + pub data: Option, +} + +impl Response { + /// 在 `code == 0` 时取出 `data`,否则转换为 [`ApiError`]。 + pub fn into_data(self) -> Result { + if self.code == 0 { + self.data.ok_or_else(|| { + ApiError { + code: self.code, + message: if self.message.is_empty() { + "成功响应缺少 data 字段".into() + } else { + self.message + }, + } + .into() + }) + } else { + Err(ApiError { + code: self.code, + message: self.message, + } + .into()) + } + } +} + +impl Client { + /// 创建客户端构建器。 + pub fn builder() -> ClientBuilder { + ClientBuilder::default() + } + /// 创建不含登录凭据的匿名客户端。 + pub fn anonymous() -> Result { + Self::builder().build() + } + /// 使用给定凭据创建客户端。 + pub fn with_credentials(credentials: Credentials) -> Result { + Self::builder().credentials(credentials).build() + } + /// 获取客户端保存的凭据引用。 + pub fn credentials(&self) -> &Credentials { + &self.credentials + } + /// 访问直播相关接口。 + pub fn live(&self) -> crate::LiveApi<'_> { + crate::LiveApi::new(self) + } + /// 访问视频相关接口。 + pub fn video(&self) -> crate::VideoApi<'_> { + crate::VideoApi::new(self) + } + /// 访问用户、空间和关系接口。 + pub fn user(&self) -> crate::UserApi<'_> { + crate::UserApi::new(self) + } + /// 访问评论接口。 + pub fn comments(&self) -> crate::CommentApi<'_> { + crate::CommentApi::new(self) + } + /// 访问搜索接口。 + pub fn search(&self) -> crate::SearchApi<'_> { + crate::SearchApi::new(self) + } + + /// 调用任意公开 GET 端点并返回响应中的 `data`。 + pub async fn get( + &self, + url: &str, + query: Vec<(String, String)>, + ) -> Result { + self.send(Method::GET, url, query, None, false).await + } + /// 调用需要 WBI 签名的 GET 端点。 + /// + /// 会在首次调用时获取并缓存当前 WBI key。 + pub async fn get_wbi( + &self, + url: &str, + query: Vec<(String, String)>, + ) -> Result { + let key = self.wbi_key().await?; + let signed = key.sign(query); + self.send( + Method::GET, + &signed_url(url, &signed), + Vec::new(), + None, + false, + ) + .await + } + /// 发送需要登录态的表单 POST 请求。 + /// + /// 自动补充 `csrf` 与 `csrf_token`;缺少 `bili_jct` 时返回 [`Error::MissingCsrf`]。 + pub async fn post_form( + &self, + url: &str, + mut form: Vec<(String, String)>, + ) -> Result { + let csrf = self.credentials.csrf().ok_or(Error::MissingCsrf)?; + if !form.iter().any(|(k, _)| k == "csrf") { + form.push(("csrf".into(), csrf.into())); + } + if !form.iter().any(|(k, _)| k == "csrf_token") { + form.push(("csrf_token".into(), csrf.into())); + } + self.send(Method::POST, url, Vec::new(), Some(form), true) + .await + } + /// 发送同时需要 Cookie/CSRF 和 WBI 查询签名的表单 POST 请求。 + pub async fn post_form_wbi( + &self, + url: &str, + query: Vec<(String, String)>, + form: Vec<(String, String)>, + ) -> Result { + let csrf = self.credentials.csrf().ok_or(Error::MissingCsrf)?; + let mut form = form; + if !form.iter().any(|(k, _)| k == "csrf") { + form.push(("csrf".into(), csrf.into())); + } + if !form.iter().any(|(k, _)| k == "csrf_token") { + form.push(("csrf_token".into(), csrf.into())); + } + let key = self.wbi_key().await?; + let signed = key.sign(query); + self.send( + Method::POST, + &signed_url(url, &signed), + Vec::new(), + Some(form), + true, + ) + .await + } + + async fn send( + &self, + method: Method, + url: &str, + query: Vec<(String, String)>, + form: Option>, + live: bool, + ) -> Result { + let mut request = self.http.request(method, url).query(&query); + if live { + request = request + .header(ORIGIN, LIVE_ORIGIN) + .header(REFERER, "https://live.bilibili.com/"); + } + if let Some(form) = form { + request = request.form(&form); + } + let envelope: Response = request.send().await?.error_for_status()?.json().await?; + envelope + .into_data() + .and_then(|data| Ok(serde_json::from_value(data)?)) + } + + async fn wbi_key(&self) -> Result { + if let Some(key) = self.wbi_key.read().expect("WBI key lock poisoned").clone() { + return Ok(key); + } + #[derive(Deserialize)] + struct Nav { + wbi_img: Option, + } + #[derive(Deserialize)] + struct WbiImage { + img_url: String, + sub_url: String, + } + let nav: Nav = self + .get("https://api.bilibili.com/x/web-interface/nav", Vec::new()) + .await?; + let image = nav.wbi_img.ok_or(Error::MissingWbiKey)?; + let key = WbiKey::from_image_urls(&image.img_url, &image.sub_url)?; + *self.wbi_key.write().expect("WBI key lock poisoned") = Some(key.clone()); + Ok(key) + } +} + +fn signed_url(url: &str, params: &[(String, String)]) -> String { + let separator = if url.contains('?') { "&" } else { "?" }; + format!( + "{url}{separator}{}", + wbi::encode( + params + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())) + ) + ) +} diff --git a/src/endpoints.rs b/src/endpoints.rs new file mode 100644 index 0000000..e2ff8f4 --- /dev/null +++ b/src/endpoints.rs @@ -0,0 +1,628 @@ +//! 高层接口分组。 +//! +//! 所有快捷方法均返回 `serde_json::Value`:Bilibili 的响应字段变化频繁,这能在无需 +//! 发布新版本时保留新增字段。尚未提供快捷方法的端点可使用 [`crate::Client::get`]、 +//! [`crate::Client::get_wbi`] 与 [`crate::Client::post_form`] 调用。 + +use crate::{Client, Result}; +use serde_json::Value; + +fn q(items: impl IntoIterator) -> Vec<(String, String)> { + items + .into_iter() + .map(|(key, value)| (key.to_owned(), value)) + .collect() +} + +/// 直播间、分区、礼物与粉丝勋章接口组。 +pub struct LiveApi<'a> { + client: &'a Client, +} +impl<'a> LiveApi<'a> { + pub(crate) fn new(client: &'a Client) -> Self { + Self { client } + } + /// 解析直播间 ID,并返回真实房间号、主播 UID 与开播状态。 + pub async fn room_init(&self, room_id: u64) -> Result { + self.client + .get( + "https://api.live.bilibili.com/room/v1/Room/room_init", + q([("id", room_id.to_string())]), + ) + .await + } + /// 获取直播间基础信息。 + pub async fn room_info(&self, room_id: u64) -> Result { + self.client + .get( + "https://api.live.bilibili.com/room/v1/Room/get_info", + q([("room_id", room_id.to_string())]), + ) + .await + } + /// 根据主播 UID 查询其直播间信息。 + pub async fn room_info_by_uid(&self, uid: u64) -> Result { + self.client + .get( + "https://api.live.bilibili.com/room/v1/Room/getRoomInfoOld", + q([("mid", uid.to_string())]), + ) + .await + } + /// 批量获取直播间基础信息。 + pub async fn room_base_info(&self, room_ids: &[u64]) -> Result { + let ids = room_ids + .iter() + .map(u64::to_string) + .collect::>() + .join(","); + self.client + .get( + "https://api.live.bilibili.com/xlive/web-room/v1/index/getRoomBaseInfo", + q([("room_ids", ids), ("req_biz", "web_room_componet".into())]), + ) + .await + } + /// 通过 WBI 签名获取直播间聚合详情。 + pub async fn room_detail(&self, room_id: u64) -> Result { + self.client + .get_wbi( + "https://api.live.bilibili.com/xlive/web-room/v1/index/getInfoByRoom", + q([ + ("room_id", room_id.to_string()), + ("web_location", "444.8".into()), + ]), + ) + .await + } + /// 获取弹幕 WebSocket 的 token 和可用服务器列表。 + pub async fn danmu_info(&self, room_id: u64) -> Result { + self.client + .get_wbi( + "https://api.live.bilibili.com/xlive/web-room/v1/index/getDanmuInfo", + q([ + ("id", room_id.to_string()), + ("type", "0".into()), + ("web_location", "444.8".into()), + ]), + ) + .await + } + /// 获取直播流播放信息与 CDN 候选地址。 + /// + /// `quality` 是期望清晰度,例如 `10000` 表示原画。 + pub async fn play_info(&self, room_id: u64, quality: u32) -> Result { + self.client + .get( + "https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo", + q([ + ("room_id", room_id.to_string()), + ("protocol", "0,1".into()), + ("format", "0,1,2".into()), + ("codec", "0,1,2".into()), + ("qn", quality.to_string()), + ("platform", "web".into()), + ("ptype", "8".into()), + ]), + ) + .await + } + /// 获取全部直播分区。 + pub async fn areas(&self) -> Result { + self.client + .get( + "https://api.live.bilibili.com/xlive/web-interface/v1/index/getWebAreaList", + q([("source_id", "2".into())]), + ) + .await + } + /// 获取指定直播分区内的房间分页列表。 + pub async fn area_rooms( + &self, + parent_area_id: u64, + area_id: u64, + page: u32, + page_size: u32, + ) -> Result { + self.client + .get( + "https://api.live.bilibili.com/room/v3/area/getRoomList", + q([ + ("parent_area_id", parent_area_id.to_string()), + ("area_id", area_id.to_string()), + ("page", page.to_string()), + ("page_size", page_size.to_string()), + ("platform", "web".into()), + ]), + ) + .await + } + /// 获取直播首页推荐列表。 + pub async fn homepage(&self) -> Result { + self.client + .get( + "https://api.live.bilibili.com/xlive/web-interface/v1/webMain/getList", + q([("platform", "web".into())]), + ) + .await + } + /// 获取直播间礼物面板配置。 + pub async fn room_gift_config(&self, room_id: u64) -> Result { + self.client + .get( + "https://api.live.bilibili.com/xlive/web-room/v1/giftPanel/roomGiftConfig", + q([ + ("room_id", room_id.to_string()), + ("platform", "pc".into()), + ("source", "live".into()), + ]), + ) + .await + } + /// 获取直播间可展示的礼物列表。 + pub async fn room_gifts(&self, room_id: u64) -> Result { + self.client + .get( + "https://api.live.bilibili.com/xlive/web-room/v1/giftPanel/roomGiftList", + q([("room_id", room_id.to_string()), ("platform", "pc".into())]), + ) + .await + } + /// 获取直播间贡献榜或在线榜。 + pub async fn contribution_rank( + &self, + room_id: u64, + anchor_uid: u64, + page: u32, + page_size: u32, + ) -> Result { + self.client.get("https://api.live.bilibili.com/xlive/general-interface/v1/rank/queryContributionRank", q([ + ("room_id", room_id.to_string()), ("ruid", anchor_uid.to_string()), ("page", page.to_string()), + ("page_size", page_size.to_string()), ("type", "online_rank".into()), + ])).await + } + /// 获取直播间历史弹幕。 + pub async fn danmu_history(&self, room_id: u64) -> Result { + self.client + .get( + "https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory", + q([("roomid", room_id.to_string()), ("room_type", "0".into())]), + ) + .await + } + /// 获取直播间主播资料面板。 + pub async fn anchor_in_room(&self, room_id: u64) -> Result { + self.client + .get( + "https://api.live.bilibili.com/live_user/v1/UserInfo/get_anchor_in_room", + q([("roomid", room_id.to_string())]), + ) + .await + } + /// 获取当前登录用户的粉丝勋章列表。 + pub async fn my_medals(&self, page: u32, page_size: u32) -> Result { + self.client + .get( + "https://api.live.bilibili.com/xlive/app-ucenter/v1/user/GetMyMedals", + q([ + ("page", page.to_string()), + ("page_size", page_size.to_string()), + ]), + ) + .await + } + /// 佩戴指定粉丝勋章。 + /// + /// 此操作会改变账号状态,需要登录 Cookie 与 CSRF token。 + pub async fn wear_medal(&self, medal_id: u64) -> Result { + self.client + .post_form( + "https://api.live.bilibili.com/xlive/web-room/v1/fansMedal/wear", + q([("medal_id", medal_id.to_string())]), + ) + .await + } + /// 卸下当前佩戴的粉丝勋章。 + /// + /// 此操作会改变账号状态,需要登录 Cookie 与 CSRF token。 + pub async fn take_off_medal(&self) -> Result { + self.client + .post_form( + "https://api.live.bilibili.com/xlive/web-room/v1/fansMedal/take_off", + Vec::new(), + ) + .await + } + /// 向直播间发送弹幕。 + /// + /// 此操作会改变账号状态,需要登录 Cookie 与 CSRF token。 + pub async fn send_danmu(&self, room_id: u64, message: impl Into) -> Result { + self.client + .post_form( + "https://api.live.bilibili.com/msg/send", + q([ + ("roomid", room_id.to_string()), + ("msg", message.into()), + ("color", "16777215".into()), + ("fontsize", "25".into()), + ("mode", "1".into()), + ( + "rnd", + (std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs()) + .to_string(), + ), + ]), + ) + .await + } +} + +/// 视频详情、播放辅助与互动接口组。 +pub struct VideoApi<'a> { + client: &'a Client, +} +impl<'a> VideoApi<'a> { + pub(crate) fn new(client: &'a Client) -> Self { + Self { client } + } + /// 根据 BV 号获取视频详情。 + pub async fn view_by_bvid(&self, bvid: impl Into) -> Result { + self.client + .get( + "https://api.bilibili.com/x/web-interface/view", + q([("bvid", bvid.into())]), + ) + .await + } + /// 根据 AV 号获取视频详情。 + pub async fn view_by_aid(&self, aid: u64) -> Result { + self.client + .get( + "https://api.bilibili.com/x/web-interface/view", + q([("aid", aid.to_string())]), + ) + .await + } + /// 获取视频的分 P 列表。 + pub async fn pages(&self, bvid: impl Into) -> Result { + self.client + .get( + "https://api.bilibili.com/x/player/pagelist", + q([("bvid", bvid.into())]), + ) + .await + } + /// 获取视频当前在线观看人数。 + pub async fn online_total(&self, aid: u64, cid: u64) -> Result { + self.client + .get( + "https://api.bilibili.com/x/player/online/total", + q([("aid", aid.to_string()), ("cid", cid.to_string())]), + ) + .await + } + /// 获取当前用户与视频的互动关系,例如点赞和收藏状态。 + pub async fn archive_relation(&self, aid: u64) -> Result { + self.client + .get( + "https://api.bilibili.com/x/web-interface/archive/relation", + q([("aid", aid.to_string())]), + ) + .await + } + /// 获取视频标签。 + pub async fn tags(&self, aid: u64) -> Result { + self.client + .get( + "https://api.bilibili.com/x/tag/archive/tags", + q([("aid", aid.to_string())]), + ) + .await + } + /// 获取指定分 P 的字幕元数据。 + pub async fn subtitles(&self, aid: u64, cid: u64) -> Result { + self.client + .get( + "https://api.bilibili.com/x/v2/subtitle/web/view", + q([("aid", aid.to_string()), ("cid", cid.to_string())]), + ) + .await + } + /// 点赞或取消点赞视频。 + /// + /// `like` 为 `true` 时点赞,为 `false` 时取消点赞;需要登录 Cookie 与 CSRF token。 + pub async fn like(&self, aid: u64, like: bool) -> Result { + self.client + .post_form( + "https://api.bilibili.com/x/web-interface/archive/like", + q([ + ("aid", aid.to_string()), + ("like", if like { "1" } else { "2" }.into()), + ]), + ) + .await + } + /// 为视频投币。 + /// + /// `count` 为投币数量,`select_like` 表示是否同时点赞;需要登录 Cookie 与 CSRF token。 + pub async fn coin(&self, aid: u64, count: u8, select_like: bool) -> Result { + self.client + .post_form( + "https://api.bilibili.com/x/web-interface/coin/add", + q([ + ("aid", aid.to_string()), + ("multiply", count.to_string()), + ("select_like", if select_like { "1" } else { "0" }.into()), + ]), + ) + .await + } + /// 修改视频收藏夹归属。 + /// + /// 两个 ID 参数均使用逗号分隔的收藏夹 ID;需要登录 Cookie 与 CSRF token。 + pub async fn favourite( + &self, + aid: u64, + add_media_ids: impl Into, + del_media_ids: impl Into, + ) -> Result { + self.client + .post_form( + "https://api.bilibili.com/x/v3/fav/resource/deal", + q([ + ("rid", aid.to_string()), + ("type", "2".into()), + ("add_media_ids", add_media_ids.into()), + ("del_media_ids", del_media_ids.into()), + ]), + ) + .await + } +} + +/// 用户资料、空间、关系和动态接口组。 +pub struct UserApi<'a> { + client: &'a Client, +} +impl<'a> UserApi<'a> { + pub(crate) fn new(client: &'a Client) -> Self { + Self { client } + } + /// 获取当前登录状态及导航栏用户信息。 + pub async fn nav(&self) -> Result { + self.client + .get("https://api.bilibili.com/x/web-interface/nav", Vec::new()) + .await + } + /// 获取用户基础资料。 + pub async fn profile(&self, uid: u64) -> Result { + self.client + .get( + "https://api.bilibili.com/x/space/acc/info", + q([("mid", uid.to_string())]), + ) + .await + } + /// 通过 WBI 签名获取用户空间投稿列表。 + pub async fn space_videos(&self, uid: u64, page: u32, page_size: u32) -> Result { + self.client + .get_wbi( + "https://api.bilibili.com/x/space/wbi/arc/search", + q([ + ("mid", uid.to_string()), + ("pn", page.to_string()), + ("ps", page_size.to_string()), + ]), + ) + .await + } + /// 获取用户关注列表。 + pub async fn following(&self, uid: u64, page: u32, page_size: u32) -> Result { + self.client + .get( + "https://api.bilibili.com/x/relation/followings", + q([ + ("vmid", uid.to_string()), + ("pn", page.to_string()), + ("ps", page_size.to_string()), + ]), + ) + .await + } + /// 获取用户粉丝列表。 + pub async fn followers(&self, uid: u64, page: u32, page_size: u32) -> Result { + self.client + .get( + "https://api.bilibili.com/x/relation/fans", + q([ + ("vmid", uid.to_string()), + ("pn", page.to_string()), + ("ps", page_size.to_string()), + ]), + ) + .await + } + /// 修改与用户的关系。 + /// + /// `act` 的具体含义由 Bilibili 接口定义;需要登录 Cookie 与 CSRF token。 + pub async fn modify_relation(&self, uid: u64, act: u8) -> Result { + self.client + .post_form( + "https://api.bilibili.com/x/relation/modify", + q([("fid", uid.to_string()), ("act", act.to_string())]), + ) + .await + } + /// 获取用户空间动态列表。 + /// + /// `offset` 应使用上一次响应给出的分页游标;首次查询可传空字符串。 + pub async fn dynamic_space(&self, uid: u64, offset: impl Into) -> Result { + self.client + .get( + "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space", + q([ + ("host_mid", uid.to_string()), + ("offset", offset.into()), + ("timezone_offset", "-480".into()), + ]), + ) + .await + } + /// 获取单条动态详情。 + pub async fn dynamic_detail(&self, dynamic_id: impl Into) -> Result { + self.client + .get( + "https://api.bilibili.com/x/polymer/web-dynamic/v1/detail", + q([ + ("id", dynamic_id.into()), + ("timezone_offset", "-480".into()), + ]), + ) + .await + } +} + +/// 视频评论与评论互动接口组。 +pub struct CommentApi<'a> { + client: &'a Client, +} +impl<'a> CommentApi<'a> { + pub(crate) fn new(client: &'a Client) -> Self { + Self { client } + } + /// 获取视频评论分页列表。 + /// + /// `oid` 为视频 AV 号,`sort` 使用 Bilibili 定义的排序值。 + pub async fn list(&self, oid: u64, page: u32, page_size: u32, sort: u8) -> Result { + self.client + .get( + "https://api.bilibili.com/x/v2/reply", + q([ + ("type", "1".into()), + ("oid", oid.to_string()), + ("pn", page.to_string()), + ("ps", page_size.to_string()), + ("sort", sort.to_string()), + ]), + ) + .await + } + /// 通过 WBI 签名获取新版评论主楼列表。 + pub async fn list_wbi(&self, oid: u64, mode: u8) -> Result { + self.client + .get_wbi( + "https://api.bilibili.com/x/v2/reply/wbi/main", + q([ + ("type", "1".into()), + ("oid", oid.to_string()), + ("mode", mode.to_string()), + ]), + ) + .await + } + /// 获取某条主评论下的回复列表。 + pub async fn replies(&self, oid: u64, root_reply_id: u64, page: u32) -> Result { + self.client + .get( + "https://api.bilibili.com/x/v2/reply/reply", + q([ + ("type", "1".into()), + ("oid", oid.to_string()), + ("root", root_reply_id.to_string()), + ("pn", page.to_string()), + ("ps", "20".into()), + ]), + ) + .await + } + /// 发布评论或回复。 + /// + /// 传入 `root_reply_id` 时发布回复;需要登录 Cookie 与 CSRF token。 + pub async fn add( + &self, + oid: u64, + message: impl Into, + root_reply_id: Option, + ) -> Result { + let mut form = q([ + ("type", "1".into()), + ("oid", oid.to_string()), + ("message", message.into()), + ]); + if let Some(root) = root_reply_id { + form.push(("root".into(), root.to_string())); + } + self.client + .post_form("https://api.bilibili.com/x/v2/reply/add", form) + .await + } + /// 对评论执行点赞或取消点赞等动作。 + /// + /// `action` 的具体含义由 Bilibili 接口定义;需要登录 Cookie 与 CSRF token。 + pub async fn action(&self, oid: u64, reply_id: u64, action: u8) -> Result { + self.client + .post_form( + "https://api.bilibili.com/x/v2/reply/action", + q([ + ("type", "1".into()), + ("oid", oid.to_string()), + ("rpid", reply_id.to_string()), + ("action", action.to_string()), + ]), + ) + .await + } +} + +/// 全站搜索和搜索建议接口组。 +pub struct SearchApi<'a> { + client: &'a Client, +} +impl<'a> SearchApi<'a> { + pub(crate) fn new(client: &'a Client) -> Self { + Self { client } + } + /// 通过 WBI 签名进行综合搜索。 + pub async fn all(&self, keyword: impl Into, page: u32) -> Result { + self.client + .get_wbi( + "https://api.bilibili.com/x/web-interface/wbi/search/all/v2", + q([("keyword", keyword.into()), ("page", page.to_string())]), + ) + .await + } + /// 通过 WBI 签名搜索视频。 + pub async fn video(&self, keyword: impl Into, page: u32) -> Result { + self.client + .get_wbi( + "https://api.bilibili.com/x/web-interface/wbi/search/type", + q([ + ("search_type", "video".into()), + ("keyword", keyword.into()), + ("page", page.to_string()), + ]), + ) + .await + } + /// 获取关键词联想建议。 + pub async fn suggest(&self, keyword: impl Into) -> Result { + self.client + .get( + "https://api.bilibili.com/x/web-interface/suggest", + q([("term", keyword.into())]), + ) + .await + } + /// 通过 WBI 签名获取搜索默认词。 + pub async fn default_word(&self) -> Result { + self.client + .get_wbi( + "https://api.bilibili.com/x/web-interface/wbi/search/default", + Vec::new(), + ) + .await + } +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..15bdaa6 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,58 @@ +use thiserror::Error; + +/// crate 内所有可恢复操作使用的结果类型。 +pub type Result = std::result::Result; + +/// Bilibili 返回了非零业务状态码时的错误信息。 +#[derive(Debug, Clone, Error, PartialEq, Eq)] +#[error("Bilibili API returned code {code}: {message}")] +pub struct ApiError { + /// Bilibili 响应中的 `code`。 + pub code: i64, + /// Bilibili 响应中的 `message` 或 `msg`。 + pub message: String, +} + +/// 调用 API、签名或解析协议时可能发生的错误。 +#[derive(Debug, Error)] +pub enum Error { + /// HTTP 传输或状态码错误。 + #[error(transparent)] + Http(#[from] reqwest::Error), + /// URL 解析错误。 + #[error(transparent)] + Url(#[from] url::ParseError), + /// JSON 编码或解码错误。 + #[error(transparent)] + Json(#[from] serde_json::Error), + /// Bilibili 返回的业务错误。 + #[error(transparent)] + Api(#[from] ApiError), + /// 状态变更请求缺少 `bili_jct` CSRF token。 + #[error("this request requires credentials with a bili_jct CSRF token")] + MissingCsrf, + /// `/x/web-interface/nav` 未返回 WBI 图片 key。 + #[error("WBI key was absent from /x/web-interface/nav")] + MissingWbiKey, + /// WBI 图片 URL 不符合预期格式。 + #[error("invalid WBI image URL: {0}")] + InvalidWbiImageUrl(String), + /// 直播 WebSocket 数据包格式无效。 + #[error("invalid WebSocket packet: {0}")] + InvalidPacket(String), + /// WebSocket 建连或读写错误。 + #[cfg(feature = "websocket")] + #[error(transparent)] + WebSocket(Box), + /// WebSocket 压缩数据解压时发生的 I/O 错误。 + #[cfg(feature = "websocket")] + #[error(transparent)] + Io(#[from] std::io::Error), +} + +#[cfg(feature = "websocket")] +impl Error { + pub(crate) fn websocket(error: tokio_tungstenite::tungstenite::Error) -> Self { + Self::WebSocket(Box::new(error)) + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..a5fe1da --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,30 @@ +//! Bilibili Web 与直播接口的异步客户端。 +//! +//! 本 crate 不实现密码、二维码、验证码或 OAuth 登录流程。请通过 Bilibili 的正常登录页面 +//! 获得会话,再将 `SESSDATA` 和 `bili_jct` 传给 [`Credentials`]。会改变账号状态的 +//! Cookie 请求会自动携带 `csrf` 和 `csrf_token`。 +//! +//! ```no_run +//! use libilibili::Client; +//! +//! # async fn example() -> Result<(), libilibili::Error> { +//! let client = Client::anonymous()?; +//! let room = client.live().room_init(5050).await?; +//! println!("{room:#}"); +//! # Ok(()) } +//! ``` + +mod auth; +mod client; +mod endpoints; +mod error; +mod wbi; + +#[cfg(feature = "websocket")] +pub mod websocket; + +pub use auth::{Credentials, CredentialsBuilder}; +pub use client::{Client, ClientBuilder, Response}; +pub use endpoints::{CommentApi, LiveApi, SearchApi, UserApi, VideoApi}; +pub use error::{ApiError, Error, Result}; +pub use wbi::{WbiKey, WBI_MIXIN_TABLE}; diff --git a/src/wbi.rs b/src/wbi.rs new file mode 100644 index 0000000..c8af484 --- /dev/null +++ b/src/wbi.rs @@ -0,0 +1,130 @@ +use crate::{Error, Result}; +use md5::{Digest, Md5}; +use std::{ + collections::BTreeMap, + time::{SystemTime, UNIX_EPOCH}, +}; +use url::Url; + +/// 推导 Bilibili 短期 WBI mixin key 使用的公开置换表。 +/// +/// 导出该常量便于调用方离线复现签名。 +pub const WBI_MIXIN_TABLE: [usize; 64] = [ + 46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49, 33, 9, 42, 19, 29, + 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40, 61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, + 54, 21, 56, 59, 6, 63, 57, 62, 11, 36, 20, 34, 44, 52, +]; + +/// 从 `/x/web-interface/nav` 的 `data.wbi_img` 推导出的 WBI mixin key。 +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WbiKey(String); + +impl WbiKey { + /// 根据两张 WBI 图片的 URL 推导 mixin key。 + pub fn from_image_urls(img_url: &str, sub_url: &str) -> Result { + let source = format!("{}{}", image_stem(img_url)?, image_stem(sub_url)?); + let mixed: String = WBI_MIXIN_TABLE + .iter() + .filter_map(|&index| source.chars().nth(index)) + .collect(); + Ok(Self(mixed.chars().take(32).collect())) + } + /// 以字符串形式返回 mixin key。 + pub fn as_str(&self) -> &str { + &self.0 + } + + /// 为参数加入 `wts` 与 `w_rid` 签名。 + /// + /// 已存在的 `wts` 和 `w_rid` 会被替换;业务参数按键名排序,且会移除 + /// WBI 规则中不参与签名的字符。 + pub fn sign( + &self, + parameters: impl IntoIterator, + ) -> Vec<(String, String)> { + let mut params: BTreeMap = parameters + .into_iter() + .filter(|(key, _)| key != "wts" && key != "w_rid") + .map(|(key, value)| (key, clean_value(&value))) + .collect(); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() + .to_string(); + params.insert("wts".to_owned(), now); + let query = encode( + params + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())), + ); + let mut hasher = Md5::new(); + hasher.update(query.as_bytes()); + hasher.update(self.0.as_bytes()); + params.insert("w_rid".to_owned(), format!("{:x}", hasher.finalize())); + params.into_iter().collect() + } +} + +fn image_stem(image_url: &str) -> Result { + let url = Url::parse(image_url).map_err(|_| Error::InvalidWbiImageUrl(image_url.to_owned()))?; + let filename = url + .path_segments() + .and_then(Iterator::last) + .and_then(|name| name.split('.').next()) + .filter(|name| !name.is_empty()) + .ok_or_else(|| Error::InvalidWbiImageUrl(image_url.to_owned()))?; + Ok(filename.to_owned()) +} + +fn clean_value(value: &str) -> String { + value.chars().filter(|ch| !"!'()*".contains(*ch)).collect() +} + +pub(crate) fn encode<'a>(params: impl IntoIterator) -> String { + params + .into_iter() + .map(|(key, value)| format!("{}={}", percent_encode(key), percent_encode(value))) + .collect::>() + .join("&") +} + +fn percent_encode(value: &str) -> String { + value + .bytes() + .flat_map(|byte| match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + vec![byte as char] + } + _ => format!("%{byte:02X}").chars().collect(), + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn derives_the_published_mixin_key() { + let key = WbiKey::from_image_urls( + "https://i0.hdslb.com/bfs/wbi/7cd084941338484aae1ad9425b84077c.png", + "https://i0.hdslb.com/bfs/wbi/4932caff0ff746eab6f01bf08b70ac45.png", + ) + .unwrap(); + assert_eq!(key.as_str(), "ea1db124af3c7062474693fa704f4ff8"); + } + #[test] + fn signing_sorts_and_cleans_values() { + let key = WbiKey("01234567890123456789012345678901".into()); + let signed = key.sign([ + (String::from("z"), String::from("a!b")), + (String::from("a"), String::from("x")), + ]); + assert_eq!(signed[0], ("a".into(), "x".into())); + assert_eq!( + signed.iter().find(|(key, _)| key == "z"), + Some(&("z".into(), "ab".into())) + ); + assert!(signed.iter().any(|(k, _)| k == "w_rid")); + } +} diff --git a/src/websocket.rs b/src/websocket.rs new file mode 100644 index 0000000..ab18351 --- /dev/null +++ b/src/websocket.rs @@ -0,0 +1,1935 @@ +//! 直播弹幕 WebSocket 协议支持。 +//! +//! [`LiveWebSocket::connect`] 会通过 WBI 获取直播间短期 token,只连接 Bilibili +//! 弹幕主机,并立即发送操作码为 7 的认证包。 + +use crate::{Client, Error, Result}; +use brotli::Decompressor; +use flate2::read::ZlibDecoder; +use futures_util::{SinkExt, StreamExt}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::{HashMap, VecDeque}; +use std::io::Read; +use tokio::net::TcpStream; +use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream}; + +const HEADER_LEN: usize = 16; + +/// 一个已解析但尚未按业务类型解释的直播 WebSocket 数据包。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Packet { + /// 协议版本:`0` 为 JSON、`1` 为人气值、`2` 为 zlib、`3` 为 brotli。 + pub version: u16, + /// 操作码,例如 `3` 表示人气值、`5` 表示服务端推送、`8` 表示认证回复。 + pub operation: u32, + /// 去除 16 字节包头后的原始数据体。 + pub body: Vec, +} + +/// 由直播 WebSocket 数据包解析出的事件。 +#[derive(Debug, Clone, PartialEq)] +pub enum LiveEvent { + /// 操作码为 5 的命令,例如 `DANMU_MSG`、`SEND_GIFT` 或 `LIVE`。 + /// + /// 命令会按 `cmd` 分发为 [`LiveCommand`] 的强类型变体。 + Command(Box), + /// 服务端返回的直播间人气值。 + Popularity(u32), + /// 操作码为 8 的 JSON 认证结果。 + Auth(Value), + /// 当前未被进一步解释的数据包。 + Unknown(Packet), +} + +/// 直播间推送命令的强类型表示。 +/// +/// 已知命令会反序列化为对应结构体,每个结构体均通过 `extra` 保留未预期字段。 +/// 未识别的命令使用 [`LiveCommand::Unknown`];已识别但字段不符合已知结构的命令 +/// 使用 [`LiveCommand::Invalid`],两者都会保留完整原始 JSON。 +#[derive(Debug, Clone, PartialEq)] +pub enum LiveCommand { + /// 普通弹幕消息。 + Danmu(Box), + /// 礼物消息。 + Gift(Box), + /// 连击送礼消息。 + ComboSend(Box), + /// 用户点赞消息。 + LikeClick(Box), + /// 直播间点赞计数变化消息。 + LikeUpdate(Box), + /// 直播间点赞提示消息。 + LikeNotice(Box), + /// 高能榜人数变化消息。 + OnlineRankCount(Box), + /// 看过人数变化消息。 + WatchedChange(Box), + /// 一批下播房间列表消息。 + StopLiveRoomList(Box), + /// 礼物星球进度消息。 + GiftStarProcess(Box), + /// 高能榜 protobuf 消息的外层载荷。 + OnlineRankV3(Box), + /// 互动 protobuf 消息的外层载荷。 + InteractWordV2(Box), + /// 大航海购买消息。 + GuardBuy(Box), + /// 醒目留言消息。 + SuperChat(Box), + /// 用户进入、关注或分享等互动消息。 + InteractWord(Box), + /// 直播间标题或分区变更消息。 + RoomChange(Box), + /// 直播开始消息。 + Live(Box), + /// 直播结束消息。 + Preparing(Box), + /// crate 当前未支持的命令。 + Unknown { + /// 原始 `cmd` 字段;缺失或非字符串时为 `None`。 + command: Option, + /// 完整原始 JSON。 + raw: Value, + }, + /// 已支持的命令无法反序列化为预期结构。 + Invalid { + /// 服务端原始 `cmd` 字段。 + command: Option, + /// 完整原始 JSON。 + raw: Value, + /// serde 产生的解析错误文本。 + error: String, + }, +} + +/// 普通弹幕消息。 +/// +/// `DANMU_MSG.info` 是异构数组。本类型按文档中的稳定索引进行手工、尽力而为的解析: +/// 可识别内容会映射到具名强类型字段,未知索引与类型不匹配的数据保存在 +/// [`DanmuMessage::unknown_info`],不会导致整条事件被丢弃。 +#[derive(Debug, Clone, PartialEq)] +pub struct DanmuMessage { + /// 服务端原始命令名,可能含有冒号后缀。 + pub cmd: String, + /// 弹幕元信息,例如颜色、发送时间和弹幕类型。 + pub metadata: DanmuMetadata, + /// 弹幕正文。 + pub text: Option, + /// 发送者信息。 + pub sender: DanmuSender, + /// 发送者佩戴的粉丝勋章;没有勋章时为 `None`。 + pub fans_medal: Option, + /// 发送者的用户等级。 + pub user_level: Option, + /// 发送者的头衔。 + pub title: Option, + /// 用户身份或守护等级。 + pub guard_level: Option, + /// 弹幕校验与时间戳信息。 + pub timestamp: Option, + /// 弹幕扩展信息。 + pub extension: Option, + /// `info` 数组中未知的索引或类型不符合预期的原始值。 + pub unknown_info: HashMap, + /// 新版弹幕的辅助字段。 + pub dm_v2: Option, + /// 未被当前版本建模的顶层字段。 + pub extra: HashMap, +} + +/// [`DanmuMessage`] 的元信息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct DanmuMetadata { + /// 十进制 RGB 弹幕颜色。 + pub color: Option, + /// 服务端记录的毫秒级时间戳。 + pub sent_at_ms: Option, + /// Bilibili 定义的弹幕类型。 + pub danmu_type: Option, + /// 渐变终止色。 + /// + /// 当前抓取样本为单个十进制颜色值;其他形态保留在 [`DanmuMetadata::extra`]。 + pub gradient_color: Option, + /// 元信息数组中未建模的索引。 + pub extra: HashMap, +} + +/// [`DanmuMessage`] 的发送者信息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct DanmuSender { + /// 用户 UID。 + pub uid: Option, + /// 用户昵称。 + pub uname: Option, + /// 是否为房管。 + pub is_admin: Option, + /// 是否为大会员。 + pub is_vip: Option, + /// 是否为年度大会员。 + pub is_svip: Option, + /// 用户等级。 + pub rank: Option, + /// 昵称颜色。 + pub name_color: Option, + /// 发送者数组中未建模的索引。 + pub extra: HashMap, +} + +/// 粉丝勋章信息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct FansMedal { + /// 勋章等级。 + pub level: Option, + /// 勋章名称。 + pub name: Option, + /// 主播昵称。 + pub anchor_name: Option, + /// 主播直播间 ID。 + pub anchor_room_id: Option, + /// 勋章颜色。 + pub color: Option, + /// 大航海等级。 + pub guard_level: Option, + /// 勋章数组中未建模的索引。 + pub extra: HashMap, +} + +/// 用户等级信息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct UserLevel { + /// 用户等级。 + pub level: Option, + /// 十进制等级颜色。 + pub color: Option, + /// 等级排名文字。 + pub rank_text: Option, + /// 用户等级数组中未建模的索引。 + pub extra: HashMap, +} + +/// 用户头衔信息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct UserTitle { + /// 头衔名称。 + pub name: Option, + /// 头衔图标 URL。 + pub icon: Option, + /// 头衔数组中未建模的索引。 + pub extra: HashMap, +} + +/// 弹幕校验与时间戳信息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct DanmuTimestamp { + /// 服务端校验字符串。 + pub ct: Option, + /// Unix 秒级时间戳。 + pub ts: Option, + /// 未建模字段。 + pub extra: HashMap, +} + +/// 弹幕的扩展信息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct DanmuExtension { + /// Bilibili 在扩展对象中返回的 JSON 字符串。 + pub extra_json: Option, + /// 未建模字段。 + pub extra: HashMap, +} + +/// 礼物消息。 +/// +/// 实际 WebSocket 结构将礼物字段置于 `data` 对象,本类型按该层级手工解析。 +#[derive(Debug, Clone, PartialEq)] +pub struct GiftMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 礼物业务数据。 + pub data: GiftData, + /// 弹幕区域信息。 + pub danmu: Option, + /// 服务端消息 ID。 + pub message_id: Option, + /// 服务端是否要求客户端确认。 + pub requires_ack: Option, + /// 服务端消息类型。 + pub message_type: Option, + /// 服务端发送时间。 + pub sent_at: Option, + /// 未被当前版本建模的顶层字段。 + pub extra: HashMap, +} + +/// [`GiftMessage`] 的礼物业务数据。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct GiftData { + /// 送礼用户 UID。 + pub uid: Option, + /// 送礼用户昵称。 + pub uname: Option, + /// 礼物 ID。 + pub gift_id: Option, + /// 礼物名称。 + pub gift_name: Option, + /// 礼物数量。 + pub num: Option, + /// 单个礼物价格。 + pub price: Option, + /// 实付总额。 + pub total_coin: Option, + /// 货币类型,例如 `gold` 或 `silver`。 + pub coin_type: Option, + /// 动作文案。 + pub action: Option, + /// 用户财富等级。 + pub wealth_level: Option, + /// 大航海等级。 + pub guard_level: Option, + /// 粉丝勋章信息。 + pub medal: Option, + /// 未被当前版本建模的 `data` 字段。 + pub extra: HashMap, +} + +/// 礼物消息中的粉丝勋章信息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct GiftMedalInfo { + /// 勋章等级。 + pub level: Option, + /// 勋章名称。 + pub name: Option, + /// 勋章所属主播昵称。 + pub anchor_name: Option, + /// 大航海等级。 + pub guard_level: Option, + /// 未被当前版本建模的字段。 + pub extra: HashMap, +} + +/// 礼物消息的弹幕区域信息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct GiftDanmu { + /// 弹幕区域。 + pub area: Option, + /// 未被当前版本建模的字段。 + pub extra: HashMap, +} + +/// 连击送礼消息。 +#[derive(Debug, Clone, PartialEq)] +pub struct ComboSendMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 连击送礼业务数据。 + pub data: ComboSendData, + /// 未被当前版本建模的顶层字段。 + pub extra: HashMap, +} + +/// [`ComboSendMessage`] 的连击送礼业务数据。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct ComboSendData { + /// 送礼用户 UID。 + pub uid: Option, + /// 送礼用户昵称。 + pub uname: Option, + /// 礼物 ID。 + pub gift_id: Option, + /// 礼物名称。 + pub gift_name: Option, + /// 本次礼物数量。 + pub num: Option, + /// 单个礼物价格。 + pub price: Option, + /// 本次实付总额。 + pub total_coin: Option, + /// 货币类型,例如 `gold`。 + pub coin_type: Option, + /// 动作文案。 + pub action: Option, + /// 连击 ID。 + pub combo_id: Option, + /// 批次连击 ID。 + pub batch_combo_id: Option, + /// 当前连击数量。 + pub combo_num: Option, + /// 当前批次连击数量。 + pub batch_combo_num: Option, + /// 连击累计实付总额。 + pub combo_total_coin: Option, + /// 大航海等级。 + pub guard_level: Option, + /// 粉丝勋章信息。 + pub medal_info: Option, + /// 未被当前版本建模的 `data` 字段。 + pub extra: HashMap, +} + +/// 连击送礼消息中的粉丝勋章信息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct ComboSendMedalInfo { + /// 勋章等级。 + pub level: Option, + /// 勋章名称。 + pub name: Option, + /// 勋章所属主播昵称。 + pub anchor_name: Option, + /// 大航海等级。 + pub guard_level: Option, + /// 未被当前版本建模的字段。 + pub extra: HashMap, +} + +/// 用户点赞消息。 +#[derive(Debug, Clone, PartialEq)] +pub struct LikeClickMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 点赞业务数据。 + pub data: LikeClickData, + /// 未被当前版本建模的顶层字段。 + pub extra: HashMap, +} + +/// [`LikeClickMessage`] 的点赞业务数据。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct LikeClickData { + /// 点赞用户 UID。 + pub uid: Option, + /// 点赞用户昵称。 + pub uname: Option, + /// 点赞文案。 + pub like_text: Option, + /// 当前点赞计数。 + pub like_count: Option, + /// 是否为点赞操作。 + pub is_like: Option, + /// 点赞图标 URL。 + pub icon: Option, + /// 粉丝勋章信息。 + pub fans_medal: Option, + /// 用户贡献信息。 + pub contribution_info: Option, + /// 用户身份标识。 + pub identities: Vec, + /// 弹幕评分。 + pub dmscore: Option, + /// 未被当前版本建模的 `data` 字段。 + pub extra: HashMap, +} + +/// 点赞消息中的粉丝勋章信息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct LikeFansMedalInfo { + /// 勋章等级。 + pub level: Option, + /// 勋章名称。 + pub name: Option, + /// 勋章颜色。 + pub color: Option, + /// 渐变起始颜色。 + pub color_start: Option, + /// 渐变结束颜色。 + pub color_end: Option, + /// 边框颜色。 + pub color_border: Option, + /// 勋章所属直播间 ID。 + pub anchor_room_id: Option, + /// 勋章所属主播昵称。 + pub anchor_name: Option, + /// 大航海等级。 + pub guard_level: Option, + /// 未被当前版本建模的字段。 + pub extra: HashMap, +} + +/// 点赞消息中的用户贡献信息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct LikeContributionInfo { + /// 贡献等级。 + pub grade: Option, + /// 未被当前版本建模的字段。 + pub extra: HashMap, +} + +/// 直播间点赞计数变化消息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct LikeUpdateMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 直播间当前点赞计数。 + pub click_count: Option, + /// 未被当前版本建模或类型不符合预期的 `data` 字段。 + pub data_extra: HashMap, + /// 未被当前版本建模的顶层字段。 + pub extra: HashMap, +} + +/// 直播间点赞提示消息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct LikeNoticeMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 直播间当前点赞计数。 + pub like_count: Option, + /// 服务端定义的提示消息类型。 + pub message_type: Option, + /// 组成提示文案的片段。 + pub content_segments: Vec, + /// `content_segments` 中不是对象的原始条目。 + pub unknown_content_segments: HashMap, + /// 未被当前版本建模或类型不符合预期的 `data` 字段。 + pub data_extra: HashMap, + /// 未被当前版本建模的顶层字段。 + pub extra: HashMap, +} + +/// [`LikeNoticeMessage`] 提示文案中的一个片段。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct LikeNoticeContentSegment { + /// 服务端定义的片段类型。 + pub kind: Option, + /// 片段文本。 + pub text: Option, + /// 未被当前版本建模的字段。 + pub extra: HashMap, +} + +/// 高能榜人数变化消息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct OnlineRankCountMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 高能榜人数。 + pub count: Option, + /// 高能榜人数显示文本。 + pub count_text: Option, + /// 在线人数。 + pub online_count: Option, + /// 在线人数显示文本。 + pub online_count_text: Option, + /// 未被当前版本建模的字段。 + pub extra: HashMap, +} + +/// 看过人数变化消息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct WatchedChangeMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 看过人数。 + pub watched_count: Option, + /// 小字号显示文本。 + pub text_small: Option, + /// 大字号显示文本。 + pub text_large: Option, + /// 未被当前版本建模的字段。 + pub extra: HashMap, +} + +/// 一批下播房间列表消息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct StopLiveRoomListMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 已下播的房间 ID 列表。 + pub room_ids: Vec, + /// 未被当前版本建模的字段。 + pub extra: HashMap, +} + +/// 礼物星球进度消息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct GiftStarProcessMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 当前进度名称。 + pub name: Option, + /// 当前数量。 + pub current: Option, + /// 目标数量。 + pub total: Option, + /// 服务端版本号。 + pub version: Option, + /// 未被当前版本建模的字段。 + pub extra: HashMap, +} + +/// 含 protobuf Base64 载荷的推送消息。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct ProtobufPayloadMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// Base64 编码的 protobuf 数据。 + pub pb_base64: String, + /// 弹幕评分。 + pub dm_score: Option, + /// 未被当前版本建模的顶层或 `data` 字段。 + pub extra: HashMap, +} + +/// 大航海购买消息。 +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct GuardBuyMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 购买用户 UID。 + pub uid: u64, + /// 购买用户昵称。 + pub username: String, + /// 舰队名称。 + pub gift_name: String, + /// 购买数量。 + pub num: u64, + /// 舰队等级,通常 1=总督、2=提督、3=舰长。 + pub guard_level: u8, + /// 未被当前版本建模的顶层字段。 + #[serde(default, flatten)] + pub extra: HashMap, +} + +/// 醒目留言消息。 +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct SuperChatMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 醒目留言的具体数据。 + pub data: SuperChatData, + /// 未被当前版本建模的顶层字段。 + #[serde(default, flatten)] + pub extra: HashMap, +} + +/// [`SuperChatMessage`] 的业务数据。 +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct SuperChatData { + /// 发送用户 UID。 + pub uid: u64, + /// 醒目留言文本。 + pub message: String, + /// 醒目留言价格。 + pub price: u64, + /// 未被当前版本建模的字段。 + #[serde(default, flatten)] + pub extra: HashMap, +} + +/// 用户进入、关注或分享等互动消息。 +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct InteractWordMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 互动事件的具体数据。 + pub data: InteractWordData, + /// 未被当前版本建模的顶层字段。 + #[serde(default, flatten)] + pub extra: HashMap, +} + +/// [`InteractWordMessage`] 的业务数据。 +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct InteractWordData { + /// 触发互动的用户 UID。 + pub uid: u64, + /// 触发互动的用户昵称。 + pub uname: String, + /// 互动类型,通常 1=进入、2=关注、3=分享。 + pub msg_type: u8, + /// 未被当前版本建模的字段。 + #[serde(default, flatten)] + pub extra: HashMap, +} + +/// 直播间标题或分区发生变化时的消息。 +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct RoomChangeMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 当前直播标题。 + #[serde(default)] + pub title: Option, + /// 当前子分区名称。 + #[serde(default)] + pub area_name: Option, + /// 当前父分区名称。 + #[serde(default)] + pub parent_area_name: Option, + /// 未被当前版本建模的顶层字段。 + #[serde(default, flatten)] + pub extra: HashMap, +} + +/// 开播或下播状态消息。 +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct LiveStatusMessage { + /// 服务端原始命令名。 + pub cmd: String, + /// 直播间 ID;部分推送可能省略该字段。 + #[serde(default)] + pub roomid: Option, + /// 未被当前版本建模的顶层字段。 + #[serde(default, flatten)] + pub extra: HashMap, +} + +/// 将操作码 5 的原始 JSON 按 `cmd` 分发为 [`LiveCommand`]。 +/// +/// 对带冒号后缀的命令(例如 `DANMU_MSG:4:0`)按冒号前的基础命令名分发。 +pub fn parse_command(value: Value) -> LiveCommand { + let command = value.get("cmd").and_then(Value::as_str).map(str::to_owned); + let normalized = command + .as_deref() + .map(|name| name.split(':').next().unwrap_or(name)); + + macro_rules! parse_as { + ($type:ty, $variant:ident) => { + match serde_json::from_value::<$type>(value.clone()) { + Ok(message) => LiveCommand::$variant(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error: error.to_string(), + }, + } + }; + } + + match normalized { + Some("DANMU_MSG") => match parse_danmu(&value) { + Ok(message) => LiveCommand::Danmu(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error, + }, + }, + Some("SEND_GIFT") => match parse_gift(&value) { + Ok(message) => LiveCommand::Gift(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error, + }, + }, + Some("COMBO_SEND") => match parse_combo_send(&value) { + Ok(message) => LiveCommand::ComboSend(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error, + }, + }, + Some("LIKE_INFO_V3_CLICK") => match parse_like_click(&value) { + Ok(message) => LiveCommand::LikeClick(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error, + }, + }, + Some("LIKE_INFO_V3_UPDATE") => match parse_like_update(&value) { + Ok(message) => LiveCommand::LikeUpdate(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error, + }, + }, + Some("LIKE_INFO_V3_NOTICE") => match parse_like_notice(&value) { + Ok(message) => LiveCommand::LikeNotice(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error, + }, + }, + Some("ONLINE_RANK_COUNT") => match parse_online_rank_count(&value) { + Ok(message) => LiveCommand::OnlineRankCount(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error, + }, + }, + Some("WATCHED_CHANGE") => match parse_watched_change(&value) { + Ok(message) => LiveCommand::WatchedChange(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error, + }, + }, + Some("STOP_LIVE_ROOM_LIST") => match parse_stop_live_room_list(&value) { + Ok(message) => LiveCommand::StopLiveRoomList(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error, + }, + }, + Some("WIDGET_GIFT_STAR_PROCESS_V2") => match parse_gift_star_process(&value) { + Ok(message) => LiveCommand::GiftStarProcess(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error, + }, + }, + Some("ONLINE_RANK_V3") => match parse_protobuf_payload(&value) { + Ok(message) => LiveCommand::OnlineRankV3(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error, + }, + }, + Some("INTERACT_WORD_V2") => match parse_protobuf_payload(&value) { + Ok(message) => LiveCommand::InteractWordV2(Box::new(message)), + Err(error) => LiveCommand::Invalid { + command, + raw: value, + error, + }, + }, + Some("GUARD_BUY") => parse_as!(GuardBuyMessage, GuardBuy), + Some("SUPER_CHAT_MESSAGE") => parse_as!(SuperChatMessage, SuperChat), + Some("INTERACT_WORD") => parse_as!(InteractWordMessage, InteractWord), + Some("ROOM_CHANGE") => parse_as!(RoomChangeMessage, RoomChange), + Some("LIVE") => parse_as!(LiveStatusMessage, Live), + Some("PREPARING") => parse_as!(LiveStatusMessage, Preparing), + _ => LiveCommand::Unknown { + command, + raw: value, + }, + } +} + +fn parse_gift(value: &Value) -> std::result::Result { + let data = value + .get("data") + .ok_or_else(|| "SEND_GIFT 缺少 data 字段".to_owned())?; + let data_object = data + .as_object() + .ok_or_else(|| "SEND_GIFT.data 不是对象".to_owned())?; + let medal = data_object.get("medal_info").and_then(parse_gift_medal); + let danmu = value.get("danmu").and_then(parse_gift_danmu); + Ok(GiftMessage { + cmd: value.get("cmd").and_then(value_string).unwrap_or_default(), + data: GiftData { + uid: data_object.get("uid").and_then(value_u64), + uname: data_object.get("uname").and_then(value_string), + gift_id: data_object.get("giftId").and_then(value_u64), + gift_name: data_object.get("giftName").and_then(value_string), + num: data_object.get("num").and_then(value_u64), + price: data_object.get("price").and_then(value_u64), + total_coin: data_object.get("total_coin").and_then(value_u64), + coin_type: data_object.get("coin_type").and_then(value_string), + action: data_object.get("action").and_then(value_string), + wealth_level: data_object.get("wealth_level").and_then(value_u32), + guard_level: data_object.get("guard_level").and_then(value_u8), + medal, + extra: object_extra( + data, + &[ + "uid", + "uname", + "giftId", + "giftName", + "num", + "price", + "total_coin", + "coin_type", + "action", + "wealth_level", + "guard_level", + "medal_info", + ], + ), + }, + danmu, + message_id: value.get("msg_id").and_then(value_lossless_string), + requires_ack: value.get("p_is_ack").and_then(value_bool), + message_type: value.get("p_msg_type").and_then(value_u32), + sent_at: value.get("send_time").and_then(value_u64), + extra: object_extra( + value, + &[ + "cmd", + "data", + "danmu", + "msg_id", + "p_is_ack", + "p_msg_type", + "send_time", + ], + ), + }) +} + +fn parse_gift_medal(value: &Value) -> Option { + let object = value.as_object()?; + Some(GiftMedalInfo { + level: object.get("medal_level").and_then(value_u8), + name: object.get("medal_name").and_then(value_string), + anchor_name: object.get("anchor_uname").and_then(value_string), + guard_level: object.get("guard_level").and_then(value_u8), + extra: object_extra( + value, + &["medal_level", "medal_name", "anchor_uname", "guard_level"], + ), + }) +} + +fn parse_gift_danmu(value: &Value) -> Option { + let object = value.as_object()?; + Some(GiftDanmu { + area: object.get("area").and_then(value_u32), + extra: object_extra(value, &["area"]), + }) +} + +fn parse_combo_send(value: &Value) -> std::result::Result { + let data = command_data(value, "COMBO_SEND")?; + let medal_info = data.get("medal_info").and_then(parse_combo_send_medal); + Ok(ComboSendMessage { + cmd: value.get("cmd").and_then(value_string).unwrap_or_default(), + data: ComboSendData { + uid: data.get("uid").and_then(value_u64), + uname: data.get("uname").and_then(value_string), + gift_id: data + .get("gift_id") + .or_else(|| data.get("giftId")) + .and_then(value_u64), + gift_name: data.get("gift_name").and_then(value_string), + num: data.get("num").and_then(value_u64), + price: data.get("price").and_then(value_u64), + total_coin: data.get("total_coin").and_then(value_u64), + coin_type: data.get("coin_type").and_then(value_string), + action: data.get("action").and_then(value_string), + combo_id: data.get("combo_id").and_then(value_lossless_string), + batch_combo_id: data.get("batch_combo_id").and_then(value_lossless_string), + combo_num: data.get("combo_num").and_then(value_u64), + batch_combo_num: data.get("batch_combo_num").and_then(value_u64), + combo_total_coin: data.get("combo_total_coin").and_then(value_u64), + guard_level: data.get("guard_level").and_then(value_u8), + medal_info, + extra: object_extra_with_invalid( + &Value::Object(data.clone()), + &[ + ("uid", data.get("uid").and_then(value_u64).is_some()), + ("uname", data.get("uname").and_then(value_string).is_some()), + ("gift_id", data.get("gift_id").and_then(value_u64).is_some()), + ("giftId", data.get("giftId").and_then(value_u64).is_some()), + ( + "gift_name", + data.get("gift_name").and_then(value_string).is_some(), + ), + ("num", data.get("num").and_then(value_u64).is_some()), + ("price", data.get("price").and_then(value_u64).is_some()), + ( + "total_coin", + data.get("total_coin").and_then(value_u64).is_some(), + ), + ( + "coin_type", + data.get("coin_type").and_then(value_string).is_some(), + ), + ( + "action", + data.get("action").and_then(value_string).is_some(), + ), + ( + "combo_id", + data.get("combo_id") + .and_then(value_lossless_string) + .is_some(), + ), + ( + "batch_combo_id", + data.get("batch_combo_id") + .and_then(value_lossless_string) + .is_some(), + ), + ( + "combo_num", + data.get("combo_num").and_then(value_u64).is_some(), + ), + ( + "batch_combo_num", + data.get("batch_combo_num").and_then(value_u64).is_some(), + ), + ( + "combo_total_coin", + data.get("combo_total_coin").and_then(value_u64).is_some(), + ), + ( + "guard_level", + data.get("guard_level").and_then(value_u8).is_some(), + ), + ( + "medal_info", + data.get("medal_info") + .and_then(parse_combo_send_medal) + .is_some(), + ), + ], + ), + }, + extra: object_extra(value, &["cmd", "data"]), + }) +} + +fn parse_combo_send_medal(value: &Value) -> Option { + let object = value.as_object()?; + Some(ComboSendMedalInfo { + level: object.get("medal_level").and_then(value_u8), + name: object.get("medal_name").and_then(value_string), + anchor_name: object.get("anchor_uname").and_then(value_string), + guard_level: object.get("guard_level").and_then(value_u8), + extra: object_extra_with_invalid( + value, + &[ + ( + "medal_level", + object.get("medal_level").and_then(value_u8).is_some(), + ), + ( + "medal_name", + object.get("medal_name").and_then(value_string).is_some(), + ), + ( + "anchor_uname", + object.get("anchor_uname").and_then(value_string).is_some(), + ), + ( + "guard_level", + object.get("guard_level").and_then(value_u8).is_some(), + ), + ], + ), + }) +} + +fn parse_like_click(value: &Value) -> std::result::Result { + let data = command_data(value, "LIKE_INFO_V3_CLICK")?; + Ok(LikeClickMessage { + cmd: value.get("cmd").and_then(value_string).unwrap_or_default(), + data: LikeClickData { + uid: data.get("uid").and_then(value_u64), + uname: data.get("uname").and_then(value_string), + like_text: data.get("like_text").and_then(value_string), + like_count: data.get("like_count").and_then(value_u64), + is_like: data.get("is_like").and_then(value_bool), + icon: data.get("icon").and_then(value_string), + fans_medal: data.get("fans_medal").and_then(parse_like_fans_medal), + contribution_info: data + .get("contribution_info") + .and_then(parse_like_contribution_info), + identities: data + .get("identities") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(), + dmscore: data.get("dmscore").and_then(value_u64), + extra: object_extra_with_invalid( + &Value::Object(data.clone()), + &[ + ("uid", data.get("uid").and_then(value_u64).is_some()), + ("uname", data.get("uname").and_then(value_string).is_some()), + ( + "like_text", + data.get("like_text").and_then(value_string).is_some(), + ), + ( + "like_count", + data.get("like_count").and_then(value_u64).is_some(), + ), + ( + "is_like", + data.get("is_like").and_then(value_bool).is_some(), + ), + ("icon", data.get("icon").and_then(value_string).is_some()), + ( + "fans_medal", + data.get("fans_medal") + .and_then(parse_like_fans_medal) + .is_some(), + ), + ( + "contribution_info", + data.get("contribution_info") + .and_then(parse_like_contribution_info) + .is_some(), + ), + ( + "identities", + data.get("identities").and_then(Value::as_array).is_some(), + ), + ("dmscore", data.get("dmscore").and_then(value_u64).is_some()), + ], + ), + }, + extra: object_extra(value, &["cmd", "data"]), + }) +} + +fn parse_like_fans_medal(value: &Value) -> Option { + let object = value.as_object()?; + Some(LikeFansMedalInfo { + level: object.get("medal_level").and_then(value_u8), + name: object.get("medal_name").and_then(value_string), + color: object.get("medal_color").and_then(value_u32), + color_start: object.get("medal_color_start").and_then(value_u32), + color_end: object.get("medal_color_end").and_then(value_u32), + color_border: object.get("medal_color_border").and_then(value_u32), + anchor_room_id: object.get("anchor_roomid").and_then(value_u64), + anchor_name: object.get("anchor_uname").and_then(value_string), + guard_level: object.get("guard_level").and_then(value_u8), + extra: object_extra_with_invalid( + value, + &[ + ( + "medal_level", + object.get("medal_level").and_then(value_u8).is_some(), + ), + ( + "medal_name", + object.get("medal_name").and_then(value_string).is_some(), + ), + ( + "medal_color", + object.get("medal_color").and_then(value_u32).is_some(), + ), + ( + "medal_color_start", + object + .get("medal_color_start") + .and_then(value_u32) + .is_some(), + ), + ( + "medal_color_end", + object.get("medal_color_end").and_then(value_u32).is_some(), + ), + ( + "medal_color_border", + object + .get("medal_color_border") + .and_then(value_u32) + .is_some(), + ), + ( + "anchor_roomid", + object.get("anchor_roomid").and_then(value_u64).is_some(), + ), + ( + "anchor_uname", + object.get("anchor_uname").and_then(value_string).is_some(), + ), + ( + "guard_level", + object.get("guard_level").and_then(value_u8).is_some(), + ), + ], + ), + }) +} + +fn parse_like_contribution_info(value: &Value) -> Option { + let object = value.as_object()?; + Some(LikeContributionInfo { + grade: object.get("grade").and_then(value_u64), + extra: object_extra_with_invalid( + value, + &[("grade", object.get("grade").and_then(value_u64).is_some())], + ), + }) +} + +fn parse_like_update(value: &Value) -> std::result::Result { + let data = command_data(value, "LIKE_INFO_V3_UPDATE")?; + Ok(LikeUpdateMessage { + cmd: value.get("cmd").and_then(value_string).unwrap_or_default(), + click_count: data.get("click_count").and_then(value_u64), + data_extra: object_extra_with_invalid( + &Value::Object(data.clone()), + &[( + "click_count", + data.get("click_count").and_then(value_u64).is_some(), + )], + ), + extra: object_extra(value, &["cmd", "data"]), + }) +} + +fn parse_like_notice(value: &Value) -> std::result::Result { + let data = command_data(value, "LIKE_INFO_V3_NOTICE")?; + let segments = data + .get("content_segments") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + Ok(LikeNoticeMessage { + cmd: value.get("cmd").and_then(value_string).unwrap_or_default(), + like_count: data.get("like_count").and_then(value_u64), + message_type: data.get("msg_type").and_then(value_u8), + content_segments: segments + .iter() + .filter_map(parse_like_notice_content_segment) + .collect(), + unknown_content_segments: segments + .iter() + .enumerate() + .filter(|(_, segment)| !segment.is_object()) + .map(|(index, segment)| (index, segment.clone())) + .collect(), + data_extra: object_extra_with_invalid( + &Value::Object(data.clone()), + &[ + ( + "like_count", + data.get("like_count").and_then(value_u64).is_some(), + ), + ( + "msg_type", + data.get("msg_type").and_then(value_u8).is_some(), + ), + ( + "content_segments", + data.get("content_segments") + .and_then(Value::as_array) + .is_some(), + ), + ], + ), + extra: object_extra(value, &["cmd", "data"]), + }) +} + +fn parse_like_notice_content_segment(value: &Value) -> Option { + let object = value.as_object()?; + Some(LikeNoticeContentSegment { + kind: object.get("type").and_then(value_u8), + text: object.get("text").and_then(value_string), + extra: object_extra_with_invalid( + value, + &[ + ("type", object.get("type").and_then(value_u8).is_some()), + ("text", object.get("text").and_then(value_string).is_some()), + ], + ), + }) +} + +fn parse_online_rank_count(value: &Value) -> std::result::Result { + let data = command_data(value, "ONLINE_RANK_COUNT")?; + Ok(OnlineRankCountMessage { + cmd: value.get("cmd").and_then(value_string).unwrap_or_default(), + count: data.get("count").and_then(value_u64), + count_text: data.get("count_text").and_then(value_string), + online_count: data.get("online_count").and_then(value_u64), + online_count_text: data.get("online_count_text").and_then(value_string), + extra: object_extra(value, &["cmd", "data"]), + }) +} + +fn parse_watched_change(value: &Value) -> std::result::Result { + let data = command_data(value, "WATCHED_CHANGE")?; + Ok(WatchedChangeMessage { + cmd: value.get("cmd").and_then(value_string).unwrap_or_default(), + watched_count: data.get("num").and_then(value_u64), + text_small: data.get("text_small").and_then(value_string), + text_large: data.get("text_large").and_then(value_string), + extra: object_extra(value, &["cmd", "data"]), + }) +} + +fn parse_stop_live_room_list( + value: &Value, +) -> std::result::Result { + let data = command_data(value, "STOP_LIVE_ROOM_LIST")?; + Ok(StopLiveRoomListMessage { + cmd: value.get("cmd").and_then(value_string).unwrap_or_default(), + room_ids: data + .get("room_id_list") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(value_u64) + .collect(), + extra: object_extra(value, &["cmd", "data"]), + }) +} + +fn parse_gift_star_process(value: &Value) -> std::result::Result { + let data = command_data(value, "WIDGET_GIFT_STAR_PROCESS_V2")?; + Ok(GiftStarProcessMessage { + cmd: value.get("cmd").and_then(value_string).unwrap_or_default(), + name: data.get("name").and_then(value_string), + current: data.get("cur_num").and_then(value_u64), + total: data.get("total_num").and_then(value_u64), + version: data.get("version").and_then(value_u64), + extra: object_extra(value, &["cmd", "data"]), + }) +} + +fn parse_protobuf_payload(value: &Value) -> std::result::Result { + let data = command_data(value, "protobuf 命令")?; + let pb_base64 = data + .get("pb") + .and_then(value_string) + .ok_or_else(|| "protobuf 命令缺少 data.pb".to_owned())?; + Ok(ProtobufPayloadMessage { + cmd: value.get("cmd").and_then(value_string).unwrap_or_default(), + pb_base64, + dm_score: data.get("dmscore").and_then(value_u64), + extra: object_extra(value, &["cmd", "data"]), + }) +} + +fn command_data<'a>( + value: &'a Value, + command: &str, +) -> std::result::Result<&'a serde_json::Map, String> { + value + .get("data") + .and_then(Value::as_object) + .ok_or_else(|| format!("{command} 缺少对象类型的 data 字段")) +} + +fn parse_danmu(value: &Value) -> std::result::Result { + let info = value + .get("info") + .and_then(Value::as_array) + .ok_or_else(|| "DANMU_MSG 缺少数组类型的 info 字段".to_owned())?; + let mut unknown_info = indexed_extra(info, &[0, 1, 2, 3, 4, 5, 7, 9, 15]); + + let metadata = parse_index(info, 0, &mut unknown_info, parse_metadata).unwrap_or_default(); + let text = parse_index(info, 1, &mut unknown_info, value_string); + let sender = parse_index(info, 2, &mut unknown_info, parse_sender).unwrap_or_default(); + let fans_medal = parse_fans_medal_index(info, &mut unknown_info); + let user_level = parse_index(info, 4, &mut unknown_info, parse_user_level); + let title = parse_index(info, 5, &mut unknown_info, parse_user_title); + let guard_level = parse_index(info, 7, &mut unknown_info, value_u8); + let timestamp = parse_index(info, 9, &mut unknown_info, parse_timestamp); + let extension = parse_index(info, 15, &mut unknown_info, parse_extension); + + Ok(DanmuMessage { + cmd: value_string(value.get("cmd").unwrap_or(&Value::Null)).unwrap_or_default(), + metadata, + text, + sender, + fans_medal, + user_level, + title, + guard_level, + timestamp, + extension, + unknown_info, + dm_v2: value.get("dm_v2").and_then(value_string), + extra: object_extra(value, &["cmd", "info", "dm_v2"]), + }) +} + +fn parse_index( + values: &[Value], + index: usize, + unknown: &mut HashMap, + parser: impl FnOnce(&Value) -> Option, +) -> Option { + let value = values.get(index)?; + match parser(value) { + Some(parsed) => Some(parsed), + None => { + unknown.insert(index, value.clone()); + None + } + } +} + +fn parse_fans_medal_index( + values: &[Value], + unknown: &mut HashMap, +) -> Option { + let value = values.get(3)?; + let Some(entries) = value.as_array() else { + unknown.insert(3, value.clone()); + return None; + }; + (!entries.is_empty()).then(|| FansMedal { + level: entries.first().and_then(value_u8), + name: entries.get(1).and_then(value_string), + anchor_name: entries.get(2).and_then(value_string), + anchor_room_id: entries.get(3).and_then(value_u64), + color: entries.get(4).and_then(value_u32), + guard_level: entries.get(10).and_then(value_u8), + extra: indexed_extra(entries, &[0, 1, 2, 3, 4, 10]), + }) +} + +fn parse_metadata(value: &Value) -> Option { + let entries = value.as_array()?; + Some(DanmuMetadata { + color: entries.get(3).and_then(value_u32), + sent_at_ms: entries.get(4).and_then(value_u64), + danmu_type: entries.get(9).and_then(value_u8), + gradient_color: entries.get(11).and_then(value_u32), + extra: indexed_extra(entries, &[3, 4, 9]), + }) +} + +fn parse_sender(value: &Value) -> Option { + let entries = value.as_array()?; + Some(DanmuSender { + uid: entries.first().and_then(value_u64), + uname: entries.get(1).and_then(value_string), + is_admin: entries.get(2).and_then(value_bool), + is_vip: entries.get(3).and_then(value_bool), + is_svip: entries.get(4).and_then(value_bool), + rank: entries.get(5).and_then(value_u32), + name_color: entries.get(7).and_then(value_string), + extra: indexed_extra(entries, &[0, 1, 2, 3, 4, 5, 7]), + }) +} + +fn parse_user_level(value: &Value) -> Option { + let entries = value.as_array()?; + Some(UserLevel { + level: entries.first().and_then(value_u8), + color: entries.get(2).and_then(value_u32), + rank_text: entries.get(3).and_then(value_string), + extra: indexed_extra(entries, &[0, 3]), + }) +} + +fn parse_user_title(value: &Value) -> Option { + let entries = value.as_array()?; + Some(UserTitle { + name: entries.first().and_then(value_string), + icon: entries.get(1).and_then(value_string), + extra: indexed_extra(entries, &[0, 1]), + }) +} + +fn parse_timestamp(value: &Value) -> Option { + value.as_object().map(|object| DanmuTimestamp { + ct: object.get("ct").and_then(value_string), + ts: object.get("ts").and_then(value_u64), + extra: object_extra(value, &["ct", "ts"]), + }) +} + +fn parse_extension(value: &Value) -> Option { + value.as_object().map(|object| DanmuExtension { + extra_json: object.get("extra").and_then(value_string), + extra: object_extra(value, &["extra"]), + }) +} + +fn indexed_extra(values: &[Value], known: &[usize]) -> HashMap { + values + .iter() + .enumerate() + .filter(|(index, _)| !known.contains(index)) + .map(|(index, value)| (index, value.clone())) + .collect() +} + +fn object_extra(value: &Value, known: &[&str]) -> HashMap { + value + .as_object() + .into_iter() + .flatten() + .filter(|(key, _)| !known.contains(&key.as_str())) + .map(|(key, value)| (key.clone(), value.clone())) + .collect() +} + +fn object_extra_with_invalid( + value: &Value, + parsed_fields: &[(&str, bool)], +) -> HashMap { + value + .as_object() + .into_iter() + .flatten() + .filter(|(key, _)| { + !parsed_fields + .iter() + .any(|(name, parsed)| key == name && *parsed) + }) + .map(|(key, value)| (key.clone(), value.clone())) + .collect() +} + +fn value_string(value: &Value) -> Option { + value.as_str().map(str::to_owned) +} + +fn value_lossless_string(value: &Value) -> Option { + value_string(value).or_else(|| value_u64(value).map(|number| number.to_string())) +} + +fn value_u64(value: &Value) -> Option { + value + .as_u64() + .or_else(|| value.as_str().and_then(|text| text.parse().ok())) +} + +fn value_u32(value: &Value) -> Option { + value_u64(value).and_then(|number| number.try_into().ok()) +} + +fn value_u8(value: &Value) -> Option { + value_u64(value).and_then(|number| number.try_into().ok()) +} + +fn value_bool(value: &Value) -> Option { + value.as_bool().or_else(|| match value_u64(value) { + Some(0) => Some(false), + Some(1) => Some(true), + _ => None, + }) +} + +/// 已认证的直播弹幕 WebSocket 连接。 +pub struct LiveWebSocket { + stream: WebSocketStream>, + pending: VecDeque, +} + +impl LiveWebSocket { + /// 建立直播弹幕连接并完成认证。 + /// + /// 会从导航接口读取当前登录用户 UID、请求弹幕 token、选择第一个 WSS 主机, + /// 并发送操作码为 7 的认证包。当前网页协议通常要求有效的登录 Cookie。 + pub async fn connect(client: &Client, room_id: u64) -> Result { + let nav = client.user().nav().await?; + let uid = nav + .get("mid") + .and_then(Value::as_u64) + .ok_or_else(|| Error::InvalidPacket("导航响应未包含当前用户 UID".into()))?; + Self::connect_with_uid(client, room_id, uid).await + } + + /// 使用已知用户 UID 建立直播弹幕连接并完成认证。 + /// + /// 一般应优先使用 [`LiveWebSocket::connect`],仅在调用方已通过可信方式取得 UID + /// 时使用此方法。 + pub async fn connect_with_uid(client: &Client, room_id: u64, uid: u64) -> Result { + let info = client.live().danmu_info(room_id).await?; + let token = info + .get("token") + .and_then(Value::as_str) + .ok_or_else(|| Error::InvalidPacket("danmu response has no token".into()))?; + let host = info + .pointer("/host_list/0/host") + .and_then(Value::as_str) + .ok_or_else(|| Error::InvalidPacket("danmu response has no host".into()))?; + let port = info + .pointer("/host_list/0/wss_port") + .and_then(Value::as_u64) + .unwrap_or(443); + if !host.ends_with(".chat.bilibili.com") { + return Err(Error::InvalidPacket(format!( + "refusing non-Bilibili chat host: {host}" + ))); + } + let (stream, _) = connect_async(format!("wss://{host}:{port}/sub")) + .await + .map_err(Error::websocket)?; + let mut socket = Self { + stream, + pending: VecDeque::new(), + }; + let auth = json!({"uid": uid, "roomid": room_id, "protover": 3, "platform": "web", "type": 2, "key": token}); + socket.send_packet(7, auth.to_string().as_bytes()).await?; + Ok(socket) + } + + /// 发送心跳包。 + /// + /// 调用方应约每 30 秒调用一次,以维持连接。 + pub async fn heartbeat(&mut self) -> Result<()> { + self.send_packet(2, &[]).await + } + + /// 等待并返回下一个直播事件。 + /// + /// 连接被服务器关闭时返回 `Ok(None)`。 + pub async fn next_event(&mut self) -> Result> { + if let Some(event) = self.pending.pop_front() { + return Ok(Some(event)); + } + while let Some(message) = self.stream.next().await { + match message.map_err(Error::websocket)? { + Message::Binary(bytes) => { + self.pending + .extend(events_from_packets(&decode_packets(&bytes)?)?); + if let Some(event) = self.pending.pop_front() { + return Ok(Some(event)); + } + } + Message::Close(_) => return Ok(None), + Message::Ping(payload) => self + .stream + .send(Message::Pong(payload)) + .await + .map_err(Error::websocket)?, + _ => {} + } + } + Ok(None) + } + + /// 等待下一个原始 WebSocket 二进制帧。 + /// + /// 返回的字节尚未经过协议包拆分、zlib/brotli 解压或 JSON 解析,适合抓取和离线 + /// 分析。此方法会自动响应 WebSocket Ping;不要与 [`LiveWebSocket::next_event`] + /// 交替调用,否则事件顺序难以推断。连接关闭时返回 `Ok(None)`。 + pub async fn next_raw_frame(&mut self) -> Result>> { + while let Some(message) = self.stream.next().await { + match message.map_err(Error::websocket)? { + Message::Binary(bytes) => return Ok(Some(bytes.to_vec())), + Message::Close(_) => return Ok(None), + Message::Ping(payload) => self + .stream + .send(Message::Pong(payload)) + .await + .map_err(Error::websocket)?, + _ => {} + } + } + Ok(None) + } + + async fn send_packet(&mut self, operation: u32, body: &[u8]) -> Result<()> { + self.stream + .send(Message::Binary(encode_packet(operation, body).into())) + .await + .map_err(Error::websocket)?; + Ok(()) + } +} + +/// 解码一个 WebSocket 二进制帧中的一个或多个协议包。 +/// +/// 压缩包的数据仍保留在 [`Packet::body`] 中;[`LiveWebSocket::next_event`] 会递归 +/// 解压 zlib 与 brotli 包并转换成事件。 +pub fn decode_packets(bytes: &[u8]) -> Result> { + let mut packets = Vec::new(); + let mut offset = 0; + while offset < bytes.len() { + if bytes.len() - offset < HEADER_LEN { + return Err(Error::InvalidPacket("truncated header".into())); + } + let packet_len = u32::from_be_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize; + let header_len = + u16::from_be_bytes(bytes[offset + 4..offset + 6].try_into().unwrap()) as usize; + if packet_len < HEADER_LEN + || header_len < HEADER_LEN + || header_len > packet_len + || offset + packet_len > bytes.len() + { + return Err(Error::InvalidPacket("invalid packet length".into())); + } + let version = u16::from_be_bytes(bytes[offset + 6..offset + 8].try_into().unwrap()); + let operation = u32::from_be_bytes(bytes[offset + 8..offset + 12].try_into().unwrap()); + packets.push(Packet { + version, + operation, + body: bytes[offset + header_len..offset + packet_len].to_vec(), + }); + offset += packet_len; + } + Ok(packets) +} + +/// 解码一个原始 WebSocket 二进制帧中的全部直播事件。 +/// +/// 本函数会拆分协议包,并递归解压 zlib 和 brotli 载荷,再将操作码为 5 的消息分发为 +/// [`LiveCommand`]。它适合离线分析 [`crate` 提供的抓取工具](crate::websocket) 输出的 +/// 原始帧。 +pub fn decode_events(bytes: &[u8]) -> Result> { + events_from_packets(&decode_packets(bytes)?) +} + +fn events_from_packets(packets: &[Packet]) -> Result> { + let mut events = Vec::new(); + for packet in packets { + match packet.version { + 2 => { + let mut decoder = ZlibDecoder::new(packet.body.as_slice()); + let mut nested = Vec::new(); + decoder.read_to_end(&mut nested)?; + events.extend(events_from_packets(&decode_packets(&nested)?)?); + } + 3 => { + let mut decoder = Decompressor::new(packet.body.as_slice(), 4096); + let mut nested = Vec::new(); + decoder.read_to_end(&mut nested)?; + events.extend(events_from_packets(&decode_packets(&nested)?)?); + } + _ if packet.operation == 3 && packet.body.len() >= 4 => events.push( + LiveEvent::Popularity(u32::from_be_bytes(packet.body[..4].try_into().unwrap())), + ), + _ if packet.operation == 5 || packet.operation == 8 => { + let value = serde_json::from_slice(&packet.body)?; + events.push(if packet.operation == 8 { + LiveEvent::Auth(value) + } else { + LiveEvent::Command(Box::new(parse_command(value))) + }); + } + _ => events.push(LiveEvent::Unknown(packet.clone())), + } + } + Ok(events) +} + +fn encode_packet(operation: u32, body: &[u8]) -> Vec { + let mut packet = Vec::with_capacity(HEADER_LEN + body.len()); + packet.extend_from_slice(&((HEADER_LEN + body.len()) as u32).to_be_bytes()); + packet.extend_from_slice(&(HEADER_LEN as u16).to_be_bytes()); + packet.extend_from_slice(&1u16.to_be_bytes()); + packet.extend_from_slice(&operation.to_be_bytes()); + packet.extend_from_slice(&1u32.to_be_bytes()); + packet.extend_from_slice(body); + packet +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn parses_packet_and_popularity() { + let packet = encode_packet(3, &42u32.to_be_bytes()); + let decoded = decode_packets(&packet).unwrap(); + assert_eq!( + events_from_packets(&decoded).unwrap(), + vec![LiveEvent::Popularity(42)] + ); + } + #[test] + fn rejects_truncated_packet() { + assert!(decode_packets(&[0; 15]).is_err()); + } + + #[test] + fn dispatches_known_command_and_keeps_extra_fields() { + let command = parse_command(json!({ + "cmd": "SEND_GIFT", + "danmu": { "area": 0 }, + "data": { + "uid": 1, + "uname": "测试用户", + "giftId": 123, + "giftName": "辣条", + "num": 2, + "price": 100, + "total_coin": 200, + "coin_type": "gold", + "new_data_field": { "enabled": true } + }, + "msg_id": "message-id", + "p_is_ack": false, + "new_server_field": { "enabled": true } + })); + let LiveCommand::Gift(gift) = command else { + panic!("应解析为礼物消息"); + }; + assert_eq!(gift.data.gift_name.as_deref(), Some("辣条")); + assert_eq!(gift.data.total_coin, Some(200)); + assert_eq!(gift.extra["new_server_field"]["enabled"], true); + } + + #[test] + fn parses_combo_send_and_keeps_nested_extra_fields() { + let command = parse_command(json!({ + "cmd": "COMBO_SEND", + "data": { + "uid": "42", + "uname": "测试用户", + "gift_id": 123, + "gift_name": "辣条", + "num": 2, + "price": 100, + "total_coin": 200, + "coin_type": "gold", + "action": "赠送了", + "combo_id": "combo-1", + "batch_combo_id": "batch-1", + "combo_num": 3, + "batch_combo_num": 4, + "combo_total_coin": 300, + "guard_level": 3, + "medal_info": { + "medal_level": 12, + "medal_name": "测试勋章", + "anchor_uname": "主播", + "medal_future": true + }, + "data_future": true + }, + "top_level_future": true + })); + let LiveCommand::ComboSend(combo) = command else { + panic!("应解析为连击送礼消息"); + }; + assert_eq!(combo.data.uid, Some(42)); + assert_eq!(combo.data.combo_total_coin, Some(300)); + assert_eq!( + combo.data.medal_info.as_ref().and_then(|medal| medal.level), + Some(12) + ); + assert_eq!( + combo.data.medal_info.as_ref().unwrap().extra["medal_future"], + true + ); + assert_eq!(combo.data.extra["data_future"], true); + assert_eq!(combo.extra["top_level_future"], true); + } + + #[test] + fn parses_like_click_and_keeps_nested_extra_fields() { + let command = parse_command(json!({ + "cmd": "LIKE_INFO_V3_CLICK", + "data": { + "uid": 42, + "uname": "测试用户", + "like_text": "为主播点赞了", + "like_count": "99", + "is_like": 1, + "icon": "https://example.test/like.png", + "fans_medal": { + "medal_level": 12, + "medal_name": "测试勋章", + "medal_color": 123, + "medal_future": true + }, + "contribution_info": { "grade": 7, "future": "保留" }, + "identities": ["guard", 3], + "dmscore": 60, + "data_future": true + }, + "top_level_future": true + })); + let LiveCommand::LikeClick(like) = command else { + panic!("应解析为点赞消息"); + }; + assert_eq!(like.data.like_count, Some(99)); + assert_eq!(like.data.is_like, Some(true)); + assert_eq!(like.data.identities, vec![json!("guard"), json!(3)]); + assert_eq!( + like.data.fans_medal.as_ref().unwrap().extra["medal_future"], + true + ); + assert_eq!( + like.data.contribution_info.as_ref().unwrap().extra["future"], + "保留" + ); + assert_eq!(like.data.extra["data_future"], true); + assert_eq!(like.extra["top_level_future"], true); + } + + #[test] + fn parses_like_update() { + let command = parse_command(json!({ + "cmd": "LIKE_INFO_V3_UPDATE", + "data": { "click_count": "12345", "data_future": true }, + "top_level_future": true + })); + let LiveCommand::LikeUpdate(update) = command else { + panic!("应解析为点赞计数变化消息"); + }; + assert_eq!(update.click_count, Some(12_345)); + assert_eq!(update.data_extra["data_future"], true); + assert_eq!(update.extra["top_level_future"], true); + } + + #[test] + fn parses_like_notice_and_keeps_segment_extra_fields() { + let command = parse_command(json!({ + "cmd": "LIKE_INFO_V3_NOTICE", + "data": { + "like_count": 12345, + "msg_type": 1, + "content_segments": [ + { "type": 1, "text": "已有 ", "segment_future": true }, + { "type": 2, "text": "12345" } + ], + "data_future": true + }, + "top_level_future": true + })); + let LiveCommand::LikeNotice(notice) = command else { + panic!("应解析为点赞提示消息"); + }; + assert_eq!(notice.like_count, Some(12_345)); + assert_eq!(notice.message_type, Some(1)); + assert_eq!(notice.content_segments[0].text.as_deref(), Some("已有 ")); + assert_eq!(notice.content_segments[0].extra["segment_future"], true); + assert_eq!(notice.data_extra["data_future"], true); + assert_eq!(notice.extra["top_level_future"], true); + } + + #[test] + fn preserves_unknown_and_invalid_commands() { + let unknown = parse_command(json!({"cmd": "FUTURE_COMMAND", "value": 1})); + assert!(matches!(unknown, LiveCommand::Unknown { .. })); + + let invalid = parse_command(json!({"cmd": "SEND_GIFT", "data": []})); + assert!(matches!(invalid, LiveCommand::Invalid { .. })); + } + + #[test] + fn dispatches_danmu_command_with_suffix() { + let command = parse_command(json!({ + "cmd": "DANMU_MSG:4:0", + "info": [ + [0, 0, 0, 16777215, 1_700_000_000_000_u64, 0, 0, 0, 0, 1, 0, [1, 2]], + "你好,世界", + [42, "测试用户", 1, 0, 0, 37, 1, "#FFFFFF"], + [12, "测试勋章", "主播", 5050, 123, 0, 0, 0, 0, 0, 3], + [38, 0, "#FFFFFF", ">50000"], + ["总督", "https://example.test/title.png"], + null, + 3, + null, + {"ct": "token", "ts": 1_700_000_000}, + null, + null, + null, + null, + null, + {"extra": "{\"foo\":true}", "new_field": 1} + ], + "dm_v2": "v2", + "top_level_future": true + })); + let LiveCommand::Danmu(danmu) = command else { + panic!("应解析为弹幕消息"); + }; + assert_eq!(danmu.text.as_deref(), Some("你好,世界")); + assert_eq!(danmu.sender.uid, Some(42)); + assert_eq!( + danmu.fans_medal.as_ref().and_then(|medal| medal.level), + Some(12) + ); + assert_eq!(danmu.metadata.color, Some(16_777_215)); + assert_eq!( + danmu.timestamp.as_ref().and_then(|time| time.ts), + Some(1_700_000_000) + ); + assert_eq!( + danmu + .extension + .as_ref() + .and_then(|extension| extension.extra_json.as_deref()), + Some("{\"foo\":true}") + ); + assert_eq!(danmu.extra["top_level_future"], true); + } +}