use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::billing::PageQuery;
use crate::error::{Error, Result};
use crate::groups::Group;
use crate::http::{client, encode, ok};
use crate::integrations::Platform;
use crate::tickets::parse_date;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Credentials {
pub token: Token,
pub email_verified: bool,
pub phone_verified: bool,
pub permissions: Vec<String>,
pub integrations: Vec<Platform>,
pub email: String,
pub phone: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
pub api_keys: Vec<ApiKey>,
pub balance: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum VerificationChannel {
Email,
Phone,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct ApiKey {
pub id: String,
pub balance: f64,
pub services: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
pub type Token = String;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Profile {
pub email: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
}
impl Profile {
pub fn from_json(json: &Value) -> Option<Profile> {
let email = json["email"].as_str().filter(|email| !email.is_empty())?;
Some(Profile {
email: email.to_string(),
display_name: json["displayName"].as_str().map(str::to_string),
icon: json["icon"].as_str().map(str::to_string),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
pub id: String,
pub current: bool,
pub agent: String,
pub created: DateTime<Utc>,
pub expires: DateTime<Utc>,
}
impl Session {
pub fn from_json(json: &Value) -> Session {
Session {
id: match &json["id"] {
Value::String(id) => id.clone(),
id => id.to_string(),
},
current: json["current"].as_bool() == Some(true),
agent: json["agent"].as_str().unwrap_or_default().to_string(),
created: parse_date(&json["created"]).unwrap_or_default(),
expires: parse_date(&json["expires"]).unwrap_or_default(),
}
}
}
#[derive(Debug, Clone)]
pub enum CredentialsOrApiKey {
Credentials(Credentials),
ApiKey(ApiKey),
}
#[derive(Debug, Clone)]
pub enum ApiKeyOrGroup {
ApiKey(ApiKey),
Group(Group),
}
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PartialCredentials {
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct PartialApiKey {
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub balance: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub services: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PartialProfile {
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
}
pub async fn authorize(email: &str, password: &str) -> Result<Token> {
let response = client()
.post(format!("{}/authentification/authorize", crate::get_url()))
.json(&json!({ "email": email, "password": password }))
.send()
.await?;
Ok(ok(response).await?.text().await?)
}
pub async fn authorize_token(token: &str) -> Result<Credentials> {
let response = client()
.post(format!("{}/authentification/authorize", crate::get_url()))
.header("Authorization", format!("Token {token}"))
.send()
.await?;
let mut credentials: Credentials = ok(response).await?.json().await?;
credentials.token = token.to_string();
Ok(credentials)
}
pub async fn authorize_api_key(api_key: &str) -> Result<ApiKey> {
let response = client()
.post(format!("{}/authentification/authorize", crate::get_url()))
.header("Authorization", format!("ApiKey {api_key}"))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn create(
email: &str,
password: &str,
phone: &str,
display_name: Option<&str>,
) -> Result<bool> {
let response = client()
.post(format!("{}/authentification/create", crate::get_url()))
.json(&json!({
"email": email,
"password": password,
"phone": phone,
"displayName": display_name,
}))
.send()
.await?;
ok(response).await?;
Ok(true)
}
pub async fn edit(credentials: &Credentials, update: &PartialCredentials) -> Result<bool> {
let response = client()
.patch(format!("{}/authentification", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(update)
.send()
.await?;
ok(response).await?;
Ok(true)
}
pub async fn verify(channel: VerificationChannel, target: &str, code: &str) -> Result<bool> {
let response = client()
.post(format!("{}/authentification/verify", crate::get_url()))
.json(&json!({ "channel": channel, "target": target, "code": code }))
.send()
.await?;
ok(response).await?;
Ok(true)
}
pub async fn send_verification(
credentials: &Credentials,
channel: VerificationChannel,
) -> Result<bool> {
let response = client()
.post(format!(
"{}/authentification/send-verification",
crate::get_url()
))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "channel": channel }))
.send()
.await?;
ok(response).await?;
Ok(true)
}
pub async fn forgot_password(email: &str) -> Result<bool> {
let response = client()
.post(format!(
"{}/authentification/password/forgot",
crate::get_url()
))
.json(&json!({ "email": email }))
.send()
.await?;
ok(response).await?;
Ok(true)
}
pub async fn reset_password(email: &str, code: &str, password: &str) -> Result<bool> {
let response = client()
.post(format!(
"{}/authentification/password/reset",
crate::get_url()
))
.json(&json!({ "email": email, "code": code, "password": password }))
.send()
.await?;
ok(response).await?;
Ok(true)
}
pub async fn change_password(
credentials: &Credentials,
current: &str,
password: &str,
) -> Result<bool> {
let response = client()
.post(format!("{}/authentification/password", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "current": current, "password": password }))
.send()
.await?;
ok(response).await?;
Ok(true)
}
pub async fn sessions(credentials: &Credentials, query: PageQuery) -> Result<Vec<Session>> {
let response = client()
.get(format!(
"{}/authentification/sessions?cursor={}&max={}",
crate::get_url(),
query.cursor,
query.max
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
let rows: Vec<Value> = ok(response).await?.json().await?;
Ok(rows.iter().map(Session::from_json).collect())
}
pub async fn revoke_session(credentials: &Credentials, session: &Session) -> Result<bool> {
let response = client()
.delete(format!(
"{}/authentification/sessions/{}",
crate::get_url(),
encode(&session.id)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
ok(response).await?;
Ok(true)
}
pub async fn sign_out(credentials: &Credentials) -> Result<bool> {
let response = client()
.post(format!("{}/authentification/sign-out", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
ok(response).await?;
Ok(true)
}
pub async fn sign_out_everywhere(credentials: &Credentials) -> Result<bool> {
let response = client()
.delete(format!("{}/authentification/sessions", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
ok(response).await?;
Ok(true)
}
pub async fn handoff(credentials: &Credentials) -> Result<String> {
let response = client()
.post(format!("{}/authentification/handoff", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(json["code"].as_str().unwrap_or_default().to_string())
}
pub async fn redeem_handoff(code: &str) -> Result<Token> {
let response = client()
.post(format!(
"{}/authentification/handoff/redeem",
crate::get_url()
))
.json(&json!({ "code": code }))
.send()
.await?;
Ok(ok(response).await?.text().await?)
}
pub async fn allocate_balance(
credentials: &Credentials,
target: &ApiKeyOrGroup,
delta: f64,
) -> Result<bool> {
let delta_micros = (delta * 1_000_000.0).round();
if !delta_micros.is_finite() || delta_micros.abs() > 9_007_199_254_740_991.0 {
return Err(Error::Message("Invalid balance delta.".to_string()));
}
let request = client()
.post(format!(
"{}/authentification/allocate-balance",
crate::get_url()
))
.header("Authorization", format!("Token {}", credentials.token));
let request = match target {
ApiKeyOrGroup::ApiKey(key) => request.header("Api-Key", &key.id),
ApiKeyOrGroup::Group(group) => request.header("Group", &group.id),
};
let response = request
.json(&json!({ "deltaMicros": delta_micros as i64 }))
.send()
.await?;
ok(response).await?;
Ok(true)
}
pub async fn generate_api_key(credentials: &Credentials) -> Result<ApiKey> {
let response = client()
.post(format!("{}/authentification/api-keys", crate::get_url()))
.header("Content-Type", "application/json")
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn remove_api_key(credentials: &Credentials, api_key: &ApiKey) -> Result<bool> {
let response = client()
.delete(format!(
"{}/authentification/api-keys/{}",
crate::get_url(),
encode(&api_key.id)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
ok(response).await?;
Ok(true)
}
pub async fn profile(credentials: &Credentials, email: &str) -> Result<Profile> {
let response = client()
.get(format!(
"{}/authentification/profile/{}",
crate::get_url(),
encode(email)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn query(credentials: &Credentials, profile: &PartialProfile) -> Result<Vec<Profile>> {
let response = client()
.post(format!("{}/authentification/query", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "email": profile.email, "displayName": profile.display_name }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn edit_api_key(
credentials: &Credentials,
api_key: &ApiKey,
update: &PartialApiKey,
) -> Result<bool> {
let response = client()
.patch(format!(
"{}/authentification/api-keys/{}",
crate::get_url(),
encode(&api_key.id)
))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "name": update.name }))
.send()
.await?;
ok(response).await?;
Ok(true)
}