Skip to main content

fauna_api/cicada/
contacts.rs

1use serde::{Deserialize, Serialize};
2use serde_json::{Value, json};
3
4use crate::authentification::CredentialsOrApiKey;
5use crate::error::Result;
6use crate::http::{client, ok};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
9#[serde(rename_all = "lowercase")]
10pub enum AddressKind {
11    Email,
12    Phone,
13    Discord,
14}
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17pub struct Address {
18    pub kind: AddressKind,
19    /// Lowercase email, E.164 phone (+12395551234), or Discord handle without @.
20    pub value: String,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct Contact {
26    pub id: String,
27    pub display_name: String,
28    #[serde(default)]
29    pub addresses: Vec<Address>,
30    /// One of its emails belongs to a Fauna account: the verified badge.
31    #[serde(default)]
32    pub registered: bool,
33    /// That Fauna account's picture.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub icon: Option<String>,
36}
37
38/// One of the inbox's owners, behind one of their verified addresses: show "You" when
39/// `owner` is your own email, else their name.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "camelCase")]
42pub struct Owner {
43    /// The owner's email.
44    pub owner: String,
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub display_name: Option<String>,
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub icon: Option<String>,
49    /// The address as it appeared.
50    pub address: String,
51}
52
53impl Owner {
54    pub fn from_json(json: &Value) -> Owner {
55        let text = |key: &str| json[key].as_str().unwrap_or_default().to_string();
56        Owner {
57            owner: text("owner"),
58            display_name: crate::tickets::optional(&json["displayName"]),
59            icon: crate::tickets::optional(&json["icon"]),
60            address: text("address"),
61        }
62    }
63}
64
65pub(crate) async fn post(
66    authorization: &CredentialsOrApiKey,
67    path: &str,
68    body: Option<Value>,
69) -> Result<reqwest::Response> {
70    let request = client()
71        .post(format!("{}{path}", super::get_url()))
72        .header("Content-Type", "application/json")
73        .header(
74            "Authorization",
75            match authorization {
76                CredentialsOrApiKey::Credentials(credentials) => {
77                    format!("Token {}", credentials.token)
78                }
79                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
80            },
81        );
82    let request = match body {
83        Some(body) => request.json(&body),
84        None => request,
85    };
86    ok(request.send().await?).await
87}
88
89/// Every contact, sorted by display name.
90pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Contact>> {
91    Ok(post(authorization, "/cicada/contacts", None)
92        .await?
93        .json()
94        .await?)
95}
96
97/// `{ id?, displayName, addresses }` in the TypeScript SDK.
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100pub struct ContactDraft {
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub id: Option<String>,
103    pub display_name: String,
104    pub addresses: Vec<Address>,
105}
106
107/// Creates a contact, or with `id` renames one and replaces its addresses.
108pub async fn save(authorization: &CredentialsOrApiKey, contact: &ContactDraft) -> Result<Contact> {
109    Ok(post(
110        authorization,
111        "/cicada/contacts/save",
112        Some(serde_json::to_value(contact)?),
113    )
114    .await?
115    .json()
116    .await?)
117}
118
119pub async fn remove(authorization: &CredentialsOrApiKey, id: &str) -> Result<()> {
120    post(
121        authorization,
122        "/cicada/contacts/delete",
123        Some(json!({ "id": id })),
124    )
125    .await?;
126    Ok(())
127}