Skip to main content

fauna_api/
integrations.rs

1use std::ops::Deref;
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use serde_json::{Value, json};
6
7use crate::authentification::Credentials;
8use crate::error::{Error, Result};
9use crate::http::{client, encode, ok};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
12pub enum Platform {
13    #[serde(rename = "GOOGLE")]
14    Google,
15    #[serde(rename = "SLACK")]
16    Slack,
17    #[serde(rename = "DISCORD")]
18    Discord,
19    #[serde(rename = "TWILIO")]
20    Twilio,
21    #[serde(rename = "MICROSOFT")]
22    Microsoft,
23    #[serde(rename = "WHATSAPP")]
24    WhatsApp,
25}
26
27impl Platform {
28    fn as_str(self) -> &'static str {
29        match self {
30            Platform::Google => "GOOGLE",
31            Platform::Slack => "SLACK",
32            Platform::Discord => "DISCORD",
33            Platform::Twilio => "TWILIO",
34            Platform::Microsoft => "MICROSOFT",
35            Platform::WhatsApp => "WHATSAPP",
36        }
37    }
38}
39
40// One linked account on a platform. A user can link several accounts per
41// platform (e.g. two gmails). Tokens stay server-side and are never exposed.
42// The platform structs below carry the platform specific surface (vars, calls).
43#[derive(Debug, Clone)]
44pub struct Account {
45    pub authorization: Credentials,
46
47    pub platform: Platform,
48
49    pub authorized: bool,
50    pub created_at: DateTime<Utc>,
51
52    pub id: String,
53}
54
55impl Account {
56    fn new(authorization: &Credentials, platform: Platform, raw: &Value) -> Self {
57        Account {
58            authorization: authorization.clone(),
59            platform,
60            authorized: raw["authorized"].as_bool().unwrap_or(false),
61            created_at: raw["createdAt"]
62                .as_str()
63                .and_then(|value| DateTime::parse_from_rfc3339(value).ok())
64                .map(|value| value.with_timezone(&Utc))
65                .unwrap_or_default(),
66            id: raw["id"].as_str().unwrap_or_default().to_string(),
67        }
68    }
69
70    pub async fn unlink(&self) -> Result<()> {
71        let response = client()
72            .delete(format!(
73                "{}/integrations/accounts/{}?platform={}",
74                crate::get_url(),
75                encode(&self.id),
76                encode(self.platform.as_str())
77            ))
78            .header(
79                "Authorization",
80                format!("Token {}", self.authorization.token),
81            )
82            .send()
83            .await?;
84        ok(response).await?;
85        Ok(())
86    }
87}
88
89fn strings(raw: &Value, key: &str) -> Vec<String> {
90    raw[key]
91        .as_array()
92        .map(|values| {
93            values
94                .iter()
95                .filter_map(|value| value.as_str().map(str::to_string))
96                .collect()
97        })
98        .unwrap_or_default()
99}
100
101fn string(raw: &Value, key: &str) -> String {
102    raw[key].as_str().unwrap_or_default().to_string()
103}
104
105#[derive(Debug, Clone, Deserialize)]
106#[serde(rename_all = "camelCase")]
107pub struct Demographic {
108    pub age_range: [f64; 2],
109    pub gender: String,
110    pub percentage: f64,
111}
112
113#[derive(Debug, Clone)]
114pub struct Google {
115    account: Account,
116
117    pub email: String,
118    pub scopes: Vec<String>,
119}
120
121impl Google {
122    fn new(authorization: &Credentials, raw: &Value) -> Self {
123        Google {
124            account: Account::new(authorization, Platform::Google, raw),
125            email: string(raw, "email"),
126            scopes: strings(raw, "scopes"),
127        }
128    }
129
130    pub async fn get_demographics(&self) -> Result<Vec<Demographic>> {
131        let response = client()
132            .post(format!(
133                "{}/integrations/google/youtube/demographics",
134                crate::get_url()
135            ))
136            .header(
137                "Authorization",
138                format!("Token {}", self.authorization.token),
139            )
140            .json(&json!({ "accountId": self.id }))
141            .send()
142            .await?;
143        Ok(ok(response).await?.json().await?)
144    }
145}
146
147impl Deref for Google {
148    type Target = Account;
149    fn deref(&self) -> &Account {
150        &self.account
151    }
152}
153
154#[derive(Debug, Clone)]
155pub struct Slack {
156    account: Account,
157
158    pub email: String,
159    pub scopes: Vec<String>,
160}
161
162impl Slack {
163    fn new(authorization: &Credentials, raw: &Value) -> Self {
164        Slack {
165            account: Account::new(authorization, Platform::Slack, raw),
166            email: string(raw, "email"),
167            scopes: strings(raw, "scopes"),
168        }
169    }
170}
171
172impl Deref for Slack {
173    type Target = Account;
174    fn deref(&self) -> &Account {
175        &self.account
176    }
177}
178
179#[derive(Debug, Clone)]
180pub struct Discord {
181    account: Account,
182
183    pub handle: String,
184}
185
186impl Discord {
187    fn new(authorization: &Credentials, raw: &Value) -> Self {
188        Discord {
189            account: Account::new(authorization, Platform::Discord, raw),
190            handle: string(raw, "handle"),
191        }
192    }
193}
194
195impl Deref for Discord {
196    type Target = Account;
197    fn deref(&self) -> &Account {
198        &self.account
199    }
200}
201
202#[derive(Debug, Clone)]
203pub struct Twilio {
204    account: Account,
205
206    pub phone: String,
207}
208
209impl Twilio {
210    fn new(authorization: &Credentials, raw: &Value) -> Self {
211        Twilio {
212            account: Account::new(authorization, Platform::Twilio, raw),
213            phone: string(raw, "phone"),
214        }
215    }
216}
217
218impl Deref for Twilio {
219    type Target = Account;
220    fn deref(&self) -> &Account {
221        &self.account
222    }
223}
224
225#[derive(Debug, Clone)]
226pub struct Microsoft {
227    account: Account,
228
229    pub email: String,
230    pub scopes: Vec<String>,
231}
232
233impl Microsoft {
234    fn new(authorization: &Credentials, raw: &Value) -> Self {
235        Microsoft {
236            account: Account::new(authorization, Platform::Microsoft, raw),
237            email: string(raw, "email"),
238            scopes: strings(raw, "scopes"),
239        }
240    }
241}
242
243impl Deref for Microsoft {
244    type Target = Account;
245    fn deref(&self) -> &Account {
246        &self.account
247    }
248}
249
250#[derive(Debug, Clone)]
251pub struct WhatsApp {
252    account: Account,
253
254    pub phone: String,
255}
256
257impl WhatsApp {
258    fn new(authorization: &Credentials, raw: &Value) -> Self {
259        WhatsApp {
260            account: Account::new(authorization, Platform::WhatsApp, raw),
261            phone: string(raw, "phone"),
262        }
263    }
264}
265
266impl Deref for WhatsApp {
267    type Target = Account;
268    fn deref(&self) -> &Account {
269        &self.account
270    }
271}
272
273/// The `Account` subclass instances `getAccounts` returns in the TypeScript SDK.
274#[derive(Debug, Clone)]
275pub enum PlatformAccount {
276    Google(Google),
277    Slack(Slack),
278    Discord(Discord),
279    Twilio(Twilio),
280    Microsoft(Microsoft),
281    WhatsApp(WhatsApp),
282}
283
284impl Deref for PlatformAccount {
285    type Target = Account;
286    fn deref(&self) -> &Account {
287        match self {
288            PlatformAccount::Google(account) => account,
289            PlatformAccount::Slack(account) => account,
290            PlatformAccount::Discord(account) => account,
291            PlatformAccount::Twilio(account) => account,
292            PlatformAccount::Microsoft(account) => account,
293            PlatformAccount::WhatsApp(account) => account,
294        }
295    }
296}
297
298fn wrap_account(authorization: &Credentials, platform: Platform, raw: &Value) -> PlatformAccount {
299    match platform {
300        Platform::Google => PlatformAccount::Google(Google::new(authorization, raw)),
301        Platform::Slack => PlatformAccount::Slack(Slack::new(authorization, raw)),
302        Platform::Discord => PlatformAccount::Discord(Discord::new(authorization, raw)),
303        Platform::Twilio => PlatformAccount::Twilio(Twilio::new(authorization, raw)),
304        Platform::Microsoft => PlatformAccount::Microsoft(Microsoft::new(authorization, raw)),
305        Platform::WhatsApp => PlatformAccount::WhatsApp(WhatsApp::new(authorization, raw)),
306    }
307}
308
309/// Returns the provider consent URL to open.
310pub async fn link_platform(credentials: &Credentials, integration: Platform) -> Result<String> {
311    let response = client()
312        .post(format!("{}/integrations/link", crate::get_url()))
313        .header("Authorization", format!("Token {}", credentials.token))
314        .json(&json!({ "integration": integration }))
315        .send()
316        .await?;
317    let value: Value = ok(response).await?.json().await?;
318    value["url"]
319        .as_str()
320        .map(str::to_string)
321        .ok_or_else(|| Error::Message("Invalid link response.".into()))
322}
323
324pub async fn get_accounts(credentials: &Credentials) -> Result<Vec<PlatformAccount>> {
325    let response = client()
326        .get(format!("{}/integrations/accounts", crate::get_url()))
327        .header("Authorization", format!("Token {}", credentials.token))
328        .send()
329        .await?;
330    let json: Vec<Value> = ok(response).await?.json().await?;
331
332    Ok(json
333        .iter()
334        .filter_map(|raw| {
335            let platform: Platform = serde_json::from_value(raw["platform"].clone()).ok()?;
336            Some(wrap_account(credentials, platform, raw))
337        })
338        .collect())
339}