Repository navigation
feat: add UniFi Protect API (protect feature) - #78
Conversation
- New ProtectClient for the official Protect Integration API (/proxy/protect/integration/v1, X-API-Key auth): cameras, lights, sensors, chimes, viewers, NVR, binary JPEG snapshots, and RTSPS stream management - Live WebSocket event subscriptions (subscribe/events and subscribe/devices) exposed as typed futures::Stream - First [features] table: default = ["unifi"], protect is opt-in; shared core (Error, Endpoint trait, common models, transport) stays ungated - Extracted shared HTTP transport used by both clients - wiremock + local-WS + serde round-trip tests; CI feature matrix; protect-events example package BREAKING CHANGE: Error is now #[non_exhaustive] and gained a WebSocket variant. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
|
Warning Review limit reached
Next review available in: 37 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: ⛔ Files ignored due to path filters (2)
📒 Files selected for processing (14)
📝 WalkthroughWalkthroughChangesThe crate now supports optional UniFi Protect REST and WebSocket APIs through a UniFi feature surface
Protect integration
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant ProtectClient
participant ProtectEndpoint
participant ProtectTransport
participant ProtectAPI
ProtectClient->>ProtectEndpoint: construct typed endpoint
ProtectClient->>ProtectTransport: execute endpoint with API key
ProtectTransport->>ProtectAPI: send authenticated REST request
ProtectAPI-->>ProtectTransport: return JSON or binary response
ProtectTransport-->>ProtectClient: deserialize typed result
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Greptile SummaryAdds opt-in UniFi Protect API support while preserving the existing Network API as the default feature.
Confidence Score: 5/5The pull request appears safe to merge because no blocking failure eligible for this follow-up review remains. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| src/protect/client.rs | Adds the primary Protect REST client and convenience methods for device, snapshot, stream, and metadata operations. |
| src/protect/ws.rs | Adds typed event and device-update WebSocket streams with explicit termination and parse-error behavior. |
| src/transport.rs | Centralizes HTTP client construction, endpoint execution, status handling, and JSON response parsing. |
| src/client.rs | Refactors the existing Network client to use the shared transport without changing its public request flow. |
| Cargo.toml | Introduces the default unifi feature and opt-in protect feature with TLS and WebSocket dependencies. |
| src/lib.rs | Applies feature gates to Network and Protect modules and public exports. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart LR
App[Application] -->|unifi feature| UC[UnifiClient]
App -->|protect feature| PC[ProtectClient]
UC --> HT[Shared HTTP transport]
PC --> HT
PC --> WS[Typed WebSocket streams]
HT --> Network[UniFi Network API]
HT --> Protect[Protect Integration API]
WS --> Protect
Reviews (4): Last reviewed commit: "fix: track protect-events example main.r..." | Re-trigger Greptile
There was a problem hiding this comment.
Pull request overview
Adds an opt-in UniFi Protect Integration API client (ProtectClient) behind a new protect cargo feature, while moving existing UniFi Network functionality behind a unifi feature (still enabled by default). This expands the crate to support both controller APIs with a shared HTTP transport layer and updated CI coverage for the feature matrix.
Changes:
- Introduces
ProtectClient(REST + WebSocket subscriptions) plus Protect models/endpoints undersrc/protect/*. - Extracts shared HTTP request/deserialize logic into
src/transport.rsand refactorsUnifiClientto use it. - Adds feature gating (
unifi/protect), updates docs/tests, and expands CI to test multiple feature combinations.
Reviewed changes
Copilot reviewed 40 out of 42 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| tests/types.rs | Gates UniFi Network-related tests behind unifi feature. |
| tests/types_extended.rs | Gates UniFi Network-related tests behind unifi feature. |
| tests/stats_tests.rs | Gates UniFi Network-related tests behind unifi feature. |
| tests/response_tests.rs | Gates UniFi Network-related tests behind unifi feature. |
| tests/pagination_tests.rs | Gates UniFi Network-related tests behind unifi feature. |
| tests/device_tests.rs | Gates UniFi Network-related tests behind unifi feature. |
| tests/protect_ws.rs | Adds Protect WebSocket subscription tests (feature-gated). |
| tests/protect_types.rs | Adds serde-focused Protect model tests (feature-gated). |
| tests/protect_events.rs | Adds typed WebSocket envelope/event parsing tests (feature-gated). |
| tests/protect_client.rs | Adds wiremock-based tests for Protect REST endpoints (feature-gated). |
| src/transport.rs | New shared HTTP transport for endpoint execution/deserialization. |
| src/protect/ws.rs | Adds typed WebSocket stream implementation and subscribe helpers. |
| src/protect/models/viewer.rs | Adds Protect Viewer model + patch type. |
| src/protect/models/sensor.rs | Adds Protect Sensor models + patch types. |
| src/protect/models/nvr.rs | Adds Protect NVR and meta info models. |
| src/protect/models/mod.rs | Exposes Protect models via a central module re-export. |
| src/protect/models/light.rs | Adds Protect Light model + patch type. |
| src/protect/models/event.rs | Adds WebSocket envelope/action/event/device-update models. |
| src/protect/models/common.rs | Adds common Protect enums and a millisecond timestamp type. |
| src/protect/models/chime.rs | Adds Protect Chime model + patch type. |
| src/protect/models/camera.rs | Adds Protect Camera model + patch + RTSPS stream models. |
| src/protect/mod.rs | Adds Protect module entrypoint and prelude exports. |
| src/protect/client.rs | Implements ProtectClient REST methods and snapshot helper. |
| src/protect/api/viewers.rs | Adds Protect Viewer endpoints (get/list/patch). |
| src/protect/api/sensors.rs | Adds Protect Sensor endpoints (get/list/patch). |
| src/protect/api/nvr.rs | Adds Protect NVR endpoint. |
| src/protect/api/mod.rs | Adds Protect API module wiring. |
| src/protect/api/meta.rs | Adds Protect meta/info endpoint. |
| src/protect/api/lights.rs | Adds Protect Light endpoints (get/list/patch). |
| src/protect/api/chimes.rs | Adds Protect Chime endpoints (get/list/patch). |
| src/protect/api/cameras.rs | Adds Protect Camera endpoints + RTSPS stream management. |
| src/models/mod.rs | Gates UniFi Network models behind unifi feature. |
| src/lib.rs | Adds feature-gated module exports for unifi and protect and transport. |
| src/error.rs | Makes Error non-exhaustive and adds WebSocket variant. |
| src/client.rs | Refactors UnifiClient to use shared transport + shared HTTP client builder. |
| src/api/mod.rs | Gates UniFi Network API modules behind unifi feature (keeps endpoint core). |
| README.md | Documents feature flags and adds Protect usage examples. |
| examples/protect-events/Cargo.toml | Adds a Protect events example crate. |
| examples/protect-events/Cargo.lock | Adds lockfile for the new example crate. |
| Cargo.toml | Adds unifi/protect features and optional WS/TLS deps; adds wiremock dev-dep. |
| Cargo.lock | Updates lockfile for new dependencies/features. |
| .github/workflows/ci.yml | Expands CI to test --no-default-features, protect, and --all-features. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
The Stream impl for TypedWsStream<T> only produces T via deserialization and never stores or pins it, so the T: Unpin bound was unnecessary. Use PhantomData<fn() -> T> so the stream stays Unpin and Send regardless of T. Addresses Copilot review comment on PR #78. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (14)
src/protect/models/event.rs (1)
39-49: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
TimestampMillisfor event timestamps.
TimestampMillisexists specifically for Protect event milliseconds, but these fields expose barei64s. This loses unit safety and makes seconds and milliseconds interchangeable.Proposed fix
-use super::common::ModelKey; +use super::common::{ModelKey, TimestampMillis}; ... - pub start: i64, + pub start: TimestampMillis, ... - pub end: Option<i64>, + pub end: Option<TimestampMillis>,As per coding guidelines, "Use strong typing with structs; avoid primitive obsession."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/protect/models/event.rs` around lines 39 - 49, Replace the bare i64 timestamp types in the event model’s start and end fields with the existing TimestampMillis type, preserving end’s optionality and serde defaults. Update the Event struct fields only; leave device and smart_detect_types unchanged.Source: Coding guidelines
src/protect/models/camera.rs (1)
1-3: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valuePlace external imports before internal modules.
src/protect/models/camera.rs#L1-L3: move theserdeimport abovesuperandcrateimports.src/protect/models/chime.rs#L1-L3: move theserdeimport abovesuperandcrateimports.src/protect/models/event.rs#L1-L2: move theserdeimport above thesuperimport.src/protect/models/light.rs#L1-L3: move theserdeimport abovesuperandcrateimports.src/protect/models/nvr.rs#L1-L3: move theserdeimport abovesuperandcrateimports.src/protect/models/sensor.rs#L1-L3: move theserdeimport abovesuperandcrateimports.src/protect/models/viewer.rs#L1-L3: move theserdeimport abovesuperandcrateimports.As per coding guidelines, "Group imports by external crates first, then internal modules."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/protect/models/camera.rs` around lines 1 - 3, Reorder imports so the external serde import precedes internal imports in src/protect/models/camera.rs (lines 1-3), src/protect/models/chime.rs (lines 1-3), src/protect/models/event.rs (lines 1-2), src/protect/models/light.rs (lines 1-3), src/protect/models/nvr.rs (lines 1-3), src/protect/models/sensor.rs (lines 1-3), and src/protect/models/viewer.rs (lines 1-3); keep super and crate imports grouped after serde without changing the imported symbols.Source: Coding guidelines
src/protect/models/mod.rs (1)
1-8: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDocument the remaining public API.
src/protect/models/mod.rs#L1-L8: add module-level docs for the public Protect model modules.src/protect/models/common.rs#L38-L45: documentTimestampMillis::as_millisandTimestampMillis::as_secs, including their precision semantics.src/protect/models/camera.rs#L197-L205: documentRtspsQuality::as_strand its API-value mapping.As per coding guidelines, "Document public API with proper doc comments."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/protect/models/mod.rs` around lines 1 - 8, Document the public Protect model modules declared in src/protect/models/mod.rs. Also add doc comments to TimestampMillis::as_millis and TimestampMillis::as_secs in src/protect/models/common.rs describing their precision semantics, and to RtspsQuality::as_str in src/protect/models/camera.rs describing its API-value mapping.Source: Coding guidelines
src/protect/api/mod.rs (1)
1-7: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDocument the public module exports.
Add doc comments describing each exported API module. As per coding guidelines, “Document public API with proper doc comments.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/protect/api/mod.rs` around lines 1 - 7, Add proper Rust doc comments for each public module export in the API module declaration: cameras, chimes, lights, meta, nvr, sensors, and viewers. Briefly describe the purpose of each module while preserving the existing module exports and visibility.Source: Coding guidelines
src/protect/api/cameras.rs (1)
1-3: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueGroup external imports before crate-local imports.
src/protect/api/cameras.rs#L1-L3: moveserde_json::Valueabovecrateimports.src/protect/api/chimes.rs#L1-L3: moveserde_json::Valueabovecrateimports.src/protect/api/sensors.rs#L1-L3: moveserde_json::Valueabovecrateimports.As per coding guidelines, “Group imports by external crates first, then internal modules.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/protect/api/cameras.rs` around lines 1 - 3, Reorder the imports so the external serde_json::Value import precedes crate-local imports in src/protect/api/cameras.rs lines 1-3, src/protect/api/chimes.rs lines 1-3, and src/protect/api/sensors.rs lines 1-3; make no other changes.Source: Coding guidelines
tests/protect_ws.rs (1)
15-21: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert the WebSocket handshake path and API key.
The server accepts any handshake, so these tests still pass if the client targets the wrong Protect endpoint or omits
X-API-Key. Capture the handshake request and assert the expected path and header.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/protect_ws.rs` around lines 15 - 21, Update the test server handshake handling around tokio_tungstenite::accept_async to capture and inspect the incoming WebSocket HTTP request before accepting it. Assert that the request uses the expected Protect endpoint path and includes the expected X-API-Key header, while preserving the existing frame-sending and close behavior.src/protect/ws.rs (1)
66-69: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUnnecessary
Unpinbound onT.
Tonly appears inPhantomData<T>and as an owned field inside the returnedWsMessage<T>; it's never pinned. TheUnpinbound onTin theStreamimpl is not needed for correctness.♻️ Suggested relaxation
-impl<T> Stream for TypedWsStream<T> -where - T: for<'a> serde::Deserialize<'a> + Unpin, -{ +impl<T> Stream for TypedWsStream<T> +where + T: for<'a> serde::Deserialize<'a>, +{🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/protect/ws.rs` around lines 66 - 69, Remove the unnecessary Unpin bound from T in the Stream implementation for TypedWsStream<T>, while retaining the Deserialize bound and existing stream behavior.src/protect/client.rs (2)
128-150: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
snapshot()re-implements auth-header + error-mapping logic instead of reusingtransport.This duplicates the header construction and non-success error mapping already centralized in
transport::execute_endpoint. If auth handling changes there (e.g. additional headers), this path can silently drift out of sync.Consider extracting a small
transporthelper (e.g.build_authenticated_request(http, url, method, api_key)) that bothexecute_endpointandsnapshot()can call, keeping the binary-body handling local to this method.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/protect/client.rs` around lines 128 - 150, Refactor snapshot() to reuse the centralized transport authentication and request-error handling, preferably by extracting a shared authenticated-request helper used by both execute_endpoint and snapshot(). Keep snapshot()’s binary response-body handling local while removing its duplicated API-key header construction and non-success status mapping.
1-19: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueImport grouping violates "external crates first, then internal modules" across all new Protect files. Every new file in this cohort lists
crate::...imports before external crates (reqwest,serde_json,futures/tokio_tungstenite), the opposite of the stated convention.
src/protect/client.rs#L1-L19: moveuse reqwest::Client;above thecrate::...imports.src/protect/api/lights.rs#L1-L3: moveuse serde_json::Value;above thecrate::...imports.src/protect/api/viewers.rs#L1-L3: moveuse serde_json::Value;above thecrate::...imports.src/protect/ws.rs#L24-L35: regroupfutures,std::*, andtokio_tungsteniteimports before thecrate::...imports.As per coding guidelines, "Group imports by external crates first, then internal modules."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/protect/client.rs` around lines 1 - 19, Regroup imports so external crates precede internal modules: in src/protect/client.rs#L1-L19 move reqwest::Client above crate imports; in src/protect/api/lights.rs#L1-L3 and src/protect/api/viewers.rs#L1-L3 move serde_json::Value above crate imports; and in src/protect/ws.rs#L24-L35 place futures, std::*, and tokio_tungstenite imports before crate imports.Source: Coding guidelines
src/protect/api/lights.rs (1)
10-70: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicated Get/GetSingle/Patch endpoint boilerplate across resource files.
lights.rsandviewers.rs(and the same pattern incameras.rs,chimes.rs,sensors.rs) repeat near-identicalGetX/GetXs/PatchXstructs, each overridingbuild_path()and leaving thePATHconstant's{id}placeholder unused/misleading.
src/protect/api/lights.rs#L10-L70: extract a small macro (or generic builder) generating theGetX/GetXs/PatchXendpoint trio from a resource name, eliminating the repeatedbuild_path()overrides and the stalePATHliteral.src/protect/api/viewers.rs#L10-L70: apply the same macro/generic here instead of the hand-written duplicate.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/protect/api/lights.rs` around lines 10 - 70, Extract a shared macro or generic builder for the GetX/GetXs/PatchX endpoint trio, generating resource-specific types, methods, response types, and request bodies without per-endpoint build_path overrides or unused "{id}" PATH literals. Apply it to the endpoint definitions in src/protect/api/lights.rs lines 10-70 and src/protect/api/viewers.rs lines 10-70; both sites require replacement of the duplicated hand-written boilerplate..github/workflows/ci.yml (1)
55-57: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winBuild the standalone Protect example in CI.
The commands in Line 55-57 target the root package and may not compile
examples/protect-events/Cargo.toml. Add an explicitcargo check --manifest-path examples/protect-events/Cargo.toml, or verify that the example is included as a workspace member.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.github/workflows/ci.yml around lines 55 - 57, Update the CI Rust command sequence near the existing cargo build and test steps to explicitly run cargo check with examples/protect-events/Cargo.toml as its manifest, unless that example is already verified as a workspace member. Ensure CI compiles the standalone Protect example in addition to the current root-package checks and tests.src/client.rs (1)
1-4: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winImport order: internal modules precede the external
reqwestcrate.See consolidated comment (shared with src/transport.rs).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/client.rs` around lines 1 - 4, Reorder the imports in src/client.rs so the internal crate modules (Endpoint, Result, and transport) appear before the external reqwest::Client import, matching the project’s import-order convention.Source: Coding guidelines
src/transport.rs (2)
1-1: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winImport grouping violates the repo's import-ordering guideline in both changed files. Internal
crate::*imports are listed before the externalreqwestimport; the guideline requires external crates first, then internal modules.
src/transport.rs#L3-5: reorder touse reqwest::Client;first, then thecrate::api::endpoint/crate::errorimports.src/client.rs#L1-4: reorder touse reqwest::Client;first, then thecrate::api::endpoint/crate::error/crate::transportimports.As per coding guidelines, "Group imports by external crates first, then internal modules."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/transport.rs` at line 1, Reorder imports in the transport module and the client module so the external reqwest::Client import appears before all internal crate imports. Preserve the existing imported symbols and group the crate::api::endpoint, crate::error, and crate::transport imports together afterward.Source: Coding guidelines
3-5: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winImport order: internal modules precede the external
reqwestcrate.See consolidated comment (shared with src/client.rs).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/transport.rs` around lines 3 - 5, Reorder the imports in the transport module so the internal crate imports, including Endpoint, HttpMethod, and Result, remain before the external reqwest::Client import, matching the project’s import-order convention.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@README.md`:
- Around line 99-118: Update the Live events example’s reconnect loop around
client.subscribe_events().await so initial WebSocket subscription failures are
handled without returning from the example. Log the subscription error, sleep
for the existing 5-second interval, and continue retrying; preserve the current
stream-processing and disconnect-retry behavior.
In `@src/protect/api/cameras.rs`:
- Around line 36-38: Centralize URL path-segment encoding and apply it to every
resource ID interpolation in build_path methods: src/protect/api/cameras.rs
lines 36-38, 63-65, 92-94, 119-121, and 151-153; src/protect/api/chimes.rs lines
36-38 and 63-65; and src/protect/api/sensors.rs lines 36-38 and 63-65. Ensure
camera_id, chime_id, and sensor_id each remain a single safely encoded path
segment rather than being formatted directly into routes.
In `@src/transport.rs`:
- Around line 70-87: Update the non-success response branch in the transport
request flow to read and retain the response body before constructing the error,
then include that body alongside the status-derived error details in
crate::error::Error::Request. Preserve the existing success-path parsing and
error behavior, while ensuring API-provided diagnostic content is available to
both UnifiClient and ProtectClient callers.
---
Nitpick comments:
In @.github/workflows/ci.yml:
- Around line 55-57: Update the CI Rust command sequence near the existing cargo
build and test steps to explicitly run cargo check with
examples/protect-events/Cargo.toml as its manifest, unless that example is
already verified as a workspace member. Ensure CI compiles the standalone
Protect example in addition to the current root-package checks and tests.
In `@src/client.rs`:
- Around line 1-4: Reorder the imports in src/client.rs so the internal crate
modules (Endpoint, Result, and transport) appear before the external
reqwest::Client import, matching the project’s import-order convention.
In `@src/protect/api/cameras.rs`:
- Around line 1-3: Reorder the imports so the external serde_json::Value import
precedes crate-local imports in src/protect/api/cameras.rs lines 1-3,
src/protect/api/chimes.rs lines 1-3, and src/protect/api/sensors.rs lines 1-3;
make no other changes.
In `@src/protect/api/lights.rs`:
- Around line 10-70: Extract a shared macro or generic builder for the
GetX/GetXs/PatchX endpoint trio, generating resource-specific types, methods,
response types, and request bodies without per-endpoint build_path overrides or
unused "{id}" PATH literals. Apply it to the endpoint definitions in
src/protect/api/lights.rs lines 10-70 and src/protect/api/viewers.rs lines
10-70; both sites require replacement of the duplicated hand-written
boilerplate.
In `@src/protect/api/mod.rs`:
- Around line 1-7: Add proper Rust doc comments for each public module export in
the API module declaration: cameras, chimes, lights, meta, nvr, sensors, and
viewers. Briefly describe the purpose of each module while preserving the
existing module exports and visibility.
In `@src/protect/client.rs`:
- Around line 128-150: Refactor snapshot() to reuse the centralized transport
authentication and request-error handling, preferably by extracting a shared
authenticated-request helper used by both execute_endpoint and snapshot(). Keep
snapshot()’s binary response-body handling local while removing its duplicated
API-key header construction and non-success status mapping.
- Around line 1-19: Regroup imports so external crates precede internal modules:
in src/protect/client.rs#L1-L19 move reqwest::Client above crate imports; in
src/protect/api/lights.rs#L1-L3 and src/protect/api/viewers.rs#L1-L3 move
serde_json::Value above crate imports; and in src/protect/ws.rs#L24-L35 place
futures, std::*, and tokio_tungstenite imports before crate imports.
In `@src/protect/models/camera.rs`:
- Around line 1-3: Reorder imports so the external serde import precedes
internal imports in src/protect/models/camera.rs (lines 1-3),
src/protect/models/chime.rs (lines 1-3), src/protect/models/event.rs (lines
1-2), src/protect/models/light.rs (lines 1-3), src/protect/models/nvr.rs (lines
1-3), src/protect/models/sensor.rs (lines 1-3), and src/protect/models/viewer.rs
(lines 1-3); keep super and crate imports grouped after serde without changing
the imported symbols.
In `@src/protect/models/event.rs`:
- Around line 39-49: Replace the bare i64 timestamp types in the event model’s
start and end fields with the existing TimestampMillis type, preserving end’s
optionality and serde defaults. Update the Event struct fields only; leave
device and smart_detect_types unchanged.
In `@src/protect/models/mod.rs`:
- Around line 1-8: Document the public Protect model modules declared in
src/protect/models/mod.rs. Also add doc comments to TimestampMillis::as_millis
and TimestampMillis::as_secs in src/protect/models/common.rs describing their
precision semantics, and to RtspsQuality::as_str in src/protect/models/camera.rs
describing its API-value mapping.
In `@src/protect/ws.rs`:
- Around line 66-69: Remove the unnecessary Unpin bound from T in the Stream
implementation for TypedWsStream<T>, while retaining the Deserialize bound and
existing stream behavior.
In `@src/transport.rs`:
- Line 1: Reorder imports in the transport module and the client module so the
external reqwest::Client import appears before all internal crate imports.
Preserve the existing imported symbols and group the crate::api::endpoint,
crate::error, and crate::transport imports together afterward.
- Around line 3-5: Reorder the imports in the transport module so the internal
crate imports, including Endpoint, HttpMethod, and Result, remain before the
external reqwest::Client import, matching the project’s import-order convention.
In `@tests/protect_ws.rs`:
- Around line 15-21: Update the test server handshake handling around
tokio_tungstenite::accept_async to capture and inspect the incoming WebSocket
HTTP request before accepting it. Assert that the request uses the expected
Protect endpoint path and includes the expected X-API-Key header, while
preserving the existing frame-sending and close behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 3507f822-59dd-463a-bd93-83835e72d679
⛔ Files ignored due to path filters (2)
Cargo.lockis excluded by!**/*.lockexamples/protect-events/Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (40)
.github/workflows/ci.ymlCargo.tomlREADME.mdexamples/protect-events/Cargo.tomlsrc/api/mod.rssrc/client.rssrc/error.rssrc/lib.rssrc/models/mod.rssrc/protect/api/cameras.rssrc/protect/api/chimes.rssrc/protect/api/lights.rssrc/protect/api/meta.rssrc/protect/api/mod.rssrc/protect/api/nvr.rssrc/protect/api/sensors.rssrc/protect/api/viewers.rssrc/protect/client.rssrc/protect/mod.rssrc/protect/models/camera.rssrc/protect/models/chime.rssrc/protect/models/common.rssrc/protect/models/event.rssrc/protect/models/light.rssrc/protect/models/mod.rssrc/protect/models/nvr.rssrc/protect/models/sensor.rssrc/protect/models/viewer.rssrc/protect/ws.rssrc/transport.rstests/device_tests.rstests/pagination_tests.rstests/protect_client.rstests/protect_events.rstests/protect_types.rstests/protect_ws.rstests/response_tests.rstests/stats_tests.rstests/types.rstests/types_extended.rs
- Percent-encode resource IDs used as URL path segments so an ID cannot alter the requested route or query (CodeRabbit) - Preserve error response bodies in a new Error::Api variant instead of discarding them via error_for_status (CodeRabbit) - Handle initial WebSocket subscription failures in the reconnect loops in README and the protect-events example (CodeRabbit) - Regression tests for both client behaviors Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f709377e23
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
The root .gitignore has a blanket main.rs entry, which silently excluded the example's entrypoint from the previous commits. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Summary
Adds support for the official UniFi Protect Integration API (Protect >= 5.3) behind a new opt-in
protectcargo feature, with the existing Network API moving behind aunififeature that remains indefault.ProtectClienttargeting/proxy/protect/integration/v1with the sameX-API-Keyauth as the Network client: cameras (list/get/patch), binary JPEG snapshots, RTSPS stream get/create/delete, lights, sensors, chimes, viewers, NVR, andmeta/info.subscribe_events()andsubscribe_device_updates()return typedfutures::Streams over{"type", "item"}envelopes. No auto-reconnect by design (the API has no replay cursor); the reconnect idiom is documented.src/transport.rs) extracted fromUnifiClientso both clients share request/deserialize behavior.[features]table:default = ["unifi"]; shared core (Error, Endpoint trait, common models) stays ungated. CI now tests the feature matrix.Erroris now#[non_exhaustive]and gained aWebSocket(String)variant (declared viaBREAKING CHANGEfooter → release-plz will cut 2.0.0).examples/protect-events/package; README Protect section.Needs live-console verification (non-blocking)
GET /nvrsresponse shape (modeled as a single object)?qualities=query params)Test plan
cargo build/test/clippy/fmt --checkacross default,--no-default-features,--no-default-features --features protect,--all-featurescargo test --doc --all-features(23 doctests)examples/protect-eventsbuilds🤖 Generated with Claude Code
Summary by CodeRabbit