use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::authentification::CredentialsOrApiKey;
use crate::error::Result;
use crate::http::{client, ok};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AddressKind {
Email,
Phone,
Discord,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Address {
pub kind: AddressKind,
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Contact {
pub id: String,
pub display_name: String,
#[serde(default)]
pub addresses: Vec<Address>,
#[serde(default)]
pub registered: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Owner {
pub owner: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
pub address: String,
}
impl Owner {
pub fn from_json(json: &Value) -> Owner {
let text = |key: &str| json[key].as_str().unwrap_or_default().to_string();
Owner {
owner: text("owner"),
display_name: crate::tickets::optional(&json["displayName"]),
icon: crate::tickets::optional(&json["icon"]),
address: text("address"),
}
}
}
pub(crate) async fn post(
authorization: &CredentialsOrApiKey,
path: &str,
body: Option<Value>,
) -> Result<reqwest::Response> {
let request = client()
.post(format!("{}{path}", super::get_url()))
.header("Content-Type", "application/json")
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
let request = match body {
Some(body) => request.json(&body),
None => request,
};
ok(request.send().await?).await
}
pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Contact>> {
Ok(post(authorization, "/cicada/contacts", None)
.await?
.json()
.await?)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ContactDraft {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
pub display_name: String,
pub addresses: Vec<Address>,
}
pub async fn save(authorization: &CredentialsOrApiKey, contact: &ContactDraft) -> Result<Contact> {
Ok(post(
authorization,
"/cicada/contacts/save",
Some(serde_json::to_value(contact)?),
)
.await?
.json()
.await?)
}
pub async fn remove(authorization: &CredentialsOrApiKey, id: &str) -> Result<()> {
post(
authorization,
"/cicada/contacts/delete",
Some(json!({ "id": id })),
)
.await?;
Ok(())
}