rusteero 2.0.0

Async Rust client for the Eero (Amazon) mesh Wi-Fi cloud API — a port of the Python eero-api library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Schedule API: `eero-api`'s `ScheduleAPI` at v8.0.4.
//!
//! Ported from `eero-api src/eero/api/schedule.py`. Scheduled pauses are sub-resources of a
//! profile, not a field on the profile itself: they live at
//! `networks/{id}/profiles/{profile}/schedules`, are created with a `POST` to that collection,
//! and are updated/deleted through their own URL — replacing the pre-v8 design of writing a
//! `schedule` array directly onto the profile (`get_profile_schedule`/`set_profile_schedule`,
//! both removed; see `routes::schedule`'s module docs).
//!
//! None of the writes in this module have been verified against a live network. Each logs a
//! [`crate::links::warn_uncharacterised_write`] before the request; follow the
//! read-compare-skip discipline documented there.

use std::sync::Arc;

use serde_json::{Value, json};
use url::Url;

use crate::envelope::Envelope;
use crate::error::Error;
use crate::links;
use crate::routes::{self, Resource};
use crate::transport::{RequestBody, Transport};

/// All seven days, spelled exactly as `eero-api`'s bedtime helpers do (`schedule.py:34-42`), in
/// the order [`ScheduleApi::enable_bedtime`]'s own default uses.
const ALL_DAYS: &[&str] = &[
    "monday",
    "tuesday",
    "wednesday",
    "thursday",
    "friday",
    "saturday",
    "sunday",
];

/// Monday through Friday, verbatim from `eero-api src/eero/api/schedule.py:44`
/// (`ScheduleAPI.set_weekday_bedtime`'s `WEEKDAYS` tuple).
const WEEKDAYS: &[&str] = &["monday", "tuesday", "wednesday", "thursday", "friday"];

/// Saturday and Sunday, verbatim from `eero-api src/eero/api/schedule.py:45`
/// (`ScheduleAPI.set_weekend_bedtime`'s `WEEKEND` tuple).
const WEEKEND: &[&str] = &["saturday", "sunday"];

/// Every optional keyword argument [`ScheduleApi::update_schedule`] accepts.
///
/// More than four optional keyword arguments, per this port's conventions
/// (`.claude/tasks/briefs/v8/phase-g-rules.md` item 2). Ported from `ScheduleAPI.update_schedule`'s
/// own five independent keyword-only fields (`schedule.py:194-202`).
#[derive(Debug, Default, Clone)]
pub struct UpdateScheduleOptions<'a> {
    /// The schedule's name. Omitted from the request when `None`.
    pub name: Option<&'a str>,
    /// The days the schedule applies to. Omitted from the request when `None`.
    pub days: Option<&'a [&'a str]>,
    /// The schedule's start time. Omitted from the request when `None`.
    pub start: Option<&'a str>,
    /// The schedule's end time. Omitted from the request when `None`.
    pub end: Option<&'a str>,
    /// Whether the schedule is enabled. Omitted from the request when `None`.
    pub enabled: Option<bool>,
}

/// `eero-api`'s `ScheduleAPI` (`src/eero/api/schedule.py`) at v8.0.4.
#[derive(Debug)]
pub struct ScheduleApi {
    transport: Arc<Transport>,
}

impl ScheduleApi {
    /// Wraps `transport` as a `ScheduleApi`.
    #[must_use]
    pub fn new(transport: Arc<Transport>) -> Self {
        Self { transport }
    }

