use crate::Client;
use crate::client::api::HiveApi;
use crate::client::api::error::ApiError;
use crate::client::authentication::Tokens;
use crate::helper::url::{Url, get_base_url};
use chrono::{DateTime, Utc, serde::ts_milliseconds};
use reqwest::StatusCode;
use serde::Deserialize;
use serde_json::Value;
use std::collections::HashMap;
use std::fmt;
use std::fmt::{Debug, Formatter};
#[derive(Deserialize, Debug)]
#[non_exhaustive]
#[allow(missing_docs)]
pub struct ActionData {
pub id: String,
pub name: String,
pub enabled: bool,
pub template: String,
#[serde(with = "ts_milliseconds")]
#[serde(rename = "created")]
pub created_at: DateTime<Utc>,
#[serde(flatten)]
#[allow(missing_docs)]
pub extra: HashMap<String, Value>,
}
pub struct Action<'a> {
client: &'a Client,
#[allow(missing_docs)]
pub data: ActionData,
}
impl Debug for Action<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Action").field("data", &self.data).finish()
}
}
impl Action<'_> {
#[must_use]
pub(crate) const fn new(client: &Client, data: ActionData) -> Action<'_> {
Action { client, data }
}
pub async fn activate(&self) -> Result<bool, ApiError> {
self.client.activate_action(&self.data.id).await
}
}
impl HiveApi {
pub(crate) async fn get_actions_data(
&self,
tokens: &Tokens,
) -> Result<Vec<ActionData>, ApiError> {
let response = self
.client
.get(get_base_url(&Url::Actions {
id: None,
activate: false,
}))
.header("Authorization", &tokens.id_token)
.send()
.await;
response?
.json::<Vec<ActionData>>()
.await
.map_err(ApiError::from)
}
pub(crate) async fn activate_action(
&self,
tokens: &Tokens,
action_id: &str,
) -> Result<bool, ApiError> {
let response = self
.client
.post(get_base_url(&Url::Actions {
id: Some(action_id),
activate: true,
}))
.body("{}")
.header("Authorization", &tokens.id_token)
.send()
.await?;
Ok(response.status() == StatusCode::OK)
}
}