hive_client/client/api/actions.rs
1use crate::client::api::error::ApiError;
2use crate::client::api::HiveApi;
3use crate::client::authentication::Tokens;
4use crate::helper::url::{get_base_url, Url};
5use crate::Client;
6use chrono::{serde::ts_milliseconds, DateTime, Utc};
7use reqwest::StatusCode;
8use serde::Deserialize;
9use serde_json::Value;
10use std::collections::HashMap;
11use std::fmt;
12use std::fmt::{Debug, Formatter};
13
14#[derive(Deserialize, Debug)]
15#[non_exhaustive]
16#[allow(missing_docs)]
17pub struct ActionData {
18 /// The unique ID of the Quick Action.
19 pub id: String,
20
21 /// The name of the Quick Action.
22 pub name: String,
23
24 /// Whether the Quick Action is enabled or not.
25 pub enabled: bool,
26
27 /// The template used for the Quick Action.
28 pub template: String,
29
30 #[serde(with = "ts_milliseconds")]
31 #[serde(rename = "created")]
32 /// The date and time when the Quick Action was first created.
33 pub created_at: DateTime<Utc>,
34
35 #[serde(flatten)]
36 #[allow(missing_docs)]
37 pub extra: HashMap<String, Value>,
38}
39
40/// A [Quick Action](https://www.hivehome.com/ie/support/Help_Using_Hive/HUH_General/What-are-Quick-Actions) setup in the Hive account.
41pub struct Action<'a> {
42 client: &'a Client,
43
44 #[allow(missing_docs)]
45 pub data: ActionData,
46}
47
48impl Debug for Action<'_> {
49 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
50 f.debug_struct("Action").field("data", &self.data).finish()
51 }
52}
53
54impl Action<'_> {
55 #[must_use]
56 pub(crate) const fn new(client: &Client, data: ActionData) -> Action<'_> {
57 Action { client, data }
58 }
59
60 /// Activate the [Quick Actions](https://www.hivehome.com/ie/support/Help_Using_Hive/HUH_General/What-are-Quick-Actions).
61 ///
62 /// # Examples
63 ///
64 /// ```no_run
65 /// use hive_client::authentication::{TrustedDevice, User};
66 /// # tokio_test::block_on(async {
67 /// let client = hive_client::Client::new("Home Automation");
68 ///
69 /// let trusted_device = Some(TrustedDevice::new(
70 /// "device_password",
71 /// "device_group_key",
72 /// "device_key"
73 /// ));
74 ///
75 /// client.login(User::new("example@example.com", "example"), trusted_device)
76 /// .await
77 /// .expect("Login should succeed");
78 ///
79 /// let actions = client.get_actions()
80 /// .await
81 /// .expect("Quick action should be retrieved");
82 ///
83 /// // Activate a quick action
84 /// let mut turn_off_heating = actions.into_iter()
85 /// .find(|action| action.data.id == "1234-5678-000-0000")
86 /// .expect("Quick action to turn off heating should exist");
87 ///
88 /// let activated = turn_off_heating.activate().await;
89 ///
90 /// assert!(activated.is_ok());
91 /// # })
92 /// ```
93 ///
94 /// # Errors
95 ///
96 /// Returns an error if the [Quick Actions](https://www.hivehome.com/ie/support/Help_Using_Hive/HUH_General/What-are-Quick-Actions) could not be activated.
97 pub async fn activate(&self) -> Result<bool, ApiError> {
98 self.client.activate_action(&self.data.id).await
99 }
100}
101
102impl HiveApi {
103 pub(crate) async fn get_actions_data(
104 &self,
105 tokens: &Tokens,
106 ) -> Result<Vec<ActionData>, ApiError> {
107 let response = self
108 .client
109 .get(get_base_url(&Url::Actions {
110 id: None,
111 activate: false,
112 }))
113 .header("Authorization", &tokens.id_token)
114 .send()
115 .await;
116
117 response?
118 .json::<Vec<ActionData>>()
119 .await
120 .map_err(ApiError::from)
121 }
122
123 pub(crate) async fn activate_action(
124 &self,
125 tokens: &Tokens,
126 action_id: &str,
127 ) -> Result<bool, ApiError> {
128 let response = self
129 .client
130 .post(get_base_url(&Url::Actions {
131 id: Some(action_id),
132 activate: true,
133 }))
134 .body("{}")
135 .header("Authorization", &tokens.id_token)
136 .send()
137 .await?;
138
139 Ok(response.status() == StatusCode::OK)
140 }
141}