    /// Resolves a single scheduled pause's request URL.
    ///
    /// Ported from `_resolve_schedule_url` (`schedule.py:48-74`), which takes one argument that
    /// is *either* a cached pause envelope *or* an id/path/URL string — decomposed here into two
    /// Rust parameters per this port's id-or-url-plus-parent convention
    /// (`.claude/tasks/briefs/v8/phase-g-rules.md` item 2). The two are mutually exclusive, not a
    /// preference-with-fallback: when `parent` is `Some`, `id_or_url` is ignored entirely and
    /// [`links::self_url`] must resolve something, exactly like Python's `Mapping` branch (a
    /// `parent` envelope with no `url` field is a validation error, not a silent fallback to
    /// `id_or_url`); when `parent` is `None`, `id_or_url` is resolved via `route`'s `"{id}"`
    /// template, exactly like Python's `str` branch.
    ///
    /// # Security (finding 2)
    ///
    /// Whichever branch resolves a URL, the result is required to actually name a scheduled
    /// pause — `networks/{id}/profiles/{id}/schedules/{id}` — via
    /// [`crate::params::require_schedule_family`], before it is returned to a caller that is
    /// about to `PUT`/`DELETE` it. Without this, a bare identifier (`"networks"`), an unrelated
    /// same-host path (`"/2.2/networks/1"`), or a *network's* own envelope passed as `parent`
    /// would all resolve to *some* URL via the generic `{id}`-template/`self_url` machinery and
    /// be sent a mutating request without ever being confirmed to be a schedule.
    fn resolve_schedule_url(
        &self,
        route: &Resource,
        id_or_url: &str,
        parent: Option<&Value>,
    ) -> Result<Url, Error> {
        let host = self.transport.api_host();
        let url = if let Some(parent) = parent {
            links::self_url(host, parent)?.ok_or_else(|| {
                Error::validation("schedule", "envelope has no resolvable 'url' field")
            })?
        } else {
            route.resolve(host, id_or_url, None)?
        };
        crate::params::require_schedule_family(&url)
    }

    /// Gets the scheduled pauses for a profile — returns the raw Eero API response.
    ///
    /// Ported from `eero-api src/eero/api/schedule.py:123-150` (`ScheduleAPI.get_schedules`):
    /// sends `GET` `routes::schedule::SCHEDULE_GET_SCHEDULES`
    /// (`networks/{network_id}/profiles/{profile_id}/schedules`), preferring the profile's own
    /// published `schedules` link when `parent` is supplied and resolvable.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Authentication`] if no valid session is configured, [`Error::Validation`]
    /// if the URL cannot be resolved, or whatever status-mapped [`Error`] the request produces.
    pub async fn get_schedules(
        &self,
        network_id: &str,
        profile_id: &str,
        parent: Option<&Value>,
    ) -> Result<Envelope, Error> {
        self.transport
            .nested(
                &routes::schedule::SCHEDULE_GET_SCHEDULES,
                network_id,
                profile_id,
                parent,
                &[],
                RequestBody::None,
            )
            .await
    }

    /// Creates a scheduled pause for a profile — returns the raw Eero API response.
    ///
    /// `enabled` has no Python default here — call with `true` to reproduce
    /// `create_schedule`'s own `enabled: bool = True` default. All five body keys (`name`,
    /// `days`, `start`, `end`, `enabled`) are always sent.
    ///
    /// Ported from `eero-api src/eero/api/schedule.py:152-192` (`ScheduleAPI.create_schedule`):
    /// sends `POST` `routes::schedule::SCHEDULE_CREATE_SCHEDULE` with body `{"name": name, "days":
    /// days, "start": start, "end": end, "enabled": enabled}`. Logs one
    /// `warn_uncharacterised_write("create_schedule")` immediately before the request.
    ///
    /// # Errors
    ///
    /// See [`ScheduleApi::get_schedules`].
    #[allow(clippy::too_many_arguments)] // mirrors schedule.py:152-162's own signature
    pub async fn create_schedule(
        &self,
        network_id: &str,
        profile_id: &str,
        name: &str,
        days: &[&str],
        start: &str,
        end: &str,
        enabled: bool,
        parent: Option<&Value>,
    ) -> Result<Envelope, Error> {
        let url = routes::schedule::SCHEDULE_CREATE_SCHEDULE.resolve(
            self.transport.api_host(),
            network_id,
            profile_id,
            parent,
        )?;
        links::warn_uncharacterised_write("create_schedule");
        self.transport
            .request(
                routes::schedule::SCHEDULE_CREATE_SCHEDULE.method.clone(),
                url,
                &[],
                RequestBody::Json(json!({
                    "name": name,
                    "days": days,
                    "start": start,
                    "end": end,
                    "enabled": enabled,
                })),
            )
            .await
    }

