diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6e478cb..74532dc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,3 +52,6 @@ jobs: - run: rustup update ${{ matrix.toolchain }} && rustup default ${{ matrix.toolchain }} - run: cargo build --locked --verbose --all-targets - run: cargo test --locked --verbose + - run: cargo build --locked --verbose --no-default-features + - run: cargo test --locked --verbose --no-default-features --features protect + - run: cargo test --locked --verbose --all-features diff --git a/Cargo.lock b/Cargo.lock index 1336df0..fa1846a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + [[package]] name = "android_system_properties" version = "0.1.5" @@ -11,6 +20,16 @@ dependencies = [ "libc", ] +[[package]] +name = "assert-json-diff" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -35,6 +54,15 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +[[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 = "bumpalo" version = "3.19.1" @@ -122,6 +150,49 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[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 = "deadpool" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b" +dependencies = [ + "deadpool-runtime", + "lazy_static", + "num_cpus", + "tokio", +] + +[[package]] +name = "deadpool-runtime" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" + [[package]] name = "deranged" version = "0.5.5" @@ -131,6 +202,16 @@ dependencies = [ "powerfmt", ] +[[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.5" @@ -306,6 +387,16 @@ dependencies = [ "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" @@ -354,6 +445,12 @@ version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + [[package]] name = "http" version = "1.4.0" @@ -393,6 +490,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hyper" version = "1.8.1" @@ -407,6 +510,7 @@ dependencies = [ "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "pin-utils", @@ -641,6 +745,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + [[package]] name = "libc" version = "0.2.184" @@ -726,6 +836,16 @@ dependencies = [ "autocfg", ] +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + [[package]] name = "once_cell" version = "1.21.3" @@ -815,6 +935,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +[[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.105" @@ -855,6 +984,64 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[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", +] + +[[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 = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "reqwest" version = "0.12.28" @@ -917,12 +1104,16 @@ version = "1.0.0" dependencies = [ "chrono", "futures", + "native-tls", + "percent-encoding", "reqwest", "serde", "serde_json", "thiserror", "tokio", + "tokio-tungstenite", "url", + "wiremock", ] [[package]] @@ -1070,6 +1261,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "1.3.0" @@ -1282,6 +1484,20 @@ dependencies = [ "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", + "native-tls", + "tokio", + "tokio-native-tls", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.7.18" @@ -1365,6 +1581,30 @@ 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", + "native-tls", + "rand", + "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.22" @@ -1389,6 +1629,12 @@ dependencies = [ "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" @@ -1652,6 +1898,29 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "wiremock" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031" +dependencies = [ + "assert-json-diff", + "base64", + "deadpool", + "futures", + "http", + "http-body-util", + "hyper", + "hyper-util", + "log", + "once_cell", + "regex", + "serde", + "serde_json", + "tokio", + "url", +] + [[package]] name = "wit-bindgen" version = "0.51.0" @@ -1687,6 +1956,26 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zerocopy" +version = "0.8.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "zerofrom" version = "0.1.6" diff --git a/Cargo.toml b/Cargo.toml index 2fb93e2..b409641 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,11 @@ exclude = [ "sailr.json", ] +[features] +default = ["unifi"] +unifi = [] +protect = ["dep:tokio-tungstenite", "dep:native-tls"] + [dependencies] tokio = { version = "1", features = ["rt-multi-thread", "macros"] } reqwest = { version = "0.12", features = ["cookies", "json"] } @@ -25,7 +30,14 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" chrono = { version = "0.4", features = ["serde"] } url = "2.5" +percent-encoding = "2.3" futures = "0.3" +tokio-tungstenite = { version = "0.26", features = ["native-tls"], optional = true } +native-tls = { version = "0.2", optional = true } [dev-dependencies] tokio = { version = "1", features = ["test-util"] } +wiremock = "0.6" + +[package.metadata.docs.rs] +all-features = true diff --git a/README.md b/README.md index 2570d31..73307c3 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # rustifi -A Rust API library for UniFi Network controllers. +A Rust API library for UniFi Network controllers, with optional support for +the UniFi Protect Integration API. ## Quick Start @@ -53,6 +54,81 @@ let client = UnifiClient::with_api_key_insecure("https://192.168.1.1", "api-key" > which makes connections vulnerable to man-in-the-middle attacks. Only use these > methods for local controllers on trusted networks. +## Cargo Features + +- `unifi` *(default)* — the UniFi Network controller API (`UnifiClient`). +- `protect` — the official UniFi Protect Integration API (`ProtectClient`). + +```toml +# Network only (default) +rustifi = "2" + +# Network + Protect +rustifi = { version = "2", features = ["protect"] } + +# Protect only +rustifi = { version = "2", default-features = false, features = ["protect"] } +``` + +## UniFi Protect + +The `protect` feature wraps the official Protect Integration API (Protect >= 5.3), +served at `https://{console}/proxy/protect/integration/v1`. Generate an API key in +the Protect app under **Settings -> Control Plane -> Integrations**. + +```rust +use rustifi::protect::ProtectClient; + +#[tokio::main] +async fn main() -> rustifi::Result<()> { + // Local consoles usually have self-signed certificates, so the + // `_insecure` constructor is common here (trusted networks only). + let client = ProtectClient::new_insecure("https://192.168.1.1", "your-api-key")?; + + // List cameras and save a snapshot + for camera in client.cameras().await? { + println!("Camera: {} ({:?})", camera.name, camera.state); + } + let jpeg = client.snapshot("camera-id", true).await?; + std::fs::write("snapshot.jpg", jpeg)?; + + Ok(()) +} +``` + +### Live events + +Motion, smart-detection, doorbell, and connectivity events are delivered over a +WebSocket (the Integration API has no REST event-history endpoint). The stream +ends on disconnect and there is no replay cursor, so reconnect in a loop: + +```rust +use futures::StreamExt; + +loop { + let mut stream = match client.subscribe_events().await { + Ok(stream) => stream, + Err(e) => { + eprintln!("subscription failed: {e}"); + tokio::time::sleep(std::time::Duration::from_secs(5)).await; + continue; + } + }; + while let Some(msg) = stream.next().await { + match msg { + Ok(event) => println!("{:?} {:?}", event.action, event.item.event_type), + Err(e) => eprintln!("stream error: {e}"), + } + } + // Events that occur while disconnected are lost. + tokio::time::sleep(std::time::Duration::from_secs(5)).await; +} +``` + +`subscribe_device_updates()` provides the same envelope for partial device-state +patches. Not yet covered: PTZ, talkback, liveviews, file uploads, chime play, +and alarm-manager webhooks. + ## WORK IN PROGRESS diff --git a/examples/protect-events/Cargo.lock b/examples/protect-events/Cargo.lock new file mode 100644 index 0000000..4160986 --- /dev/null +++ b/examples/protect-events/Cargo.lock @@ -0,0 +1,2005 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "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 = "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.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9" +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 = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cookie" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "log", + "publicsuffix", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[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 = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[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 2.0.119", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[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" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7" + +[[package]] +name = "futures-executor" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a" + +[[package]] +name = "futures-macro" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "futures-sink" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e34418ac499d6305c2fb5ad0ed2f6ac998c5f8ca209b4510f7f94242c647e307" + +[[package]] +name = "futures-task" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109" + +[[package]] +name = "futures-util" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "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", + "libc", + "wasi", +] + +[[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", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "h2" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[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.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "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", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[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", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.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 = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[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.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "litrs" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[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 = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[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 = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[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.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "protect-events" +version = "1.0.0" +dependencies = [ + "futures", + "rustifi", + "tokio", +] + +[[package]] +name = "psl-types" +version = "2.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" + +[[package]] +name = "publicsuffix" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f42ea446cab60335f76979ec15e12619a2165b5ae2c12166bef27d283a9fadf" +dependencies = [ + "idna", + "psl-types", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[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", +] + +[[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 = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "cookie", + "cookie_store", + "encoding_rs", + "futures-core", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "mime", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[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 = "rustifi" +version = "1.0.0" +dependencies = [ + "chrono", + "futures", + "native-tls", + "percent-encoding", + "reqwest", + "serde", + "serde_json", + "thiserror", + "tokio", + "tokio-tungstenite", + "url", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "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 = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +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", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "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 = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +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 2.0.119", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "time" +version = "0.3.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e1d5e639ff6bab73cb6885cc7e7b1de96c3f32c68ec55f3952614bec1092244" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "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 2.0.119", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[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", + "native-tls", + "tokio", + "tokio-native-tls", + "tungstenite", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[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", + "native-tls", + "rand", + "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 = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[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 2.0.119", + "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 = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[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 2.0.119", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "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 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/examples/protect-events/Cargo.toml b/examples/protect-events/Cargo.toml new file mode 100644 index 0000000..ef41395 --- /dev/null +++ b/examples/protect-events/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "protect-events" +version = "1.0.0" +edition = "2021" +description = "Example that lists Protect cameras, saves a snapshot, and tails live events" + +[dependencies] +rustifi = { path = "../..", default-features = false, features = ["protect"] } +tokio = { version = "1", features = ["full"] } +futures = "0.3" diff --git a/examples/protect-events/src/main.rs b/examples/protect-events/src/main.rs new file mode 100644 index 0000000..23b689e --- /dev/null +++ b/examples/protect-events/src/main.rs @@ -0,0 +1,51 @@ +use futures::StreamExt; +use rustifi::protect::ProtectClient; + +#[tokio::main] +async fn main() -> rustifi::Result<()> { + let base_url = std::env::var("PROTECT_URL").expect("PROTECT_URL not set"); + let api_key = std::env::var("PROTECT_API_KEY").expect("PROTECT_API_KEY not set"); + + // Local consoles usually have self-signed certificates; only use the + // insecure constructor on trusted networks. + let client = ProtectClient::new_insecure(base_url, api_key)?; + + let info = client.meta_info().await?; + println!("Protect version: {}", info.application_version); + + let cameras = client.cameras().await?; + for camera in &cameras { + println!("Camera: {} [{}] ({:?})", camera.name, camera.id, camera.state); + } + + if let Some(camera) = cameras.first() { + let jpeg = client.snapshot(&camera.id, false).await?; + let path = format!("{}.jpg", camera.id); + std::fs::write(&path, jpeg).expect("failed to write snapshot"); + println!("Saved snapshot of {} to {}", camera.name, path); + } + + println!("Tailing live events (Ctrl-C to quit)..."); + loop { + let mut stream = match client.subscribe_events().await { + Ok(stream) => stream, + Err(e) => { + eprintln!("subscription failed: {e}; retrying in 5s"); + tokio::time::sleep(std::time::Duration::from_secs(5)).await; + continue; + } + }; + while let Some(msg) = stream.next().await { + match msg { + Ok(event) => println!( + "[{:?}] {:?} on {} (smart: {:?})", + event.action, event.item.event_type, event.item.device, + event.item.smart_detect_types + ), + Err(e) => eprintln!("stream error: {e}"), + } + } + eprintln!("disconnected; reconnecting in 5s (events in between are lost)"); + tokio::time::sleep(std::time::Duration::from_secs(5)).await; + } +} diff --git a/src/api/mod.rs b/src/api/mod.rs index 9b3d01e..05e9ce3 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -1,14 +1,25 @@ +#[cfg(feature = "unifi")] pub mod acl; +#[cfg(feature = "unifi")] pub mod clients; +#[cfg(feature = "unifi")] pub mod devices; +#[cfg(feature = "unifi")] pub mod dns; pub mod endpoint; +#[cfg(feature = "unifi")] pub mod firewall; +#[cfg(feature = "unifi")] pub mod hotspot; +#[cfg(feature = "unifi")] pub mod networks; +#[cfg(feature = "unifi")] pub mod resources; +#[cfg(feature = "unifi")] pub mod sites; +#[cfg(feature = "unifi")] pub mod traffic; +#[cfg(feature = "unifi")] pub mod wifi; pub use endpoint::Endpoint; diff --git a/src/client.rs b/src/client.rs index a80f497..55d1251 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1,7 +1,7 @@ -use crate::api::endpoint::{Endpoint, HttpMethod}; +use crate::api::endpoint::Endpoint; use crate::error::Result; -use reqwest::{cookie::Jar, Client}; -use std::sync::Arc; +use crate::transport; +use reqwest::Client; /// The base URL for the UniFi remote cloud API. pub const REMOTE_API_URL: &str = "https://api.ui.com"; @@ -107,23 +107,7 @@ impl UnifiClient { base_path: impl Into, accept_invalid_certs: bool, ) -> Result { - let jar = Jar::default(); - let cookie_store = Arc::new(jar); - - let mut builder = Client::builder() - .user_agent("rustifi/1.0") - .cookie_store(true) - .cookie_provider(cookie_store) - .connect_timeout(std::time::Duration::from_secs(30)) - .timeout(std::time::Duration::from_secs(60)); - - if accept_invalid_certs { - builder = builder - .danger_accept_invalid_certs(true) - .danger_accept_invalid_hostnames(true); - } - - let http = builder.build()?; + let http = transport::build_http_client(accept_invalid_certs, true)?; Ok(Self { http, @@ -252,21 +236,12 @@ impl UnifiClient { /// # Ok::<(), rustifi::Error>(()) /// ``` pub fn remote(api_key: impl Into, host_id: impl Into) -> Result { - let jar = Jar::default(); - let cookie_store = Arc::new(jar); - // Validate the API key can be parsed as a header value let key = api_key.into(); let _: reqwest::header::HeaderValue = key.parse()?; // For remote API, we don't need to accept invalid certs - let http = Client::builder() - .user_agent("rustifi/1.0") - .cookie_store(true) - .cookie_provider(cookie_store) - .connect_timeout(std::time::Duration::from_secs(30)) - .timeout(std::time::Duration::from_secs(60)) - .build()?; + let http = transport::build_http_client(false, true)?; Ok(Self { http, @@ -308,51 +283,20 @@ impl UnifiClient { E: Endpoint, E::Response: for<'a> serde::Deserialize<'a>, { - let path = endpoint.build_path(); - - // Build URL based on whether this is a remote or local client - let url = if let Some(host_id) = &self.host_id { + // Build URL prefix based on whether this is a remote or local client + let url_prefix = if let Some(host_id) = &self.host_id { // Remote API: https://api.ui.com/v1/connector/consoles/{host_id}/{path} format!( - "{}/{}/connector/consoles/{}/{}", - self.base_url, self.base_path, host_id, path + "{}/{}/connector/consoles/{}", + self.base_url, self.base_path, host_id ) } else { // Local API: {base_url}/{base_path}/{path} - format!("{}/{}/{}", self.base_url, self.base_path, path) + format!("{}/{}", self.base_url, self.base_path) }; - let mut headers = reqwest::header::HeaderMap::new(); - - if let Some(api_key) = &self.api_key { - headers.insert("X-API-Key", api_key.parse()?); - } - - let mut request = self.http.request(E::METHOD.into(), &url).headers(headers); - - // Append query parameters using reqwest's query() for proper URL encoding - let params = endpoint.query_params(); - if !params.is_empty() { - request = request.query(¶ms); - } - - // Add JSON body for POST/PUT/PATCH methods - if let Some(body) = endpoint.request_body()? { - request = request.json(&body); - } - - let response = request.send().await?; - - if !response.status().is_success() { - return Err(crate::error::Error::Request( - response.error_for_status().unwrap_err(), - )); - } - - let body = response.text().await?; - let response_data = serde_json::from_str::(&body) - .map_err(|e| crate::error::Error::Parse(format!("{}\nResponse body: {}", e, body)))?; - Ok(response_data) + transport::execute_endpoint(&self.http, &url_prefix, self.api_key.as_deref(), endpoint) + .await } /// Execute a request for endpoints without dynamic path parameters. @@ -373,15 +317,3 @@ impl UnifiClient { &self.base_path } } - -impl From for reqwest::Method { - fn from(method: HttpMethod) -> Self { - match method { - HttpMethod::Get => reqwest::Method::GET, - HttpMethod::Post => reqwest::Method::POST, - HttpMethod::Put => reqwest::Method::PUT, - HttpMethod::Patch => reqwest::Method::PATCH, - HttpMethod::Delete => reqwest::Method::DELETE, - } - } -} diff --git a/src/error.rs b/src/error.rs index 2d8a22c..69abae3 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,6 +1,7 @@ use thiserror::Error; #[derive(Debug, Error)] +#[non_exhaustive] pub enum Error { #[error("Authentication failed: {0}")] Auth(String), @@ -8,6 +9,9 @@ pub enum Error { #[error("API request failed: {0}")] Request(#[from] reqwest::Error), + #[error("API request failed with status {status}: {body}")] + Api { status: u16, body: String }, + #[error("Response parsing failed: {0}")] Parse(String), @@ -28,6 +32,9 @@ pub enum Error { #[error("URL parsing failed: {0}")] UrlParse(#[from] url::ParseError), + + #[error("WebSocket error: {0}")] + WebSocket(String), } pub type Result = std::result::Result; diff --git a/src/lib.rs b/src/lib.rs index 0138bb8..0f94ae7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,27 +1,49 @@ pub mod api; +#[cfg(feature = "unifi")] pub mod client; pub mod error; pub mod models; +#[cfg(feature = "unifi")] pub mod pagination; +#[cfg(feature = "protect")] +pub mod protect; +#[cfg(feature = "unifi")] pub mod response; +#[cfg(feature = "unifi")] pub mod stats; +#[cfg(any(feature = "unifi", feature = "protect"))] +pub(crate) mod transport; +#[cfg(feature = "unifi")] pub mod wrappers; +#[cfg(feature = "unifi")] pub use client::{UnifiClient, REMOTE_API_URL}; pub use error::{Error, Result}; +#[cfg(feature = "unifi")] pub use pagination::DEFAULT_PAGE_SIZE; +#[cfg(feature = "protect")] +pub use protect::ProtectClient; +#[cfg(feature = "unifi")] pub use stats::{aggregate_clients_by_device, get_device_client_stats, DeviceClientStats}; +#[cfg(feature = "unifi")] pub use wrappers::DeviceWithInfo; pub mod prelude { + #[cfg(feature = "unifi")] pub use crate::api::networks::{Network, NetworkRequest}; pub use crate::api::Endpoint; + #[cfg(feature = "unifi")] pub use crate::client::UnifiClient; pub use crate::error::{Error, Result}; + #[cfg(feature = "unifi")] pub use crate::models::{ APModel, Client, Device, DeviceType, FirewallAction, FirewallPolicy, FirewallZone, Site, Voucher, WifiBroadcast, WifiSecurity, }; + #[cfg(feature = "protect")] + pub use crate::protect::prelude::*; + #[cfg(feature = "unifi")] pub use crate::stats::DeviceClientStats; + #[cfg(feature = "unifi")] pub use crate::wrappers::DeviceWithInfo; } diff --git a/src/models/mod.rs b/src/models/mod.rs index 5e562ef..8cd3bb2 100644 --- a/src/models/mod.rs +++ b/src/models/mod.rs @@ -1,28 +1,48 @@ +#[cfg(feature = "unifi")] pub mod access_point; +#[cfg(feature = "unifi")] pub mod client; pub mod common; +#[cfg(feature = "unifi")] pub mod device; +#[cfg(feature = "unifi")] pub mod device_details; +#[cfg(feature = "unifi")] pub mod device_statistics; +#[cfg(feature = "unifi")] pub mod firewall; +#[cfg(feature = "unifi")] pub mod site; +#[cfg(feature = "unifi")] pub mod site_device; +#[cfg(feature = "unifi")] pub mod voucher; +#[cfg(feature = "unifi")] pub mod wifi; +#[cfg(feature = "unifi")] pub use access_point::APModel; +#[cfg(feature = "unifi")] pub use client::{AccessType, Client, ClientAccess, ClientType}; pub use common::{IpAddress, MacAddress, Timestamp}; +#[cfg(feature = "unifi")] pub use device::{Device, DeviceType}; +#[cfg(feature = "unifi")] pub use device_details::{ AccessPointFeature, DeviceDetails, DeviceFeatures, DeviceUplink, InterfaceState, PhysicalInterfaces, PoE, Port, PortConnector, Radio, SwitchingFeature, WirelessStandard, }; +#[cfg(feature = "unifi")] pub use device_statistics::{ DeviceStatistics, RadioStatistics, StatisticsInterfaces, StatisticsUplink, }; +#[cfg(feature = "unifi")] pub use firewall::{FirewallAction, FirewallPolicy, FirewallZone}; +#[cfg(feature = "unifi")] pub use site::Site; +#[cfg(feature = "unifi")] pub use site_device::{DeviceFeature, DeviceInterface, DeviceState, SiteDevice}; +#[cfg(feature = "unifi")] pub use voucher::Voucher; +#[cfg(feature = "unifi")] pub use wifi::{WifiBroadcast, WifiSecurity}; diff --git a/src/protect/api/cameras.rs b/src/protect/api/cameras.rs new file mode 100644 index 0000000..ed9b301 --- /dev/null +++ b/src/protect/api/cameras.rs @@ -0,0 +1,161 @@ +use crate::api::endpoint::{Endpoint, HttpMethod}; +use crate::protect::models::{Camera, CameraPatch, RtspsQuality, RtspsStreams}; +use serde_json::Value; + +/// Fetch all cameras. +/// Endpoint: GET /proxy/protect/integration/v1/cameras +#[derive(Debug, Clone, Default)] +pub struct GetCameras; + +impl Endpoint for GetCameras { + const PATH: &'static str = "cameras"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = Vec; +} + +/// Fetch a single camera by ID. +/// Endpoint: GET /proxy/protect/integration/v1/cameras/{id} +#[derive(Debug, Clone)] +pub struct GetCamera { + pub camera_id: String, +} + +impl GetCamera { + pub fn new(camera_id: impl Into) -> Self { + Self { + camera_id: camera_id.into(), + } + } +} + +impl Endpoint for GetCamera { + const PATH: &'static str = "cameras/{id}"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = Camera; + + fn build_path(&self) -> String { + format!("cameras/{}", super::encode_id(&self.camera_id)) + } +} + +/// Partially update a camera's settings. +/// Endpoint: PATCH /proxy/protect/integration/v1/cameras/{id} +#[derive(Debug, Clone)] +pub struct PatchCamera { + pub camera_id: String, + pub patch: CameraPatch, +} + +impl PatchCamera { + pub fn new(camera_id: impl Into, patch: CameraPatch) -> Self { + Self { + camera_id: camera_id.into(), + patch, + } + } +} + +impl Endpoint for PatchCamera { + const PATH: &'static str = "cameras/{id}"; + const METHOD: HttpMethod = HttpMethod::Patch; + type Response = Camera; + + fn build_path(&self) -> String { + format!("cameras/{}", super::encode_id(&self.camera_id)) + } + + fn request_body(&self) -> Result, serde_json::Error> { + Ok(Some(serde_json::to_value(&self.patch)?)) + } +} + +/// Fetch the currently provisioned RTSPS stream URLs for a camera. +/// Endpoint: GET /proxy/protect/integration/v1/cameras/{id}/rtsps-stream +#[derive(Debug, Clone)] +pub struct GetRtspsStreams { + pub camera_id: String, +} + +impl GetRtspsStreams { + pub fn new(camera_id: impl Into) -> Self { + Self { + camera_id: camera_id.into(), + } + } +} + +impl Endpoint for GetRtspsStreams { + const PATH: &'static str = "cameras/{id}/rtsps-stream"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = RtspsStreams; + + fn build_path(&self) -> String { + format!("cameras/{}/rtsps-stream", super::encode_id(&self.camera_id)) + } +} + +/// Provision RTSPS streams for the given qualities. +/// Endpoint: POST /proxy/protect/integration/v1/cameras/{id}/rtsps-stream +#[derive(Debug, Clone)] +pub struct CreateRtspsStream { + pub camera_id: String, + pub qualities: Vec, +} + +impl CreateRtspsStream { + pub fn new(camera_id: impl Into, qualities: Vec) -> Self { + Self { + camera_id: camera_id.into(), + qualities, + } + } +} + +impl Endpoint for CreateRtspsStream { + const PATH: &'static str = "cameras/{id}/rtsps-stream"; + const METHOD: HttpMethod = HttpMethod::Post; + type Response = RtspsStreams; + + fn build_path(&self) -> String { + format!("cameras/{}/rtsps-stream", super::encode_id(&self.camera_id)) + } + + fn request_body(&self) -> Result, serde_json::Error> { + Ok(Some(serde_json::json!({ "qualities": self.qualities }))) + } +} + +/// Remove provisioned RTSPS streams for the given qualities. +/// Endpoint: DELETE /proxy/protect/integration/v1/cameras/{id}/rtsps-stream?qualities=... +#[derive(Debug, Clone)] +pub struct DeleteRtspsStream { + pub camera_id: String, + pub qualities: Vec, +} + +impl DeleteRtspsStream { + pub fn new(camera_id: impl Into, qualities: Vec) -> Self { + Self { + camera_id: camera_id.into(), + qualities, + } + } +} + +impl Endpoint for DeleteRtspsStream { + const PATH: &'static str = "cameras/{id}/rtsps-stream"; + const METHOD: HttpMethod = HttpMethod::Delete; + // The console returns an empty body on success. + type Response = Option; + + fn build_path(&self) -> String { + format!("cameras/{}/rtsps-stream", super::encode_id(&self.camera_id)) + } + + fn query_params(&self) -> Vec<(&'static str, String)> { + self.qualities + .iter() + .map(|q| ("qualities", q.as_str().to_string())) + .collect() + } +} diff --git a/src/protect/api/chimes.rs b/src/protect/api/chimes.rs new file mode 100644 index 0000000..23b7641 --- /dev/null +++ b/src/protect/api/chimes.rs @@ -0,0 +1,70 @@ +use crate::api::endpoint::{Endpoint, HttpMethod}; +use crate::protect::models::{Chime, ChimePatch}; +use serde_json::Value; + +/// Fetch all chimes. +/// Endpoint: GET /proxy/protect/integration/v1/chimes +#[derive(Debug, Clone, Default)] +pub struct GetChimes; + +impl Endpoint for GetChimes { + const PATH: &'static str = "chimes"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = Vec; +} + +/// Fetch a single chime by ID. +/// Endpoint: GET /proxy/protect/integration/v1/chimes/{id} +#[derive(Debug, Clone)] +pub struct GetChime { + pub chime_id: String, +} + +impl GetChime { + pub fn new(chime_id: impl Into) -> Self { + Self { + chime_id: chime_id.into(), + } + } +} + +impl Endpoint for GetChime { + const PATH: &'static str = "chimes/{id}"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = Chime; + + fn build_path(&self) -> String { + format!("chimes/{}", super::encode_id(&self.chime_id)) + } +} + +/// Partially update a chime's settings. +/// Endpoint: PATCH /proxy/protect/integration/v1/chimes/{id} +#[derive(Debug, Clone)] +pub struct PatchChime { + pub chime_id: String, + pub patch: ChimePatch, +} + +impl PatchChime { + pub fn new(chime_id: impl Into, patch: ChimePatch) -> Self { + Self { + chime_id: chime_id.into(), + patch, + } + } +} + +impl Endpoint for PatchChime { + const PATH: &'static str = "chimes/{id}"; + const METHOD: HttpMethod = HttpMethod::Patch; + type Response = Chime; + + fn build_path(&self) -> String { + format!("chimes/{}", super::encode_id(&self.chime_id)) + } + + fn request_body(&self) -> Result, serde_json::Error> { + Ok(Some(serde_json::to_value(&self.patch)?)) + } +} diff --git a/src/protect/api/lights.rs b/src/protect/api/lights.rs new file mode 100644 index 0000000..de24c08 --- /dev/null +++ b/src/protect/api/lights.rs @@ -0,0 +1,70 @@ +use crate::api::endpoint::{Endpoint, HttpMethod}; +use crate::protect::models::{Light, LightPatch}; +use serde_json::Value; + +/// Fetch all lights. +/// Endpoint: GET /proxy/protect/integration/v1/lights +#[derive(Debug, Clone, Default)] +pub struct GetLights; + +impl Endpoint for GetLights { + const PATH: &'static str = "lights"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = Vec; +} + +/// Fetch a single light by ID. +/// Endpoint: GET /proxy/protect/integration/v1/lights/{id} +#[derive(Debug, Clone)] +pub struct GetLight { + pub light_id: String, +} + +impl GetLight { + pub fn new(light_id: impl Into) -> Self { + Self { + light_id: light_id.into(), + } + } +} + +impl Endpoint for GetLight { + const PATH: &'static str = "lights/{id}"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = Light; + + fn build_path(&self) -> String { + format!("lights/{}", super::encode_id(&self.light_id)) + } +} + +/// Partially update a light's settings. +/// Endpoint: PATCH /proxy/protect/integration/v1/lights/{id} +#[derive(Debug, Clone)] +pub struct PatchLight { + pub light_id: String, + pub patch: LightPatch, +} + +impl PatchLight { + pub fn new(light_id: impl Into, patch: LightPatch) -> Self { + Self { + light_id: light_id.into(), + patch, + } + } +} + +impl Endpoint for PatchLight { + const PATH: &'static str = "lights/{id}"; + const METHOD: HttpMethod = HttpMethod::Patch; + type Response = Light; + + fn build_path(&self) -> String { + format!("lights/{}", super::encode_id(&self.light_id)) + } + + fn request_body(&self) -> Result, serde_json::Error> { + Ok(Some(serde_json::to_value(&self.patch)?)) + } +} diff --git a/src/protect/api/meta.rs b/src/protect/api/meta.rs new file mode 100644 index 0000000..6f88d25 --- /dev/null +++ b/src/protect/api/meta.rs @@ -0,0 +1,13 @@ +use crate::api::endpoint::{Endpoint, HttpMethod}; +use crate::protect::models::MetaInfo; + +/// Fetch Protect application version info. +/// Endpoint: GET /proxy/protect/integration/v1/meta/info +#[derive(Debug, Clone, Default)] +pub struct GetMetaInfo; + +impl Endpoint for GetMetaInfo { + const PATH: &'static str = "meta/info"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = MetaInfo; +} diff --git a/src/protect/api/mod.rs b/src/protect/api/mod.rs new file mode 100644 index 0000000..8a91321 --- /dev/null +++ b/src/protect/api/mod.rs @@ -0,0 +1,22 @@ +pub mod cameras; +pub mod chimes; +pub mod lights; +pub mod meta; +pub mod nvr; +pub mod sensors; +pub mod viewers; + +use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC}; + +// Encode everything except RFC 3986 unreserved characters, so an ID cannot +// smuggle path separators or query/fragment delimiters into the request URL. +const PATH_SEGMENT: &AsciiSet = &NON_ALPHANUMERIC + .remove(b'-') + .remove(b'_') + .remove(b'.') + .remove(b'~'); + +/// Percent-encode a resource ID for use as a single URL path segment. +pub(crate) fn encode_id(id: &str) -> String { + utf8_percent_encode(id, PATH_SEGMENT).to_string() +} diff --git a/src/protect/api/nvr.rs b/src/protect/api/nvr.rs new file mode 100644 index 0000000..57f2d1e --- /dev/null +++ b/src/protect/api/nvr.rs @@ -0,0 +1,15 @@ +use crate::api::endpoint::{Endpoint, HttpMethod}; +use crate::protect::models::Nvr; + +/// Fetch NVR / console information. +/// Endpoint: GET /proxy/protect/integration/v1/nvrs +/// +/// The console returns a single NVR object (not an array). +#[derive(Debug, Clone, Default)] +pub struct GetNvr; + +impl Endpoint for GetNvr { + const PATH: &'static str = "nvrs"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = Nvr; +} diff --git a/src/protect/api/sensors.rs b/src/protect/api/sensors.rs new file mode 100644 index 0000000..307d758 --- /dev/null +++ b/src/protect/api/sensors.rs @@ -0,0 +1,70 @@ +use crate::api::endpoint::{Endpoint, HttpMethod}; +use crate::protect::models::{Sensor, SensorPatch}; +use serde_json::Value; + +/// Fetch all sensors. +/// Endpoint: GET /proxy/protect/integration/v1/sensors +#[derive(Debug, Clone, Default)] +pub struct GetSensors; + +impl Endpoint for GetSensors { + const PATH: &'static str = "sensors"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = Vec; +} + +/// Fetch a single sensor by ID. +/// Endpoint: GET /proxy/protect/integration/v1/sensors/{id} +#[derive(Debug, Clone)] +pub struct GetSensor { + pub sensor_id: String, +} + +impl GetSensor { + pub fn new(sensor_id: impl Into) -> Self { + Self { + sensor_id: sensor_id.into(), + } + } +} + +impl Endpoint for GetSensor { + const PATH: &'static str = "sensors/{id}"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = Sensor; + + fn build_path(&self) -> String { + format!("sensors/{}", super::encode_id(&self.sensor_id)) + } +} + +/// Partially update a sensor's settings. +/// Endpoint: PATCH /proxy/protect/integration/v1/sensors/{id} +#[derive(Debug, Clone)] +pub struct PatchSensor { + pub sensor_id: String, + pub patch: SensorPatch, +} + +impl PatchSensor { + pub fn new(sensor_id: impl Into, patch: SensorPatch) -> Self { + Self { + sensor_id: sensor_id.into(), + patch, + } + } +} + +impl Endpoint for PatchSensor { + const PATH: &'static str = "sensors/{id}"; + const METHOD: HttpMethod = HttpMethod::Patch; + type Response = Sensor; + + fn build_path(&self) -> String { + format!("sensors/{}", super::encode_id(&self.sensor_id)) + } + + fn request_body(&self) -> Result, serde_json::Error> { + Ok(Some(serde_json::to_value(&self.patch)?)) + } +} diff --git a/src/protect/api/viewers.rs b/src/protect/api/viewers.rs new file mode 100644 index 0000000..e6dfbc9 --- /dev/null +++ b/src/protect/api/viewers.rs @@ -0,0 +1,70 @@ +use crate::api::endpoint::{Endpoint, HttpMethod}; +use crate::protect::models::{Viewer, ViewerPatch}; +use serde_json::Value; + +/// Fetch all viewers. +/// Endpoint: GET /proxy/protect/integration/v1/viewers +#[derive(Debug, Clone, Default)] +pub struct GetViewers; + +impl Endpoint for GetViewers { + const PATH: &'static str = "viewers"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = Vec; +} + +/// Fetch a single viewer by ID. +/// Endpoint: GET /proxy/protect/integration/v1/viewers/{id} +#[derive(Debug, Clone)] +pub struct GetViewer { + pub viewer_id: String, +} + +impl GetViewer { + pub fn new(viewer_id: impl Into) -> Self { + Self { + viewer_id: viewer_id.into(), + } + } +} + +impl Endpoint for GetViewer { + const PATH: &'static str = "viewers/{id}"; + const METHOD: HttpMethod = HttpMethod::Get; + type Response = Viewer; + + fn build_path(&self) -> String { + format!("viewers/{}", super::encode_id(&self.viewer_id)) + } +} + +/// Partially update a viewer's settings. +/// Endpoint: PATCH /proxy/protect/integration/v1/viewers/{id} +#[derive(Debug, Clone)] +pub struct PatchViewer { + pub viewer_id: String, + pub patch: ViewerPatch, +} + +impl PatchViewer { + pub fn new(viewer_id: impl Into, patch: ViewerPatch) -> Self { + Self { + viewer_id: viewer_id.into(), + patch, + } + } +} + +impl Endpoint for PatchViewer { + const PATH: &'static str = "viewers/{id}"; + const METHOD: HttpMethod = HttpMethod::Patch; + type Response = Viewer; + + fn build_path(&self) -> String { + format!("viewers/{}", super::encode_id(&self.viewer_id)) + } + + fn request_body(&self) -> Result, serde_json::Error> { + Ok(Some(serde_json::to_value(&self.patch)?)) + } +} diff --git a/src/protect/client.rs b/src/protect/client.rs new file mode 100644 index 0000000..6e0f01a --- /dev/null +++ b/src/protect/client.rs @@ -0,0 +1,266 @@ +use crate::api::endpoint::Endpoint; +use crate::error::{Error, Result}; +use crate::protect::api::{ + cameras::{ + CreateRtspsStream, DeleteRtspsStream, GetCamera, GetCameras, GetRtspsStreams, PatchCamera, + }, + chimes::{GetChime, GetChimes, PatchChime}, + lights::{GetLight, GetLights, PatchLight}, + meta::GetMetaInfo, + nvr::GetNvr, + sensors::{GetSensor, GetSensors, PatchSensor}, + viewers::{GetViewer, GetViewers, PatchViewer}, +}; +use crate::protect::models::{ + Camera, CameraPatch, Chime, ChimePatch, Light, LightPatch, MetaInfo, Nvr, RtspsQuality, + RtspsStreams, Sensor, SensorPatch, Viewer, ViewerPatch, +}; +use crate::transport; +use reqwest::Client; + +/// Base path of the official Protect Integration API on a local console. +pub const PROTECT_BASE_PATH: &str = "proxy/protect/integration/v1"; + +/// Client for the official UniFi Protect Integration API. +/// +/// Authenticates with an `X-API-Key` header. Generate a key in the Protect +/// app under Settings -> Control Plane -> Integrations. +/// +/// # Example +/// ```no_run +/// use rustifi::protect::ProtectClient; +/// +/// # async fn run() -> rustifi::Result<()> { +/// // Local consoles usually have self-signed certs; see `new_insecure`. +/// let client = ProtectClient::new("https://protect.example.com", "your-api-key")?; +/// let cameras = client.cameras().await?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Clone, Debug)] +pub struct ProtectClient { + http: Client, + base_url: String, + api_key: String, + accept_invalid_certs: bool, +} + +impl ProtectClient { + /// Create a new Protect client with strict TLS validation. + /// + /// # Errors + /// Returns an error if the API key contains invalid HTTP header characters. + pub fn new(base_url: impl Into, api_key: impl Into) -> Result { + Self::build(base_url, api_key, false) + } + + /// Create a new Protect client that accepts invalid/self-signed TLS certificates. + /// + /// # Security Warning + /// **This disables TLS certificate validation.** Only use this for local + /// consoles with self-signed certificates on trusted networks. Using this + /// over untrusted networks exposes you to man-in-the-middle attacks. + /// + /// # Errors + /// Returns an error if the API key contains invalid HTTP header characters. + pub fn new_insecure(base_url: impl Into, api_key: impl Into) -> Result { + Self::build(base_url, api_key, true) + } + + fn build( + base_url: impl Into, + api_key: impl Into, + accept_invalid_certs: bool, + ) -> Result { + // Validate the API key can be parsed as a header value early + let api_key = api_key.into(); + let _: reqwest::header::HeaderValue = api_key.parse()?; + + let http = transport::build_http_client(accept_invalid_certs, false)?; + + Ok(Self { + http, + base_url: base_url.into().trim_end_matches('/').to_string(), + api_key, + accept_invalid_certs, + }) + } + + pub fn base_url(&self) -> &str { + &self.base_url + } + + pub fn api_key(&self) -> &str { + &self.api_key + } + + pub(crate) fn accepts_invalid_certs(&self) -> bool { + self.accept_invalid_certs + } + + /// Execute a request for an endpoint instance. + /// Use this when the endpoint has dynamic path parameters. + pub async fn execute(&self, endpoint: &E) -> Result + where + E: Endpoint, + E::Response: for<'a> serde::Deserialize<'a>, + { + let url_prefix = format!("{}/{}", self.base_url, PROTECT_BASE_PATH); + transport::execute_endpoint(&self.http, &url_prefix, Some(&self.api_key), endpoint).await + } + + /// Execute a request for endpoints without dynamic path parameters. + /// For endpoints with path parameters, use `execute()` instead. + pub async fn request(&self) -> Result + where + E: Endpoint + Default, + E::Response: for<'a> serde::Deserialize<'a>, + { + self.execute(&E::default()).await + } + + /// Fetch a JPEG snapshot from a camera. + /// Endpoint: GET /proxy/protect/integration/v1/cameras/{id}/snapshot + /// + /// Returns the raw JPEG bytes. This is a dedicated method because the + /// [`Endpoint`] trait models JSON responses only; if more binary endpoints + /// are added later, a `RawEndpoint` trait may replace this. + pub async fn snapshot(&self, camera_id: &str, high_quality: bool) -> Result> { + let url = format!( + "{}/{}/cameras/{}/snapshot", + self.base_url, + PROTECT_BASE_PATH, + crate::protect::api::encode_id(camera_id) + ); + + let response = self + .http + .get(&url) + .header( + "X-API-Key", + self.api_key.parse::()?, + ) + .query(&[("highQuality", high_quality.to_string())]) + .send() + .await?; + + if !response.status().is_success() { + let status = response.status().as_u16(); + let body = response.text().await.unwrap_or_default(); + return Err(Error::Api { status, body }); + } + + Ok(response.bytes().await?.to_vec()) + } + + /// Fetch Protect application version info. + pub async fn meta_info(&self) -> Result { + self.execute(&GetMetaInfo).await + } + + /// Fetch all cameras. + pub async fn cameras(&self) -> Result> { + self.execute(&GetCameras).await + } + + /// Fetch a single camera by ID. + pub async fn camera(&self, id: &str) -> Result { + self.execute(&GetCamera::new(id)).await + } + + /// Partially update a camera's settings. + pub async fn patch_camera(&self, id: &str, patch: CameraPatch) -> Result { + self.execute(&PatchCamera::new(id, patch)).await + } + + /// Fetch the currently provisioned RTSPS stream URLs for a camera. + pub async fn rtsps_streams(&self, camera_id: &str) -> Result { + self.execute(&GetRtspsStreams::new(camera_id)).await + } + + /// Provision RTSPS streams for the given qualities. + pub async fn create_rtsps_streams( + &self, + camera_id: &str, + qualities: Vec, + ) -> Result { + self.execute(&CreateRtspsStream::new(camera_id, qualities)) + .await + } + + /// Remove provisioned RTSPS streams for the given qualities. + pub async fn delete_rtsps_streams( + &self, + camera_id: &str, + qualities: Vec, + ) -> Result<()> { + self.execute(&DeleteRtspsStream::new(camera_id, qualities)) + .await?; + Ok(()) + } + + /// Fetch all lights. + pub async fn lights(&self) -> Result> { + self.execute(&GetLights).await + } + + /// Fetch a single light by ID. + pub async fn light(&self, id: &str) -> Result { + self.execute(&GetLight::new(id)).await + } + + /// Partially update a light's settings. + pub async fn patch_light(&self, id: &str, patch: LightPatch) -> Result { + self.execute(&PatchLight::new(id, patch)).await + } + + /// Fetch all sensors. + pub async fn sensors(&self) -> Result> { + self.execute(&GetSensors).await + } + + /// Fetch a single sensor by ID. + pub async fn sensor(&self, id: &str) -> Result { + self.execute(&GetSensor::new(id)).await + } + + /// Partially update a sensor's settings. + pub async fn patch_sensor(&self, id: &str, patch: SensorPatch) -> Result { + self.execute(&PatchSensor::new(id, patch)).await + } + + /// Fetch all chimes. + pub async fn chimes(&self) -> Result> { + self.execute(&GetChimes).await + } + + /// Fetch a single chime by ID. + pub async fn chime(&self, id: &str) -> Result { + self.execute(&GetChime::new(id)).await + } + + /// Partially update a chime's settings. + pub async fn patch_chime(&self, id: &str, patch: ChimePatch) -> Result { + self.execute(&PatchChime::new(id, patch)).await + } + + /// Fetch all viewers. + pub async fn viewers(&self) -> Result> { + self.execute(&GetViewers).await + } + + /// Fetch a single viewer by ID. + pub async fn viewer(&self, id: &str) -> Result { + self.execute(&GetViewer::new(id)).await + } + + /// Partially update a viewer's settings. + pub async fn patch_viewer(&self, id: &str, patch: ViewerPatch) -> Result { + self.execute(&PatchViewer::new(id, patch)).await + } + + /// Fetch NVR / console information. + pub async fn nvr(&self) -> Result { + self.execute(&GetNvr).await + } +} diff --git a/src/protect/mod.rs b/src/protect/mod.rs new file mode 100644 index 0000000..125467f --- /dev/null +++ b/src/protect/mod.rs @@ -0,0 +1,28 @@ +//! UniFi Protect Integration API support. +//! +//! This module wraps the official Protect Integration API (Protect >= 5.3), +//! available at `https://{console}/proxy/protect/integration/v1`. It uses the +//! same `X-API-Key` authentication as the Network Integration API. +//! +//! Enable with the `protect` cargo feature: +//! +//! ```toml +//! rustifi = { version = "2", features = ["protect"] } +//! ``` + +pub mod api; +pub mod client; +pub mod models; +pub mod ws; + +pub use client::{ProtectClient, PROTECT_BASE_PATH}; + +pub mod prelude { + pub use crate::protect::client::ProtectClient; + pub use crate::protect::models::{ + Camera, CameraPatch, Chime, Light, ModelKey, Nvr, ProtectDeviceState, ProtectEvent, + ProtectEventType, RtspsQuality, RtspsStreams, Sensor, SmartDetectType, Viewer, WsAction, + WsMessage, + }; + pub use crate::protect::ws::{DeviceUpdateStream, ProtectEventStream}; +} diff --git a/src/protect/models/camera.rs b/src/protect/models/camera.rs new file mode 100644 index 0000000..5544ad3 --- /dev/null +++ b/src/protect/models/camera.rs @@ -0,0 +1,206 @@ +use super::common::{ModelKey, ProtectDeviceState}; +use crate::models::common::MacAddress; +use serde::{Deserialize, Serialize}; + +/// A Protect camera as returned by `GET /cameras` and `GET /cameras/{id}`. +/// +/// Fields that are not guaranteed to be present on every camera model or +/// Protect release are `Option` — Ubiquiti adds fields per release. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Camera { + pub id: String, + #[serde(default)] + pub model_key: ModelKey, + #[serde(default)] + pub state: ProtectDeviceState, + #[serde(default)] + pub name: String, + #[serde(default)] + pub mac: Option, + #[serde(default)] + pub model: Option, + #[serde(default, rename = "type")] + pub type_field: Option, + #[serde(default)] + pub firmware_version: Option, + #[serde(default)] + pub is_mic_enabled: Option, + #[serde(default)] + pub mic_volume: Option, + #[serde(default)] + pub video_mode: Option, + #[serde(default)] + pub hdr_type: Option, + #[serde(default)] + pub osd_settings: Option, + #[serde(default)] + pub led_settings: Option, + #[serde(default)] + pub lcd_message: Option, + #[serde(default)] + pub smart_detect_settings: Option, + #[serde(default)] + pub recording_settings: Option, + #[serde(default)] + pub feature_flags: Option, + #[serde(default)] + pub is_third_party_camera: Option, + #[serde(default)] + pub active_patrol_slot: Option, +} + +/// On-screen display settings for a camera. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct OsdSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub is_name_enabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub is_date_enabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub is_logo_enabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub is_debug_enabled: Option, +} + +/// Status LED settings for a camera. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct LedSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub is_enabled: Option, +} + +/// LCD message shown on doorbell cameras. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct LcdMessage { + #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")] + pub type_field: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reset_at: Option, +} + +/// Smart detection configuration for a camera. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct SmartDetectSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub object_types: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auto_tracking_object_types: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub audio_types: Option>, +} + +/// Recording configuration for a camera. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct RecordingSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pre_padding_secs: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub post_padding_secs: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub retention_duration_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_motion_event_delay: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub suppress_illumination_surge: Option, +} + +/// Capabilities reported by a camera. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CameraFeatureFlags { + #[serde(default)] + pub has_hdr: Option, + #[serde(default)] + pub has_mic: Option, + #[serde(default)] + pub has_led_status: Option, + #[serde(default)] + pub has_speaker: Option, + #[serde(default)] + pub has_chime: Option, + #[serde(default)] + pub has_smart_detect: Option, + #[serde(default)] + pub smart_detect_types: Option>, + #[serde(default)] + pub smart_detect_audio_types: Option>, + #[serde(default)] + pub video_modes: Option>, + #[serde(default)] + pub hdr_types: Option>, + #[serde(default)] + pub is_ptz: Option, +} + +/// Partial update body for `PATCH /cameras/{id}`. +/// +/// Only fields set to `Some` are serialized and sent. +#[derive(Clone, Debug, Default, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CameraPatch { + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub osd_settings: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub led_settings: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub lcd_message: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub mic_volume: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub video_mode: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub hdr_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub smart_detect_settings: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub recording_settings: Option, +} + +/// RTSPS stream URLs per quality, from the `/cameras/{id}/rtsps-stream` endpoints. +/// +/// A quality is `None` when no stream is provisioned for it. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct RtspsStreams { + #[serde(default)] + pub high: Option, + #[serde(default)] + pub medium: Option, + #[serde(default)] + pub low: Option, + #[serde(default)] + pub package: Option, +} + +/// Stream quality selector for RTSPS stream management. +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "camelCase")] +pub enum RtspsQuality { + High, + Medium, + Low, + Package, +} + +impl RtspsQuality { + pub fn as_str(&self) -> &'static str { + match self { + RtspsQuality::High => "high", + RtspsQuality::Medium => "medium", + RtspsQuality::Low => "low", + RtspsQuality::Package => "package", + } + } +} diff --git a/src/protect/models/chime.rs b/src/protect/models/chime.rs new file mode 100644 index 0000000..fd01e1c --- /dev/null +++ b/src/protect/models/chime.rs @@ -0,0 +1,56 @@ +use super::common::{ModelKey, ProtectDeviceState}; +use crate::models::common::MacAddress; +use serde::{Deserialize, Serialize}; + +/// A Protect chime as returned by `GET /chimes` and `GET /chimes/{id}`. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Chime { + pub id: String, + #[serde(default)] + pub model_key: ModelKey, + #[serde(default)] + pub state: ProtectDeviceState, + #[serde(default)] + pub name: String, + #[serde(default)] + pub mac: Option, + #[serde(default)] + pub model: Option, + #[serde(default)] + pub firmware_version: Option, + #[serde(default)] + pub volume: Option, + #[serde(default)] + pub camera_ids: Option>, + #[serde(default)] + pub ring_settings: Option>, +} + +/// Per-camera ring configuration for a chime. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct RingSetting { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub camera_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub repeat_times: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub track_no: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub volume: Option, +} + +/// Partial update body for `PATCH /chimes/{id}`. +#[derive(Clone, Debug, Default, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ChimePatch { + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub volume: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub camera_ids: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub ring_settings: Option>, +} diff --git a/src/protect/models/common.rs b/src/protect/models/common.rs new file mode 100644 index 0000000..bde9066 --- /dev/null +++ b/src/protect/models/common.rs @@ -0,0 +1,62 @@ +use serde::Deserialize; + +/// Connection state reported for every Protect device. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ProtectDeviceState { + Connected, + Connecting, + Disconnected, + #[serde(other)] + #[default] + Unknown, +} + +/// The `modelKey` discriminator present on every Protect object. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "camelCase")] +pub enum ModelKey { + Camera, + Light, + Sensor, + Chime, + Viewer, + Nvr, + Doorlock, + Event, + #[serde(other)] + #[default] + Unknown, +} + +/// A millisecond-precision Unix timestamp, as used by Protect events. +/// +/// Distinct from [`crate::models::common::Timestamp`], which holds seconds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct TimestampMillis(pub i64); + +impl TimestampMillis { + pub fn as_millis(&self) -> i64 { + self.0 + } + + pub fn as_secs(&self) -> i64 { + self.0 / 1000 + } +} + +impl std::fmt::Display for TimestampMillis { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +impl<'de> Deserialize<'de> for TimestampMillis { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let n = i64::deserialize(deserializer)?; + Ok(TimestampMillis(n)) + } +} diff --git a/src/protect/models/event.rs b/src/protect/models/event.rs new file mode 100644 index 0000000..abc4ccd --- /dev/null +++ b/src/protect/models/event.rs @@ -0,0 +1,96 @@ +use super::common::ModelKey; +use serde::Deserialize; + +/// Envelope for messages received on the Protect WebSocket subscriptions. +/// +/// Both `/subscribe/events` and `/subscribe/devices` deliver frames shaped as +/// `{"type": "add" | "update", "item": {...}}`. +#[derive(Clone, Debug, Deserialize, PartialEq)] +pub struct WsMessage { + #[serde(rename = "type")] + pub action: WsAction, + pub item: T, +} + +/// The action discriminator on a WebSocket frame. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "camelCase")] +pub enum WsAction { + Add, + Update, + Remove, + #[serde(other)] + #[default] + Unknown, +} + +/// A motion, smart-detection, doorbell, or connectivity event. +/// +/// Delivered via the `/subscribe/events` WebSocket. Events arrive as an `add` +/// when they start and an `update` (with `end` set) when they finish. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ProtectEvent { + pub id: String, + #[serde(default)] + pub model_key: ModelKey, + #[serde(default, rename = "type")] + pub event_type: ProtectEventType, + /// Event start, epoch milliseconds. + #[serde(default)] + pub start: i64, + /// Event end, epoch milliseconds. `None` while the event is ongoing. + #[serde(default)] + pub end: Option, + /// ID of the device that produced the event. + #[serde(default)] + pub device: String, + #[serde(default)] + pub smart_detect_types: Vec, +} + +/// The kind of a Protect event. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "camelCase")] +pub enum ProtectEventType { + Motion, + SmartDetectZone, + SmartDetectLine, + /// Doorbell ring. + Doorbell, + Disconnect, + #[serde(other)] + #[default] + Unknown, +} + +/// Object classes recognized by smart detection. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "camelCase")] +pub enum SmartDetectType { + Person, + Vehicle, + Animal, + Face, + Package, + LicensePlate, + #[serde(other)] + #[default] + Unknown, +} + +/// A partial device-state patch from the `/subscribe/devices` WebSocket. +/// +/// Frames carry heterogeneous partial updates for any device type, so only the +/// identifying fields are typed; the remaining fields are kept as raw JSON in +/// [`Self::fields`]. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct DeviceUpdate { + #[serde(default)] + pub id: String, + #[serde(default)] + pub model_key: ModelKey, + #[serde(flatten)] + pub fields: serde_json::Map, +} diff --git a/src/protect/models/light.rs b/src/protect/models/light.rs new file mode 100644 index 0000000..b0074c9 --- /dev/null +++ b/src/protect/models/light.rs @@ -0,0 +1,72 @@ +use super::common::{ModelKey, ProtectDeviceState}; +use crate::models::common::MacAddress; +use serde::{Deserialize, Serialize}; + +/// A Protect floodlight as returned by `GET /lights` and `GET /lights/{id}`. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Light { + pub id: String, + #[serde(default)] + pub model_key: ModelKey, + #[serde(default)] + pub state: ProtectDeviceState, + #[serde(default)] + pub name: String, + #[serde(default)] + pub mac: Option, + #[serde(default)] + pub model: Option, + #[serde(default)] + pub firmware_version: Option, + #[serde(default)] + pub is_light_on: Option, + #[serde(default)] + pub is_pir_motion_detected: Option, + #[serde(default)] + pub is_locating: Option, + #[serde(default)] + pub camera_id: Option, + #[serde(default)] + pub light_mode_settings: Option, + #[serde(default)] + pub light_device_settings: Option, +} + +/// When and how the light activates. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct LightModeSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub enable_at: Option, +} + +/// Hardware settings for the light. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct LightDeviceSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub is_indicator_enabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub led_level: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pir_duration: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pir_sensitivity: Option, +} + +/// Partial update body for `PATCH /lights/{id}`. +#[derive(Clone, Debug, Default, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct LightPatch { + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub is_light_on: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub light_mode_settings: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub light_device_settings: Option, +} diff --git a/src/protect/models/mod.rs b/src/protect/models/mod.rs new file mode 100644 index 0000000..6888536 --- /dev/null +++ b/src/protect/models/mod.rs @@ -0,0 +1,25 @@ +pub mod camera; +pub mod chime; +pub mod common; +pub mod event; +pub mod light; +pub mod nvr; +pub mod sensor; +pub mod viewer; + +pub use camera::{ + Camera, CameraFeatureFlags, CameraPatch, LcdMessage, LedSettings, OsdSettings, + RecordingSettings, RtspsQuality, RtspsStreams, SmartDetectSettings, +}; +pub use chime::{Chime, ChimePatch, RingSetting}; +pub use common::{ModelKey, ProtectDeviceState, TimestampMillis}; +pub use event::{ + DeviceUpdate, ProtectEvent, ProtectEventType, SmartDetectType, WsAction, WsMessage, +}; +pub use light::{Light, LightDeviceSettings, LightModeSettings, LightPatch}; +pub use nvr::{MetaInfo, Nvr}; +pub use sensor::{ + BatteryStatus, Sensor, SensorAlarmSettings, SensorPatch, SensorReading, SensorSettings, + SensorStats, +}; +pub use viewer::{Viewer, ViewerPatch}; diff --git a/src/protect/models/nvr.rs b/src/protect/models/nvr.rs new file mode 100644 index 0000000..e3ebc84 --- /dev/null +++ b/src/protect/models/nvr.rs @@ -0,0 +1,41 @@ +use super::common::ModelKey; +use crate::models::common::MacAddress; +use serde::Deserialize; + +/// The Protect NVR / console as returned by `GET /nvrs`. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Nvr { + #[serde(default)] + pub id: String, + #[serde(default)] + pub model_key: ModelKey, + #[serde(default)] + pub name: String, + #[serde(default)] + pub mac: Option, + #[serde(default)] + pub version: Option, + #[serde(default)] + pub firmware_version: Option, + #[serde(default)] + pub uptime: Option, + #[serde(default)] + pub hardware_platform: Option, + #[serde(default)] + pub hardware_id: Option, + #[serde(default)] + pub host: Option, + #[serde(default)] + pub ports: Option, + #[serde(default)] + pub storage_stats: Option, +} + +/// Application version info from `GET /meta/info`. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct MetaInfo { + #[serde(default)] + pub application_version: String, +} diff --git a/src/protect/models/sensor.rs b/src/protect/models/sensor.rs new file mode 100644 index 0000000..b8367f5 --- /dev/null +++ b/src/protect/models/sensor.rs @@ -0,0 +1,116 @@ +use super::common::{ModelKey, ProtectDeviceState}; +use crate::models::common::MacAddress; +use serde::{Deserialize, Serialize}; + +/// A Protect sensor as returned by `GET /sensors` and `GET /sensors/{id}`. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Sensor { + pub id: String, + #[serde(default)] + pub model_key: ModelKey, + #[serde(default)] + pub state: ProtectDeviceState, + #[serde(default)] + pub name: String, + #[serde(default)] + pub mac: Option, + #[serde(default)] + pub model: Option, + #[serde(default)] + pub firmware_version: Option, + #[serde(default)] + pub mount_type: Option, + #[serde(default)] + pub is_opened: Option, + #[serde(default)] + pub is_motion_detected: Option, + #[serde(default)] + pub battery_status: Option, + #[serde(default)] + pub stats: Option, + #[serde(default)] + pub alarm_settings: Option, + #[serde(default)] + pub light_settings: Option, + #[serde(default)] + pub motion_settings: Option, + #[serde(default)] + pub temperature_settings: Option, + #[serde(default)] + pub humidity_settings: Option, +} + +/// Battery level and charge state. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BatteryStatus { + #[serde(default)] + pub percentage: Option, + #[serde(default)] + pub is_low: Option, +} + +/// Latest environmental readings from the sensor. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SensorStats { + #[serde(default)] + pub light: Option, + #[serde(default)] + pub temperature: Option, + #[serde(default)] + pub humidity: Option, +} + +/// A single reading with its value and status. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SensorReading { + #[serde(default)] + pub value: Option, + #[serde(default)] + pub status: Option, +} + +/// Alarm sound detection settings. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct SensorAlarmSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub is_enabled: Option, +} + +/// Generic enable/threshold settings block shared by sensor capabilities. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SensorSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub is_enabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sensitivity: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub low_threshold: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub high_threshold: Option, +} + +/// Partial update body for `PATCH /sensors/{id}`. +#[derive(Clone, Debug, Default, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SensorPatch { + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub mount_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub alarm_settings: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub light_settings: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub motion_settings: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub temperature_settings: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub humidity_settings: Option, +} diff --git a/src/protect/models/viewer.rs b/src/protect/models/viewer.rs new file mode 100644 index 0000000..53ff344 --- /dev/null +++ b/src/protect/models/viewer.rs @@ -0,0 +1,35 @@ +use super::common::{ModelKey, ProtectDeviceState}; +use crate::models::common::MacAddress; +use serde::{Deserialize, Serialize}; + +/// A Protect viewer (ViewPort) as returned by `GET /viewers` and `GET /viewers/{id}`. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Viewer { + pub id: String, + #[serde(default)] + pub model_key: ModelKey, + #[serde(default)] + pub state: ProtectDeviceState, + #[serde(default)] + pub name: String, + #[serde(default)] + pub mac: Option, + #[serde(default)] + pub model: Option, + #[serde(default)] + pub firmware_version: Option, + /// ID of the liveview currently shown on this viewer. + #[serde(default)] + pub liveview: Option, +} + +/// Partial update body for `PATCH /viewers/{id}`. +#[derive(Clone, Debug, Default, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ViewerPatch { + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub liveview: Option, +} diff --git a/src/protect/ws.rs b/src/protect/ws.rs new file mode 100644 index 0000000..6d7ac95 --- /dev/null +++ b/src/protect/ws.rs @@ -0,0 +1,171 @@ +//! Live event subscriptions over the Protect Integration API WebSocket. +//! +//! The streams end (`poll_next` returns `None`) when the console closes the +//! connection or a transport error occurs. The API offers no replay cursor, so +//! events occurring while disconnected are lost; reconnect by calling the +//! subscribe method again: +//! +//! ```no_run +//! # use futures::StreamExt; +//! # async fn run(client: rustifi::protect::ProtectClient) -> rustifi::Result<()> { +//! loop { +//! let mut stream = client.subscribe_events().await?; +//! while let Some(msg) = stream.next().await { +//! match msg { +//! Ok(event) => println!("{:?}", event), +//! Err(e) => eprintln!("stream error: {}", e), +//! } +//! } +//! tokio::time::sleep(std::time::Duration::from_secs(5)).await; +//! } +//! # } +//! ``` + +use crate::error::{Error, Result}; +use crate::protect::client::{ProtectClient, PROTECT_BASE_PATH}; +use crate::protect::models::{DeviceUpdate, ProtectEvent, WsMessage}; +use futures::stream::Stream; +use std::marker::PhantomData; +use std::pin::Pin; +use std::task::{Context, Poll}; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::{ + connect_async_tls_with_config, Connector, MaybeTlsStream, WebSocketStream, +}; + +type WsStream = WebSocketStream>; + +/// Stream of Protect events from `/subscribe/events`. +pub type ProtectEventStream = TypedWsStream; + +/// Stream of partial device updates from `/subscribe/devices`. +pub type DeviceUpdateStream = TypedWsStream; + +/// A WebSocket connection yielding typed `{"type": ..., "item": ...}` frames. +/// +/// - Text frames are deserialized to `WsMessage`; failures yield +/// [`Error::Parse`] without ending the stream. +/// - Ping/pong/binary frames are skipped (tungstenite answers pings itself). +/// - A close frame or transport error yields [`Error::WebSocket`] and then the +/// stream ends. +pub struct TypedWsStream { + inner: WsStream, + // Set after a close frame or transport error; the stream then ends + // instead of surfacing follow-up frames from the closing handshake. + terminated: bool, + // fn() -> T keeps the stream Unpin/Send regardless of T, which is only + // ever produced by deserialization, never stored. + _marker: PhantomData T>, +} + +impl std::fmt::Debug for TypedWsStream { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TypedWsStream").finish_non_exhaustive() + } +} + +impl Stream for TypedWsStream +where + T: for<'a> serde::Deserialize<'a>, +{ + type Item = Result>; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if self.terminated { + return Poll::Ready(None); + } + loop { + match Pin::new(&mut self.inner).poll_next(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + self.terminated = true; + return Poll::Ready(None); + } + Poll::Ready(Some(Ok(Message::Text(text)))) => { + let parsed = serde_json::from_str::>(text.as_str()) + .map_err(|e| Error::Parse(format!("{}\nFrame: {}", e, text))); + return Poll::Ready(Some(parsed)); + } + Poll::Ready(Some(Ok(Message::Close(frame)))) => { + self.terminated = true; + let reason = frame + .map(|f| format!("connection closed: {} {}", f.code, f.reason)) + .unwrap_or_else(|| "connection closed".to_string()); + return Poll::Ready(Some(Err(Error::WebSocket(reason)))); + } + // Ping/pong/binary/raw frames carry no events; keep polling. + Poll::Ready(Some(Ok(_))) => continue, + Poll::Ready(Some(Err(e))) => { + self.terminated = true; + return Poll::Ready(Some(Err(Error::WebSocket(e.to_string())))); + } + } + } + } +} + +async fn connect(client: &ProtectClient, endpoint: &str) -> Result> { + let mut url = url::Url::parse(client.base_url())?; + let ws_scheme = match url.scheme() { + "https" | "wss" => "wss", + _ => "ws", + }; + url.set_scheme(ws_scheme).map_err(|_| { + Error::WebSocket(format!("cannot derive ws url from {}", client.base_url())) + })?; + + let ws_url = format!( + "{}/{}/{}", + url.as_str().trim_end_matches('/'), + PROTECT_BASE_PATH, + endpoint + ); + + let mut request = ws_url + .into_client_request() + .map_err(|e| Error::WebSocket(e.to_string()))?; + request + .headers_mut() + .insert("X-API-Key", client.api_key().parse()?); + + let connector = if client.accepts_invalid_certs() { + let tls = native_tls::TlsConnector::builder() + .danger_accept_invalid_certs(true) + .danger_accept_invalid_hostnames(true) + .build() + .map_err(|e| Error::WebSocket(e.to_string()))?; + Some(Connector::NativeTls(tls)) + } else { + None + }; + + let (inner, _response) = connect_async_tls_with_config(request, None, false, connector) + .await + .map_err(|e| Error::WebSocket(e.to_string()))?; + + Ok(TypedWsStream { + inner, + terminated: false, + _marker: PhantomData, + }) +} + +impl ProtectClient { + /// Subscribe to live motion, smart-detection, doorbell, and connectivity + /// events. + /// Endpoint: WSS /proxy/protect/integration/v1/subscribe/events + /// + /// See the [module docs](self) for the reconnect idiom. + pub async fn subscribe_events(&self) -> Result { + connect(self, "subscribe/events").await + } + + /// Subscribe to live partial device-state updates. + /// Endpoint: WSS /proxy/protect/integration/v1/subscribe/devices + /// + /// See the [module docs](self) for the reconnect idiom. + pub async fn subscribe_device_updates(&self) -> Result { + connect(self, "subscribe/devices").await + } +} diff --git a/src/transport.rs b/src/transport.rs new file mode 100644 index 0000000..9834535 --- /dev/null +++ b/src/transport.rs @@ -0,0 +1,101 @@ +//! Shared HTTP transport used by the UniFi Network and Protect clients. + +use crate::api::endpoint::{Endpoint, HttpMethod}; +use crate::error::Result; +use reqwest::Client; + +/// Build a reqwest client with the crate's standard settings. +/// +/// # Security Warning +/// Passing `accept_invalid_certs = true` disables TLS certificate validation. +/// Only use this for local consoles with self-signed certificates on trusted +/// networks. +pub(crate) fn build_http_client(accept_invalid_certs: bool, cookies: bool) -> Result { + let mut builder = Client::builder() + .user_agent("rustifi/1.0") + .connect_timeout(std::time::Duration::from_secs(30)) + .timeout(std::time::Duration::from_secs(60)); + + if cookies { + let cookie_store = std::sync::Arc::new(reqwest::cookie::Jar::default()); + builder = builder.cookie_store(true).cookie_provider(cookie_store); + } + + if accept_invalid_certs { + builder = builder + .danger_accept_invalid_certs(true) + .danger_accept_invalid_hostnames(true); + } + + Ok(builder.build()?) +} + +/// Execute an [`Endpoint`] request against `{url_prefix}/{path}` and +/// deserialize the JSON response. +/// +/// `url_prefix` is the caller-computed base (e.g. `https://host/api/v1` or the +/// remote connector form) without a trailing slash. +pub(crate) async fn execute_endpoint( + http: &Client, + url_prefix: &str, + api_key: Option<&str>, + endpoint: &E, +) -> Result +where + E: Endpoint, + E::Response: for<'a> serde::Deserialize<'a>, +{ + let url = format!("{}/{}", url_prefix, endpoint.build_path()); + + let mut headers = reqwest::header::HeaderMap::new(); + if let Some(api_key) = api_key { + headers.insert("X-API-Key", api_key.parse()?); + } + + let mut request = http.request(E::METHOD.into(), &url).headers(headers); + + // Append query parameters using reqwest's query() for proper URL encoding + let params = endpoint.query_params(); + if !params.is_empty() { + request = request.query(¶ms); + } + + // Add JSON body for POST/PUT/PATCH methods + if let Some(body) = endpoint.request_body()? { + request = request.json(&body); + } + + let response = request.send().await?; + + if !response.status().is_success() { + // Preserve the error body — controllers return JSON describing the + // actual failure reason, which error_for_status() would discard. + let status = response.status().as_u16(); + let body = response.text().await.unwrap_or_default(); + return Err(crate::error::Error::Api { status, body }); + } + + let body = response.text().await?; + // Some endpoints (e.g. DELETE) return an empty body; deserialize it as null + // so responses typed as Option<_> or () succeed. + let effective_body = if body.trim().is_empty() { + "null" + } else { + &body + }; + let response_data = serde_json::from_str::(effective_body) + .map_err(|e| crate::error::Error::Parse(format!("{}\nResponse body: {}", e, body)))?; + Ok(response_data) +} + +impl From for reqwest::Method { + fn from(method: HttpMethod) -> Self { + match method { + HttpMethod::Get => reqwest::Method::GET, + HttpMethod::Post => reqwest::Method::POST, + HttpMethod::Put => reqwest::Method::PUT, + HttpMethod::Patch => reqwest::Method::PATCH, + HttpMethod::Delete => reqwest::Method::DELETE, + } + } +} diff --git a/tests/device_tests.rs b/tests/device_tests.rs index d239514..c50c45f 100644 --- a/tests/device_tests.rs +++ b/tests/device_tests.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "unifi")] + use rustifi::models::{Device, DeviceType}; use serde_json::json; diff --git a/tests/pagination_tests.rs b/tests/pagination_tests.rs index af456be..3366e44 100644 --- a/tests/pagination_tests.rs +++ b/tests/pagination_tests.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "unifi")] + use rustifi::api::clients::GetClients; use rustifi::api::devices::GetDevices; use rustifi::api::Endpoint; diff --git a/tests/protect_client.rs b/tests/protect_client.rs new file mode 100644 index 0000000..0d29351 --- /dev/null +++ b/tests/protect_client.rs @@ -0,0 +1,193 @@ +#![cfg(feature = "protect")] + +use rustifi::protect::models::{CameraPatch, RtspsQuality}; +use rustifi::protect::ProtectClient; +use serde_json::json; +use wiremock::matchers::{body_json, header, method, path, query_param}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +async fn client_for(server: &MockServer) -> ProtectClient { + ProtectClient::new(server.uri(), "test-api-key").unwrap() +} + +#[tokio::test] +async fn test_cameras_bare_array_and_api_key_header() { + let server = MockServer::start().await; + + Mock::given(method("GET")) + .and(path("/proxy/protect/integration/v1/cameras")) + .and(header("X-API-Key", "test-api-key")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!([ + { "id": "cam1", "modelKey": "camera", "state": "CONNECTED", "name": "Front" }, + { "id": "cam2", "modelKey": "camera", "state": "DISCONNECTED", "name": "Back" } + ]))) + .expect(1) + .mount(&server) + .await; + + let cameras = client_for(&server).await.cameras().await.unwrap(); + assert_eq!(cameras.len(), 2); + assert_eq!(cameras[0].id, "cam1"); + assert_eq!(cameras[1].name, "Back"); +} + +#[tokio::test] +async fn test_patch_camera_sends_only_set_fields() { + let server = MockServer::start().await; + + Mock::given(method("PATCH")) + .and(path("/proxy/protect/integration/v1/cameras/cam1")) + .and(header("X-API-Key", "test-api-key")) + .and(body_json(json!({ "name": "Renamed", "micVolume": 42 }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "id": "cam1", "modelKey": "camera", "state": "CONNECTED", "name": "Renamed", + "micVolume": 42 + }))) + .expect(1) + .mount(&server) + .await; + + let patch = CameraPatch { + name: Some("Renamed".to_string()), + mic_volume: Some(42), + ..Default::default() + }; + let camera = client_for(&server) + .await + .patch_camera("cam1", patch) + .await + .unwrap(); + assert_eq!(camera.name, "Renamed"); + assert_eq!(camera.mic_volume, Some(42)); +} + +#[tokio::test] +async fn test_snapshot_returns_binary_bytes() { + let server = MockServer::start().await; + // Not valid JSON and not valid UTF-8 — must round-trip untouched. + let jpeg_bytes: Vec = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46]; + + Mock::given(method("GET")) + .and(path("/proxy/protect/integration/v1/cameras/cam1/snapshot")) + .and(query_param("highQuality", "true")) + .and(header("X-API-Key", "test-api-key")) + .respond_with( + ResponseTemplate::new(200) + .set_body_bytes(jpeg_bytes.clone()) + .insert_header("content-type", "image/jpeg"), + ) + .expect(1) + .mount(&server) + .await; + + let bytes = client_for(&server) + .await + .snapshot("cam1", true) + .await + .unwrap(); + assert_eq!(bytes, jpeg_bytes); +} + +#[tokio::test] +async fn test_create_rtsps_stream_body_and_response() { + let server = MockServer::start().await; + + Mock::given(method("POST")) + .and(path( + "/proxy/protect/integration/v1/cameras/cam1/rtsps-stream", + )) + .and(body_json(json!({ "qualities": ["high", "low"] }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "high": "rtsps://10.0.0.1:7441/aaaa", + "low": "rtsps://10.0.0.1:7441/bbbb" + }))) + .expect(1) + .mount(&server) + .await; + + let streams = client_for(&server) + .await + .create_rtsps_streams("cam1", vec![RtspsQuality::High, RtspsQuality::Low]) + .await + .unwrap(); + assert_eq!(streams.high.as_deref(), Some("rtsps://10.0.0.1:7441/aaaa")); + assert_eq!(streams.medium, None); +} + +#[tokio::test] +async fn test_delete_rtsps_stream_query_params_and_empty_body() { + let server = MockServer::start().await; + + Mock::given(method("DELETE")) + .and(path( + "/proxy/protect/integration/v1/cameras/cam1/rtsps-stream", + )) + .and(query_param("qualities", "high")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + client_for(&server) + .await + .delete_rtsps_streams("cam1", vec![RtspsQuality::High]) + .await + .unwrap(); +} + +#[tokio::test] +async fn test_error_status_preserves_body() { + let server = MockServer::start().await; + + Mock::given(method("GET")) + .and(path("/proxy/protect/integration/v1/cameras/nope")) + .respond_with( + ResponseTemplate::new(404).set_body_json(json!({ "error": "camera not found" })), + ) + .mount(&server) + .await; + + let err = client_for(&server).await.camera("nope").await.unwrap_err(); + match err { + rustifi::Error::Api { status, body } => { + assert_eq!(status, 404); + assert!(body.contains("camera not found")); + } + other => panic!("expected Api error, got {other:?}"), + } +} + +#[tokio::test] +async fn test_resource_ids_are_path_encoded() { + let server = MockServer::start().await; + + // An ID containing a slash must be encoded into a single path segment, + // not allowed to change the route. + Mock::given(method("GET")) + .and(path("/proxy/protect/integration/v1/cameras/a%2Fb")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "id": "a/b", "modelKey": "camera", "state": "CONNECTED", "name": "Weird" + }))) + .expect(1) + .mount(&server) + .await; + + let camera = client_for(&server).await.camera("a/b").await.unwrap(); + assert_eq!(camera.name, "Weird"); +} + +#[tokio::test] +async fn test_meta_info() { + let server = MockServer::start().await; + + Mock::given(method("GET")) + .and(path("/proxy/protect/integration/v1/meta/info")) + .respond_with( + ResponseTemplate::new(200).set_body_json(json!({ "applicationVersion": "6.2.88" })), + ) + .mount(&server) + .await; + + let info = client_for(&server).await.meta_info().await.unwrap(); + assert_eq!(info.application_version, "6.2.88"); +} diff --git a/tests/protect_events.rs b/tests/protect_events.rs new file mode 100644 index 0000000..59f3a4d --- /dev/null +++ b/tests/protect_events.rs @@ -0,0 +1,148 @@ +#![cfg(feature = "protect")] + +use rustifi::protect::models::{ + DeviceUpdate, ModelKey, ProtectEvent, ProtectEventType, SmartDetectType, WsAction, WsMessage, +}; +use serde_json::json; + +#[test] +fn test_smart_detect_add_frame() { + let json_data = json!({ + "type": "add", + "item": { + "id": "68386a43006bf603e4002b3d", + "modelKey": "event", + "type": "smartDetectZone", + "start": 1748517571853i64, + "device": "61ddb03ba0a70603e4004fab", + "smartDetectTypes": ["person"] + } + }); + + let msg: WsMessage = serde_json::from_value(json_data).unwrap(); + assert_eq!(msg.action, WsAction::Add); + assert_eq!(msg.item.model_key, ModelKey::Event); + assert_eq!(msg.item.event_type, ProtectEventType::SmartDetectZone); + assert_eq!(msg.item.start, 1748517571853); + assert_eq!(msg.item.end, None); + assert_eq!(msg.item.device, "61ddb03ba0a70603e4004fab"); + assert_eq!(msg.item.smart_detect_types, vec![SmartDetectType::Person]); +} + +#[test] +fn test_smart_detect_update_frame_with_end() { + let json_data = json!({ + "type": "update", + "item": { + "id": "68386a43006bf603e4002b3d", + "modelKey": "event", + "type": "smartDetectZone", + "start": 1748517571853i64, + "end": 1748517581453i64, + "device": "61ddb03ba0a70603e4004fab", + "smartDetectTypes": ["face", "person"] + } + }); + + let msg: WsMessage = serde_json::from_value(json_data).unwrap(); + assert_eq!(msg.action, WsAction::Update); + assert_eq!(msg.item.end, Some(1748517581453)); + assert_eq!( + msg.item.smart_detect_types, + vec![SmartDetectType::Face, SmartDetectType::Person] + ); +} + +#[test] +fn test_motion_event_frame() { + let json_data = json!({ + "type": "add", + "item": { + "id": "68386a43006bf603e4002b3e", + "modelKey": "event", + "type": "motion", + "start": 1748517571853i64, + "device": "61ddb03ba0a70603e4004fab" + } + }); + + let msg: WsMessage = serde_json::from_value(json_data).unwrap(); + assert_eq!(msg.item.event_type, ProtectEventType::Motion); + assert!(msg.item.smart_detect_types.is_empty()); +} + +#[test] +fn test_doorbell_ring_frame() { + let json_data = json!({ + "type": "add", + "item": { + "id": "68386a43006bf603e4002b3f", + "modelKey": "event", + "type": "doorbell", + "start": 1748517571853i64, + "device": "61ddb03ba0a70603e4004fab" + } + }); + + let msg: WsMessage = serde_json::from_value(json_data).unwrap(); + assert_eq!(msg.item.event_type, ProtectEventType::Doorbell); +} + +#[test] +fn test_unknown_event_and_detect_types_tolerated() { + let json_data = json!({ + "type": "add", + "item": { + "id": "abc", + "modelKey": "event", + "type": "someFutureEventType", + "start": 1i64, + "device": "dev1", + "smartDetectTypes": ["hoverboard", "person"] + } + }); + + let msg: WsMessage = serde_json::from_value(json_data).unwrap(); + assert_eq!(msg.item.event_type, ProtectEventType::Unknown); + assert_eq!( + msg.item.smart_detect_types, + vec![SmartDetectType::Unknown, SmartDetectType::Person] + ); +} + +#[test] +fn test_unknown_ws_action_tolerated() { + let json_data = json!({ + "type": "somethingElse", + "item": { + "id": "abc", + "modelKey": "event", + "type": "motion", + "start": 1i64, + "device": "dev1" + } + }); + + let msg: WsMessage = serde_json::from_value(json_data).unwrap(); + assert_eq!(msg.action, WsAction::Unknown); +} + +#[test] +fn test_device_update_frame() { + let json_data = json!({ + "type": "update", + "item": { + "id": "61ddb03ba0a70603e4004fab", + "modelKey": "camera", + "state": "CONNECTED", + "isMicEnabled": false + } + }); + + let msg: WsMessage = serde_json::from_value(json_data).unwrap(); + assert_eq!(msg.action, WsAction::Update); + assert_eq!(msg.item.id, "61ddb03ba0a70603e4004fab"); + assert_eq!(msg.item.model_key, ModelKey::Camera); + assert_eq!(msg.item.fields.get("isMicEnabled"), Some(&json!(false))); + assert_eq!(msg.item.fields.get("state"), Some(&json!("CONNECTED"))); +} diff --git a/tests/protect_types.rs b/tests/protect_types.rs new file mode 100644 index 0000000..e798b25 --- /dev/null +++ b/tests/protect_types.rs @@ -0,0 +1,248 @@ +#![cfg(feature = "protect")] + +use rustifi::protect::models::{ + Camera, CameraPatch, Chime, Light, MetaInfo, ModelKey, Nvr, ProtectDeviceState, RtspsQuality, + RtspsStreams, Sensor, Viewer, +}; +use serde_json::json; + +#[test] +fn test_camera_deserialization() { + let json_data = json!({ + "id": "61ddb03ba0a70603e4004fab", + "modelKey": "camera", + "state": "CONNECTED", + "name": "Front Door", + "mac": "74ACB9000000", + "model": "UVC G4 Doorbell", + "type": "UVC G4 Doorbell", + "firmwareVersion": "4.71.42", + "isMicEnabled": true, + "micVolume": 100, + "videoMode": "default", + "hdrType": "auto", + "osdSettings": { + "isNameEnabled": false, + "isDateEnabled": false, + "isLogoEnabled": true, + "isDebugEnabled": false + }, + "ledSettings": { "isEnabled": true }, + "lcdMessage": { "type": "LEAVE_PACKAGE_AT_DOOR", "text": "" }, + "smartDetectSettings": { + "objectTypes": ["person", "vehicle"], + "autoTrackingObjectTypes": [], + "audioTypes": ["alrmSmoke"] + }, + "recordingSettings": { + "mode": "always", + "prePaddingSecs": 3, + "postPaddingSecs": 3 + }, + "featureFlags": { + "hasHdr": true, + "hasMic": true, + "hasLedStatus": true, + "smartDetectTypes": ["person", "vehicle"], + "videoModes": ["default"], + "isPtz": false + } + }); + + let camera: Camera = serde_json::from_value(json_data).unwrap(); + assert_eq!(camera.id, "61ddb03ba0a70603e4004fab"); + assert_eq!(camera.model_key, ModelKey::Camera); + assert_eq!(camera.state, ProtectDeviceState::Connected); + assert_eq!(camera.name, "Front Door"); + assert_eq!(camera.mac.unwrap().as_str(), "74ACB9000000"); + assert_eq!(camera.mic_volume, Some(100)); + assert_eq!(camera.osd_settings.unwrap().is_logo_enabled, Some(true)); + assert_eq!( + camera.smart_detect_settings.unwrap().object_types.unwrap(), + vec!["person", "vehicle"] + ); + assert!(camera.feature_flags.unwrap().has_hdr.unwrap()); +} + +#[test] +fn test_camera_minimal_and_unknown_fields() { + // Only guaranteed fields plus an unknown field from a future release + let json_data = json!({ + "id": "abc123", + "modelKey": "camera", + "state": "CONNECTED", + "name": "Minimal Cam", + "someFutureField": { "nested": true } + }); + + let camera: Camera = serde_json::from_value(json_data).unwrap(); + assert_eq!(camera.id, "abc123"); + assert_eq!(camera.mac, None); + assert_eq!(camera.osd_settings, None); +} + +#[test] +fn test_unknown_enum_variants_tolerated() { + let json_data = json!({ + "id": "abc123", + "modelKey": "somethingNew", + "state": "SOMETHING_NEW", + "name": "Future Device" + }); + + let camera: Camera = serde_json::from_value(json_data).unwrap(); + assert_eq!(camera.model_key, ModelKey::Unknown); + assert_eq!(camera.state, ProtectDeviceState::Unknown); +} + +#[test] +fn test_camera_patch_skips_none_fields() { + let patch = CameraPatch { + name: Some("New Name".to_string()), + mic_volume: Some(50), + ..Default::default() + }; + + let value = serde_json::to_value(&patch).unwrap(); + assert_eq!(value, json!({ "name": "New Name", "micVolume": 50 })); +} + +#[test] +fn test_rtsps_streams_deserialization() { + let json_data = json!({ + "high": "rtsps://192.168.1.1:7441/abcd1234", + "medium": null, + "low": "rtsps://192.168.1.1:7441/wxyz9876" + }); + + let streams: RtspsStreams = serde_json::from_value(json_data).unwrap(); + assert_eq!( + streams.high.as_deref(), + Some("rtsps://192.168.1.1:7441/abcd1234") + ); + assert_eq!(streams.medium, None); + assert_eq!(streams.package, None); +} + +#[test] +fn test_rtsps_quality_serialization() { + assert_eq!( + serde_json::to_value(RtspsQuality::High).unwrap(), + json!("high") + ); + assert_eq!(RtspsQuality::Package.as_str(), "package"); +} + +#[test] +fn test_light_deserialization() { + let json_data = json!({ + "id": "5f9b1c000000000000000000", + "modelKey": "light", + "state": "CONNECTED", + "name": "Backyard Floodlight", + "isLightOn": false, + "isPirMotionDetected": false, + "lightModeSettings": { "mode": "motion", "enableAt": "fulltime" }, + "lightDeviceSettings": { + "isIndicatorEnabled": true, + "ledLevel": 4, + "pirDuration": 15000, + "pirSensitivity": 50 + } + }); + + let light: Light = serde_json::from_value(json_data).unwrap(); + assert_eq!(light.name, "Backyard Floodlight"); + assert_eq!(light.is_light_on, Some(false)); + assert_eq!( + light.light_mode_settings.unwrap().mode.as_deref(), + Some("motion") + ); + assert_eq!(light.light_device_settings.unwrap().led_level, Some(4)); +} + +#[test] +fn test_sensor_deserialization() { + let json_data = json!({ + "id": "5f9b2d000000000000000000", + "modelKey": "sensor", + "state": "CONNECTED", + "name": "Garage Door", + "mountType": "door", + "isOpened": false, + "batteryStatus": { "percentage": 87, "isLow": false }, + "stats": { + "light": { "value": 12.0, "status": "neutral" }, + "temperature": { "value": 21.5, "status": "neutral" }, + "humidity": { "value": 40.0, "status": "neutral" } + }, + "motionSettings": { "isEnabled": true, "sensitivity": 80 } + }); + + let sensor: Sensor = serde_json::from_value(json_data).unwrap(); + assert_eq!(sensor.mount_type.as_deref(), Some("door")); + assert_eq!(sensor.battery_status.unwrap().percentage, Some(87)); + let stats = sensor.stats.unwrap(); + assert_eq!(stats.temperature.unwrap().value, Some(21.5)); + assert_eq!(sensor.motion_settings.unwrap().sensitivity, Some(80)); +} + +#[test] +fn test_chime_deserialization() { + let json_data = json!({ + "id": "5f9b3e000000000000000000", + "modelKey": "chime", + "state": "CONNECTED", + "name": "Hallway Chime", + "volume": 80, + "cameraIds": ["61ddb03ba0a70603e4004fab"], + "ringSettings": [ + { "cameraId": "61ddb03ba0a70603e4004fab", "repeatTimes": 1, "trackNo": 1, "volume": 80 } + ] + }); + + let chime: Chime = serde_json::from_value(json_data).unwrap(); + assert_eq!(chime.volume, Some(80)); + assert_eq!(chime.camera_ids.unwrap().len(), 1); + assert_eq!(chime.ring_settings.unwrap()[0].repeat_times, Some(1)); +} + +#[test] +fn test_viewer_deserialization() { + let json_data = json!({ + "id": "5f9b4f000000000000000000", + "modelKey": "viewer", + "state": "DISCONNECTED", + "name": "Lobby Screen", + "liveview": "5f9b5a000000000000000000" + }); + + let viewer: Viewer = serde_json::from_value(json_data).unwrap(); + assert_eq!(viewer.state, ProtectDeviceState::Disconnected); + assert_eq!(viewer.liveview.as_deref(), Some("5f9b5a000000000000000000")); +} + +#[test] +fn test_nvr_deserialization() { + let json_data = json!({ + "id": "5f9b6b000000000000000000", + "modelKey": "nvr", + "name": "Dream Machine Pro", + "mac": "74ACB9111111", + "version": "5.3.41", + "uptime": 123456789i64, + "hardwarePlatform": "al324" + }); + + let nvr: Nvr = serde_json::from_value(json_data).unwrap(); + assert_eq!(nvr.name, "Dream Machine Pro"); + assert_eq!(nvr.version.as_deref(), Some("5.3.41")); + assert_eq!(nvr.uptime, Some(123456789)); +} + +#[test] +fn test_meta_info_deserialization() { + let json_data = json!({ "applicationVersion": "6.2.88" }); + let info: MetaInfo = serde_json::from_value(json_data).unwrap(); + assert_eq!(info.application_version, "6.2.88"); +} diff --git a/tests/protect_ws.rs b/tests/protect_ws.rs new file mode 100644 index 0000000..0abe65c --- /dev/null +++ b/tests/protect_ws.rs @@ -0,0 +1,95 @@ +#![cfg(feature = "protect")] + +use futures::{SinkExt, StreamExt}; +use rustifi::protect::models::{ProtectEventType, WsAction}; +use rustifi::protect::ProtectClient; +use rustifi::Error; +use tokio_tungstenite::tungstenite::Message; + +/// Spawn a WebSocket server on an ephemeral port that accepts one connection, +/// sends the given frames, and then closes. +async fn spawn_ws_server(frames: Vec) -> String { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + + tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap(); + for frame in frames { + ws.send(frame).await.unwrap(); + } + let _ = ws.close(None).await; + }); + + format!("http://{}", addr) +} + +fn event_frame(event_type: &str) -> Message { + Message::Text( + format!( + r#"{{"type":"add","item":{{"id":"e1","modelKey":"event","type":"{}","start":1748517571853,"device":"cam1","smartDetectTypes":[]}}}}"#, + event_type + ) + .into(), + ) +} + +#[tokio::test] +async fn test_event_stream_decodes_text_frames() { + let base_url = + spawn_ws_server(vec![event_frame("motion"), event_frame("smartDetectZone")]).await; + + let client = ProtectClient::new(base_url, "test-key").unwrap(); + let mut stream = client.subscribe_events().await.unwrap(); + + let first = stream.next().await.unwrap().unwrap(); + assert_eq!(first.action, WsAction::Add); + assert_eq!(first.item.event_type, ProtectEventType::Motion); + + let second = stream.next().await.unwrap().unwrap(); + assert_eq!(second.item.event_type, ProtectEventType::SmartDetectZone); +} + +#[tokio::test] +async fn test_event_stream_skips_pings_and_ends_on_close() { + let base_url = spawn_ws_server(vec![ + Message::Ping(vec![1, 2, 3].into()), + event_frame("doorbell"), + ]) + .await; + + let client = ProtectClient::new(base_url, "test-key").unwrap(); + let mut stream = client.subscribe_events().await.unwrap(); + + // The ping must be skipped, yielding the doorbell event first. + let first = stream.next().await.unwrap().unwrap(); + assert_eq!(first.item.event_type, ProtectEventType::Doorbell); + + // Server close: a WebSocket error item, then the stream ends. + match stream.next().await { + Some(Err(Error::WebSocket(_))) | None => {} + other => panic!("expected close or end of stream, got {:?}", other.is_some()), + } + assert!(stream.next().await.is_none()); +} + +#[tokio::test] +async fn test_event_stream_surfaces_parse_errors_and_continues() { + let base_url = spawn_ws_server(vec![ + Message::Text("this is not json".to_string().into()), + event_frame("motion"), + ]) + .await; + + let client = ProtectClient::new(base_url, "test-key").unwrap(); + let mut stream = client.subscribe_events().await.unwrap(); + + match stream.next().await { + Some(Err(Error::Parse(_))) => {} + other => panic!("expected parse error, got ok={:?}", other.is_some()), + } + + // The stream must survive a malformed frame. + let next = stream.next().await.unwrap().unwrap(); + assert_eq!(next.item.event_type, ProtectEventType::Motion); +} diff --git a/tests/response_tests.rs b/tests/response_tests.rs index 1986eec..c947e49 100644 --- a/tests/response_tests.rs +++ b/tests/response_tests.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "unifi")] + use rustifi::response::{ApiResponse, PaginatedResponse}; use serde::Deserialize; use serde_json::json; diff --git a/tests/stats_tests.rs b/tests/stats_tests.rs index 568a6f2..650bc5d 100644 --- a/tests/stats_tests.rs +++ b/tests/stats_tests.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "unifi")] + use rustifi::models::{AccessType, Client, ClientAccess, ClientType}; use rustifi::stats::{aggregate_clients_by_device, get_device_client_stats, DeviceClientStats}; diff --git a/tests/types.rs b/tests/types.rs index 9ad3fd3..556dcde 100644 --- a/tests/types.rs +++ b/tests/types.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "unifi")] + use rustifi::models::{IpAddress, MacAddress}; use serde_json::json; use std::net::Ipv4Addr; diff --git a/tests/types_extended.rs b/tests/types_extended.rs index 1fafc12..65f5312 100644 --- a/tests/types_extended.rs +++ b/tests/types_extended.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "unifi")] + use rustifi::models::{AccessType, Client, ClientType}; use serde_json::json;