use std::sync::Arc;
use reqwest::Method;
use serde_json::{Value, json};
use url::Url;
use crate::envelope::Envelope;
use crate::error::Error;
use crate::params;
use crate::routes;
use crate::routes::Resource;
use crate::transport::{RequestBody, RequestTimeout, Transport};
#[derive(Debug)]
pub struct DataUsageApi {
transport: Arc<Transport>,
}
impl DataUsageApi {
#[must_use]
pub fn new(transport: Arc<Transport>) -> Self {
Self { transport }
}
#[allow(clippy::too_many_arguments)]
pub async fn get_data_usage(
&self,
network_id: &str,
start: &str,
end: &str,
cadence: &str,
timezone: Option<&str>,
timeout: Option<RequestTimeout>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let cadence = validated_cadence(cadence)?;
self.get_usage(
&routes::data_usage::V8_GET_DATA_USAGE,
network_id,
start,
end,
Some(cadence),
timezone,
timeout,
parent,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn get_breakdown(
&self,
network_id: &str,
start: &str,
end: &str,
cadence: Option<&str>,
timezone: Option<&str>,
timeout: Option<RequestTimeout>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let cadence = validated_cadence_opt(cadence)?;
self.get_usage(
&routes::data_usage::GET_DATA_USAGE_BREAKDOWN,
network_id,
start,
end,
cadence,
timezone,
timeout,
parent,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn get_devices_usage(
&self,
network_id: &str,
start: &str,
end: &str,
cadence: Option<&str>,
timezone: Option<&str>,
profile_id: Option<&str>,
timeout: Option<RequestTimeout>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let cadence = validated_cadence_opt(cadence)?;
let url = self.route_url(
&routes::data_usage::GET_DEVICES_DATA_USAGE,
network_id,
parent,
)?;
let mut query = usage_query(start, end, cadence, timezone);
if let Some(profile_id) = profile_id {
query.push(("profile_id", profile_id.to_owned()));
}
self.transport
.request_with_timeout(Method::GET, url, &query, RequestBody::None, timeout)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn get_device_usage(
&self,
network_id: &str,
device_mac: &str,
start: &str,
end: &str,
cadence: &str,
timezone: Option<&str>,
timeout: Option<RequestTimeout>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
self.get_child_usage(
&routes::data_usage::GET_DEVICES_DATA_USAGE,
network_id,
device_mac,
start,
end,
cadence,
timezone,
timeout,
parent,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn get_eeros_summary(
&self,
network_id: &str,
start: &str,
end: &str,
cadence: &str,
timezone: Option<&str>,
timeout: Option<RequestTimeout>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let cadence = validated_cadence(cadence)?;
self.get_usage(
&routes::data_usage::GET_EEROS_DATA_USAGE_SUMMARY,
network_id,
start,
end,
Some(cadence),
timezone,
timeout,
parent,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn get_eeros_usage(
&self,
network_id: &str,
start: &str,
end: &str,
cadence: &str,
timezone: Option<&str>,
timeout: Option<RequestTimeout>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let cadence = validated_cadence(cadence)?;
self.get_usage(
&routes::data_usage::GET_EEROS_DATA_USAGE,
network_id,
start,
end,
Some(cadence),
timezone,
timeout,
parent,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn get_eero_usage(
&self,
network_id: &str,
eero_id: &str,
start: &str,
end: &str,
cadence: &str,
timezone: Option<&str>,
timeout: Option<RequestTimeout>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
self.get_child_usage(
&routes::data_usage::GET_EEROS_DATA_USAGE,
network_id,
eero_id,
start,
end,
cadence,
timezone,
timeout,
parent,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn get_profile_usage(
&self,
network_id: &str,
profile_id: &str,
start: &str,
end: &str,
cadence: &str,
timezone: Option<&str>,
timeout: Option<RequestTimeout>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
self.get_child_usage(
&routes::data_usage::GET_PROFILES_DATA_USAGE,
network_id,
profile_id,
start,
end,
cadence,
timezone,
timeout,
parent,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn get_unprofiled_devices(
&self,
network_id: &str,
start: &str,
end: &str,
cadence: Option<&str>,
timezone: Option<&str>,
timeout: Option<RequestTimeout>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let cadence = validated_cadence_opt(cadence)?;
self.get_usage(
&routes::data_usage::GET_UNPROFILED_DEVICES_DATA_USAGE,
network_id,
start,
end,
cadence,
timezone,
timeout,
parent,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn get_unprofiled_summary(
&self,
network_id: &str,
start: &str,
end: &str,
cadence: &str,
timezone: Option<&str>,
timeout: Option<RequestTimeout>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let cadence = validated_cadence(cadence)?;
self.get_usage(
&routes::data_usage::GET_UNPROFILED_DATA_USAGE_SUMMARY,
network_id,
start,
end,
Some(cadence),
timezone,
timeout,
parent,
)
.await
}
pub async fn get_report_settings(
&self,
network_id: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let url = self.route_url(
&routes::data_usage::GET_DATA_USAGE_REPORT_SETTINGS,
network_id,
parent,
)?;
self.transport
.request(Method::GET, url, &[], RequestBody::None)
.await
}
pub async fn set_report_settings(
&self,
network_id: &str,
cadence: &str,
notification_day: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let cadence = validated_cadence(cadence)?;
let url = self.route_url(
&routes::data_usage::SET_DATA_USAGE_REPORT_SETTINGS,
network_id,
parent,
)?;
crate::links::warn_uncharacterised_write("set data usage report settings for network");
self.transport
.request(
Method::PUT,
url,
&[],
RequestBody::Json(json!({
"cadence": cadence,
"notification_day": notification_day,
})),
)
.await
}
#[allow(clippy::too_many_arguments)]
async fn get_usage(
&self,
route: &Resource,
network_id: &str,
start: &str,
end: &str,
cadence: Option<&str>,
timezone: Option<&str>,
timeout: Option<RequestTimeout>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let url = self.route_url(route, network_id, parent)?;
let query = usage_query(start, end, cadence, timezone);
self.transport
.request_with_timeout(Method::GET, url, &query, RequestBody::None, timeout)
.await
}
#[allow(clippy::too_many_arguments)]
async fn get_child_usage(
&self,
route: &Resource,
network_id: &str,
child: &str,
start: &str,
end: &str,
cadence: &str,
timezone: Option<&str>,
timeout: Option<RequestTimeout>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let validated_child = crate::links::validate_identifier(child)?;
let cadence = validated_cadence(cadence)?;
let collection = self.route_url(route, network_id, parent)?;
let url = append_path(&collection, validated_child)?;
let query = usage_query(start, end, Some(cadence), timezone);
self.transport
.request_with_timeout(Method::GET, url, &query, RequestBody::None, timeout)
.await
}
fn route_url(
&self,
route: &Resource,
network_id: &str,
parent: Option<&Value>,
) -> Result<Url, Error> {
let base = params::resolve_network_url(
self.transport.api_host(),
network_id,
parent,
route.version,
)?;
let joined = format!(
"{}{}",
base.as_str().trim_end_matches('/'),
route_suffix(route.template)
);
Url::parse(&joined)
.map_err(|err| Error::validation("url", format!("not a valid URL: {err}")))
}
}
fn route_suffix(template: &str) -> &str {
template.split_once("{id}").map_or("", |(_, suffix)| suffix)
}
fn validated_cadence(cadence: &str) -> Result<&str, Error> {
params::validate_cadence(cadence, params::CADENCE_VALUES)
}
fn validated_cadence_opt(cadence: Option<&str>) -> Result<Option<&str>, Error> {
cadence.map(validated_cadence).transpose()
}
fn usage_query(
start: &str,
end: &str,
cadence: Option<&str>,
timezone: Option<&str>,
) -> Vec<(&'static str, String)> {
let mut query = vec![("start", start.to_owned()), ("end", end.to_owned())];
if let Some(cadence) = cadence {
query.push(("cadence", cadence.to_owned()));
}
if let Some(timezone) = timezone {
query.push(("timezone", timezone.to_owned()));
}
query
}
fn append_path(base: &Url, child: &str) -> Result<Url, Error> {
let joined = format!("{}/{child}", base.as_str().trim_end_matches('/'));
Url::parse(&joined).map_err(|err| Error::validation("url", format!("not a valid URL: {err}")))
}
#[cfg(test)]
mod tests {
use super::route_suffix;
use crate::routes::data_usage as routes;
#[test]
fn route_suffix_is_the_template_text_after_the_id_placeholder() {
for (template, suffix) in [
(routes::V8_GET_DATA_USAGE.template, "/data_usage"),
(
routes::GET_DATA_USAGE_BREAKDOWN.template,
"/data_usage/breakdown",
),
(
routes::GET_DEVICES_DATA_USAGE.template,
"/data_usage/devices",
),
(
routes::GET_EEROS_DATA_USAGE_SUMMARY.template,
"/data_usage/eeros/summary",
),
(routes::GET_EEROS_DATA_USAGE.template, "/data_usage/eeros"),
(
routes::GET_PROFILES_DATA_USAGE.template,
"/data_usage/profiles",
),
(
routes::GET_UNPROFILED_DEVICES_DATA_USAGE.template,
"/data_usage/unprofiled/devices",
),
(
routes::GET_UNPROFILED_DATA_USAGE_SUMMARY.template,
"/data_usage/unprofiled/summary",
),
(
routes::GET_DATA_USAGE_REPORT_SETTINGS.template,
"/data_usage/report_settings",
),
(
routes::SET_DATA_USAGE_REPORT_SETTINGS.template,
"/data_usage/report_settings",
),
] {
assert!(template.starts_with("networks/{id}/"), "{template}");
assert_eq!(route_suffix(template), suffix, "{template}");
}
}
}