    /// Updates a scheduled pause via its own URL — returns the raw Eero API response.
    ///
    /// Every field is optional; only the supplied ones are sent. See
    /// `resolve_schedule_url` for how `schedule`/`parent` resolve the pause's URL.
    ///
    /// Ported from `eero-api src/eero/api/schedule.py:194-247` (`ScheduleAPI.update_schedule`):
    /// sends `PUT` `routes::schedule::SCHEDULE_UPDATE`. Logs one
    /// `warn_uncharacterised_write("update_schedule")` immediately before the request — but only
    /// once local validation has passed (see the `# Errors` section below), matching Python's own
    /// ordering (`schedule.py:227-246`).
    ///
    /// # Errors
    ///
    /// Returns `Error::Validation { field: "schedule", .. }` if every one of `name`, `days`,
    /// `start`, `end`, `enabled` is `None` — checked *before* any request is sent, matching
    /// Python's own `if not payload: raise ...` (`schedule.py:227-231`). Returns
    /// `Error::Validation { field: "schedule", .. }` if `schedule`/`parent` cannot be resolved to
    /// a URL. Otherwise, [`Error::Authentication`] if no valid session is configured, or whatever
    /// status-mapped [`Error`] the request produces.
    pub async fn update_schedule(
        &self,
        schedule: &str,
        options: &UpdateScheduleOptions<'_>,
        parent: Option<&Value>,
    ) -> Result<Envelope, Error> {
        let mut payload = serde_json::Map::new();
        if let Some(name) = options.name {
            payload.insert("name".to_owned(), Value::String(name.to_owned()));
        }
        if let Some(days) = options.days {
            payload.insert(
                "days".to_owned(),
                Value::Array(
                    days.iter()
                        .map(|d| Value::String((*d).to_owned()))
                        .collect(),
                ),
            );
        }
        if let Some(start) = options.start {
            payload.insert("start".to_owned(), Value::String(start.to_owned()));
        }
        if let Some(end) = options.end {
            payload.insert("end".to_owned(), Value::String(end.to_owned()));
        }
        if let Some(enabled) = options.enabled {
            payload.insert("enabled".to_owned(), Value::Bool(enabled));
        }

        if payload.is_empty() {
            return Err(Error::validation(
                "schedule",
                "at least one of name, days, start, end, enabled must be supplied",
            ));
        }

        let url =
            self.resolve_schedule_url(&routes::schedule::SCHEDULE_UPDATE, schedule, parent)?;
        links::warn_uncharacterised_write("update_schedule");
        self.transport
            .request(
                routes::schedule::SCHEDULE_UPDATE.method.clone(),
                url,
                &[],
                RequestBody::Json(Value::Object(payload)),
            )
            .await
    }

    /// Deletes a scheduled pause via its own URL — returns the raw Eero API response.
    ///
    /// See `resolve_schedule_url` for how `schedule`/`parent` resolve the pause's
    /// URL.
    ///
    /// Ported from `eero-api src/eero/api/schedule.py:250-270` (`ScheduleAPI.delete_schedule`):
    /// sends `DELETE` `routes::schedule::SCHEDULE_DELETE`. Logs one
    /// `warn_uncharacterised_write("delete_schedule")` immediately before the request.
    ///
    /// # Errors
    ///
    /// Returns `Error::Validation { field: "schedule", .. }` if `schedule`/`parent` cannot be
    /// resolved to a URL. Otherwise, [`Error::Authentication`] if no valid session is configured,
    /// or whatever status-mapped [`Error`] the request produces.
    pub async fn delete_schedule(
        &self,
        schedule: &str,
        parent: Option<&Value>,
    ) -> Result<Envelope, Error> {
        let url =
            self.resolve_schedule_url(&routes::schedule::SCHEDULE_DELETE, schedule, parent)?;
        links::warn_uncharacterised_write("delete_schedule");
        self.transport
            .request(
                routes::schedule::SCHEDULE_DELETE.method.clone(),
                url,
                &[],
                RequestBody::None,
            )
            .await
    }

    /// Deletes every scheduled pause currently set on a profile.
    ///
    /// Issues one read ([`ScheduleApi::get_schedules`]) followed by one `DELETE` per existing
    /// pause. Never retried; a pause that fails to delete aborts every remaining delete and its
    /// error propagates immediately — matching Python's own "not swallowed" behaviour
    /// (`schedule.py:274-317`) exactly.
    ///
    /// Ported from `eero-api src/eero/api/schedule.py:274-317`
    /// (`ScheduleAPI.clear_profile_schedule`). Unlike every other method in this module, returns
    /// `Vec<Envelope>` — one raw response per `DELETE`, in read order — matching Python's own
    /// `List[Dict[str, Any]]` return shape.
    ///
    /// # Errors
    ///
    /// Whatever [`ScheduleApi::get_schedules`] or [`ScheduleApi::delete_schedule`] returns on
    /// failure; a delete failure aborts immediately, leaving any remaining pauses undeleted.
    pub async fn clear_profile_schedule(
        &self,
        network_id: &str,
        profile_id: &str,
        parent: Option<&Value>,
    ) -> Result<Vec<Envelope>, Error> {
        let schedules_response = self.get_schedules(network_id, profile_id, parent).await?;
        let data = schedules_response.data();
        let pauses: &[Value] = data.as_array().map_or(&[], Vec::as_slice);

        let mut results = Vec::with_capacity(pauses.len());
        for pause in pauses {
            // Ported from `delete_schedule(pause)` (`schedule.py:313`): Python passes the pause's
            // own *envelope* (mapping), not a bare URL string, so this goes through the same
            // `parent`-is-`Some` branch of `resolve_schedule_url`/`_resolve_schedule_url` every
            // other caller uses — the placeholder `""` `id_or_url` is never consulted, matching
            // `_resolve_schedule_url`'s `Mapping` branch, which ignores nothing else. This is also
            // what gives an unresolvable pause the *identical* message
            // (`"envelope has no resolvable 'url' field"`, field `"schedule"`) every other
            // resolution failure in this module produces, and the identical treat-empty-as-missing
            // rule ([`links::self_url`]).
            results.push(self.delete_schedule("", Some(pause)).await?);
        }
        Ok(results)
    }

    /// Creates a single bedtime scheduled pause for a profile, scoped to `days` (all seven days
    /// if `None`) — returns the raw Eero API response.
    ///
    /// Built on [`ScheduleApi::create_schedule`] (one pause), not a `schedule` array written onto
    /// the profile.
    ///
    /// Ported from `eero-api src/eero/api/schedule.py:319-368` (`ScheduleAPI.enable_bedtime`).
    ///
    /// # Errors
    ///
    /// See [`ScheduleApi::create_schedule`].
    pub async fn enable_bedtime(
        &self,
        network_id: &str,
        profile_id: &str,
        start_time: &str,
        end_time: &str,
        days: Option<&[&str]>,
        parent: Option<&Value>,
    ) -> Result<Envelope, Error> {
        let days = days.unwrap_or(ALL_DAYS);
        self.create_schedule(
            network_id, profile_id, "Bedtime", days, start_time, end_time, true, parent,
        )
        .await
    }

    /// Sets bedtime for weekdays only (Monday through Friday) — returns the raw Eero API
    /// response.
    ///
    /// Delegates to [`ScheduleApi::enable_bedtime`] with `days` fixed to `["monday", "tuesday",
    /// "wednesday", "thursday", "friday"]`.
    ///
    /// Ported from `eero-api src/eero/api/schedule.py:370-393` (`ScheduleAPI.set_weekday_bedtime`).
    ///
    /// # Errors
    ///
    /// See [`ScheduleApi::create_schedule`].
    pub async fn set_weekday_bedtime(
        &self,
        network_id: &str,
        profile_id: &str,
        start_time: &str,
        end_time: &str,
        parent: Option<&Value>,
    ) -> Result<Envelope, Error> {
        self.enable_bedtime(
            network_id,
            profile_id,
            start_time,
            end_time,
            Some(WEEKDAYS),
            parent,
        )
        .await
    }

    /// Sets bedtime for weekends only (Saturday and Sunday) — returns the raw Eero API response.
    ///
    /// Delegates to [`ScheduleApi::enable_bedtime`] with `days` fixed to `["saturday",
    /// "sunday"]`.
    ///
    /// Ported from `eero-api src/eero/api/schedule.py:395-418` (`ScheduleAPI.set_weekend_bedtime`).
    ///
    /// # Errors
    ///
    /// See [`ScheduleApi::create_schedule`].
    pub async fn set_weekend_bedtime(
        &self,
        network_id: &str,
        profile_id: &str,
        start_time: &str,
        end_time: &str,
        parent: Option<&Value>,
    ) -> Result<Envelope, Error> {
        self.enable_bedtime(
            network_id,
            profile_id,
            start_time,
            end_time,
            Some(WEEKEND),
            parent,
        )
        .await
    }
}