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::billing::PageQuery;
9use crate::error::{Error, Result};
10use crate::http::{client, encode, ok};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
13pub enum Platform {
14 #[serde(rename = "GOOGLE")]
15 Google,
16 #[serde(rename = "SLACK")]
17 Slack,
18 #[serde(rename = "DISCORD")]
19 Discord,
20 #[serde(rename = "TWILIO")]
21 Twilio,
22 #[serde(rename = "MICROSOFT")]
23 Microsoft,
24 #[serde(rename = "WHATSAPP")]
25 WhatsApp,
26 #[serde(rename = "GITHUB")]
27 GitHub,
28}
29
30impl Platform {
31 fn as_str(self) -> &'static str {
32 match self {
33 Platform::Google => "GOOGLE",
34 Platform::Slack => "SLACK",
35 Platform::Discord => "DISCORD",
36 Platform::Twilio => "TWILIO",
37 Platform::Microsoft => "MICROSOFT",
38 Platform::WhatsApp => "WHATSAPP",
39 Platform::GitHub => "GITHUB",
40 }
41 }
42}
43
44#[derive(Debug, Clone)]
48pub struct Account {
49 pub authorization: Credentials,
50
51 pub platform: Platform,
52
53 pub authorized: bool,
54 pub created_at: DateTime<Utc>,
55
56 pub id: String,
57}
58
59impl Account {
60 fn new(authorization: &Credentials, platform: Platform, raw: &Value) -> Self {
61 Account {
62 authorization: authorization.clone(),
63 platform,
64 authorized: raw["authorized"].as_bool().unwrap_or(false),
65 created_at: raw["createdAt"]
66 .as_str()
67 .and_then(|value| DateTime::parse_from_rfc3339(value).ok())
68 .map(|value| value.with_timezone(&Utc))
69 .unwrap_or_default(),
70 id: raw["id"].as_str().unwrap_or_default().to_string(),
71 }
72 }
73
74 pub async fn unlink(&self) -> Result<()> {
75 let response = client()
76 .delete(format!(
77 "{}/integrations/accounts/{}?platform={}",
78 crate::get_url(),
79 encode(&self.id),
80 encode(self.platform.as_str())
81 ))
82 .header(
83 "Authorization",
84 format!("Token {}", self.authorization.token),
85 )
86 .send()
87 .await?;
88 ok(response).await?;
89 Ok(())
90 }
91}
92
93fn strings(raw: &Value, key: &str) -> Vec<String> {
94 raw[key]
95 .as_array()
96 .map(|values| {
97 values
98 .iter()
99 .filter_map(|value| value.as_str().map(str::to_string))
100 .collect()
101 })
102 .unwrap_or_default()
103}
104
105fn string(raw: &Value, key: &str) -> String {
106 raw[key].as_str().unwrap_or_default().to_string()
107}
108
109#[derive(Debug, Clone, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub struct Demographic {
112 pub age_range: [f64; 2],
113 pub gender: String,
114 pub percentage: f64,
115}
116
117#[derive(Debug, Clone)]
118pub struct Google {
119 account: Account,
120
121 pub email: String,
122 pub scopes: Vec<String>,
123}
124
125impl Google {
126 fn new(authorization: &Credentials, raw: &Value) -> Self {
127 Google {
128 account: Account::new(authorization, Platform::Google, raw),
129 email: string(raw, "email"),
130 scopes: strings(raw, "scopes"),
131 }
132 }
133
134 pub async fn get_demographics(&self) -> Result<Vec<Demographic>> {
135 let response = client()
136 .post(format!(
137 "{}/integrations/google/youtube/demographics",
138 crate::get_url()
139 ))
140 .header(
141 "Authorization",
142 format!("Token {}", self.authorization.token),
143 )
144 .json(&json!({ "accountId": self.id }))
145 .send()
146 .await?;
147 Ok(ok(response).await?.json().await?)
148 }
149}
150
151impl Deref for Google {
152 type Target = Account;
153 fn deref(&self) -> &Account {
154 &self.account
155 }
156}
157
158#[derive(Debug, Clone)]
159pub struct Slack {
160 account: Account,
161
162 pub email: String,
163 pub scopes: Vec<String>,
164}
165
166impl Slack {
167 fn new(authorization: &Credentials, raw: &Value) -> Self {
168 Slack {
169 account: Account::new(authorization, Platform::Slack, raw),
170 email: string(raw, "email"),
171 scopes: strings(raw, "scopes"),
172 }
173 }
174}
175
176impl Deref for Slack {
177 type Target = Account;
178 fn deref(&self) -> &Account {
179 &self.account
180 }
181}
182
183#[derive(Debug, Clone)]
184pub struct Discord {
185 account: Account,
186
187 pub handle: String,
188}
189
190impl Discord {
191 fn new(authorization: &Credentials, raw: &Value) -> Self {
192 Discord {
193 account: Account::new(authorization, Platform::Discord, raw),
194 handle: string(raw, "handle"),
195 }
196 }
197}
198
199impl Deref for Discord {
200 type Target = Account;
201 fn deref(&self) -> &Account {
202 &self.account
203 }
204}
205
206#[derive(Debug, Clone)]
207pub struct Twilio {
208 account: Account,
209
210 pub phone: String,
211}
212
213impl Twilio {
214 fn new(authorization: &Credentials, raw: &Value) -> Self {
215 Twilio {
216 account: Account::new(authorization, Platform::Twilio, raw),
217 phone: string(raw, "phone"),
218 }
219 }
220}
221
222impl Deref for Twilio {
223 type Target = Account;
224 fn deref(&self) -> &Account {
225 &self.account
226 }
227}
228
229#[derive(Debug, Clone)]
230pub struct Microsoft {
231 account: Account,
232
233 pub email: String,
234 pub scopes: Vec<String>,
235}
236
237impl Microsoft {
238 fn new(authorization: &Credentials, raw: &Value) -> Self {
239 Microsoft {
240 account: Account::new(authorization, Platform::Microsoft, raw),
241 email: string(raw, "email"),
242 scopes: strings(raw, "scopes"),
243 }
244 }
245}
246
247impl Deref for Microsoft {
248 type Target = Account;
249 fn deref(&self) -> &Account {
250 &self.account
251 }
252}
253
254#[derive(Debug, Clone)]
255pub struct WhatsApp {
256 account: Account,
257
258 pub phone: String,
259}
260
261impl WhatsApp {
262 fn new(authorization: &Credentials, raw: &Value) -> Self {
263 WhatsApp {
264 account: Account::new(authorization, Platform::WhatsApp, raw),
265 phone: string(raw, "phone"),
266 }
267 }
268}
269
270impl Deref for WhatsApp {
271 type Target = Account;
272 fn deref(&self) -> &Account {
273 &self.account
274 }
275}
276
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279#[serde(rename_all = "camelCase")]
280pub struct GitHubRepository {
281 pub name: String,
283 pub url: String,
285 pub private: bool,
286 pub branch: String,
288 pub writable: bool,
290}
291
292impl GitHubRepository {
293 pub fn from_json(json: &Value) -> GitHubRepository {
294 GitHubRepository {
295 name: string(json, "name"),
296 url: string(json, "url"),
297 private: json["private"].as_bool() == Some(true),
298 branch: string(json, "branch"),
299 writable: json["writable"].as_bool() == Some(true),
300 }
301 }
302}
303
304#[derive(Debug, Clone)]
308pub struct GitHub {
309 account: Account,
310
311 pub handle: String,
313 pub install_url: String,
315}
316
317impl GitHub {
318 fn new(authorization: &Credentials, raw: &Value) -> Self {
319 GitHub {
320 account: Account::new(authorization, Platform::GitHub, raw),
321 handle: string(raw, "handle"),
322 install_url: string(raw, "installUrl"),
323 }
324 }
325
326 pub async fn repositories(&self, query: PageQuery) -> Result<Vec<GitHubRepository>> {
328 let response = client()
329 .post(format!(
330 "{}/integrations/github/repositories",
331 crate::get_url()
332 ))
333 .header(
334 "Authorization",
335 format!("Token {}", self.authorization.token),
336 )
337 .json(&json!({ "accountId": self.id, "cursor": query.cursor, "max": query.max }))
338 .send()
339 .await?;
340 let json: Value = ok(response).await?.json().await?;
341 Ok(json
342 .as_array()
343 .into_iter()
344 .flatten()
345 .map(GitHubRepository::from_json)
346 .collect())
347 }
348}
349
350impl Deref for GitHub {
351 type Target = Account;
352 fn deref(&self) -> &Account {
353 &self.account
354 }
355}
356
357#[derive(Debug, Clone)]
359pub enum PlatformAccount {
360 Google(Google),
361 Slack(Slack),
362 Discord(Discord),
363 Twilio(Twilio),
364 Microsoft(Microsoft),
365 WhatsApp(WhatsApp),
366 GitHub(GitHub),
367}
368
369impl Deref for PlatformAccount {
370 type Target = Account;
371 fn deref(&self) -> &Account {
372 match self {
373 PlatformAccount::Google(account) => account,
374 PlatformAccount::Slack(account) => account,
375 PlatformAccount::Discord(account) => account,
376 PlatformAccount::Twilio(account) => account,
377 PlatformAccount::Microsoft(account) => account,
378 PlatformAccount::WhatsApp(account) => account,
379 PlatformAccount::GitHub(account) => account,
380 }
381 }
382}
383
384impl PlatformAccount {
385 pub fn from_json(json: &Value, authorization: &Credentials) -> Result<PlatformAccount> {
387 let platform: Platform = serde_json::from_value(json["platform"].clone())
388 .map_err(|_| Error::Message(format!("Unknown platform {}.", json["platform"])))?;
389 Ok(match platform {
390 Platform::Google => PlatformAccount::Google(Google::new(authorization, json)),
391 Platform::Slack => PlatformAccount::Slack(Slack::new(authorization, json)),
392 Platform::Discord => PlatformAccount::Discord(Discord::new(authorization, json)),
393 Platform::Twilio => PlatformAccount::Twilio(Twilio::new(authorization, json)),
394 Platform::Microsoft => PlatformAccount::Microsoft(Microsoft::new(authorization, json)),
395 Platform::WhatsApp => PlatformAccount::WhatsApp(WhatsApp::new(authorization, json)),
396 Platform::GitHub => PlatformAccount::GitHub(GitHub::new(authorization, json)),
397 })
398 }
399}
400
401#[derive(Debug, Clone, PartialEq, Eq)]
403pub struct PlatformBrand {
404 pub id: Platform,
405 pub name: String,
406 pub logo: String,
408}
409
410impl PlatformBrand {
411 pub fn from_json(json: &Value) -> Result<PlatformBrand> {
412 Ok(PlatformBrand {
413 id: serde_json::from_value(json["id"].clone())
414 .map_err(|_| Error::Message(format!("Unknown platform {}.", json["id"])))?,
415 name: string(json, "name"),
416 logo: string(json, "logo"),
417 })
418 }
419}
420
421#[derive(Debug, Clone)]
424pub struct Accounts {
425 pub platforms: Vec<PlatformBrand>,
426 pub accounts: Vec<PlatformAccount>,
427}
428
429impl Accounts {
430 pub fn from_json(json: &Value, authorization: &Credentials) -> Result<Accounts> {
431 let list = |key: &str| json[key].as_array().cloned().unwrap_or_default();
432 Ok(Accounts {
433 platforms: list("platforms")
434 .iter()
435 .map(PlatformBrand::from_json)
436 .collect::<Result<_>>()?,
437 accounts: list("accounts")
438 .iter()
439 .map(|account| PlatformAccount::from_json(account, authorization))
440 .collect::<Result<_>>()?,
441 })
442 }
443}
444
445#[derive(Debug, Clone)]
447pub enum LinkOutcome {
448 Linked(Box<PlatformAccount>),
450 Cancelled,
452 Failed(String),
454}
455
456impl LinkOutcome {
457 pub fn from_json(json: &Value, authorization: &Credentials) -> Result<LinkOutcome> {
458 match json["outcome"].as_str() {
459 Some("linked") => Ok(LinkOutcome::Linked(Box::new(PlatformAccount::from_json(
460 &json["account"],
461 authorization,
462 )?))),
463 Some("cancelled") => Ok(LinkOutcome::Cancelled),
464 Some("failed") => Ok(LinkOutcome::Failed(string(json, "reason"))),
465 _ => Err(Error::Message(format!(
466 "Unknown link outcome {}.",
467 json["outcome"]
468 ))),
469 }
470 }
471}
472
473fn landed_claim(landed: &str, state: &str) -> Option<String> {
476 let landed = reqwest::Url::parse(landed).ok()?;
477 let (landed_state, claim) = landed
478 .fragment()?
479 .strip_prefix("fauna-link=")?
480 .split_once('.')?;
481 (landed_state == state).then(|| claim.to_string())
482}
483
484pub async fn link_platform<F, Fut>(
491 credentials: &Credentials,
492 integration: Platform,
493 return_to: &str,
494 open: F,
495) -> Result<LinkOutcome>
496where
497 F: FnOnce(String) -> Fut,
498 Fut: Future<Output = String>,
499{
500 let response = client()
501 .post(format!("{}/integrations/link", crate::get_url()))
502 .header("Authorization", format!("Token {}", credentials.token))
503 .json(&json!({ "integration": integration, "returnTo": return_to }))
504 .send()
505 .await?;
506 let link: Value = ok(response).await?.json().await?;
507 let (Some(url), Some(state)) = (link["url"].as_str(), link["state"].as_str()) else {
508 return Err(Error::Message("Invalid link response.".into()));
509 };
510 let landed = open(url.to_string()).await;
511 finish_link(credentials, state, landed_claim(&landed, state).as_deref()).await
512}
513
514pub async fn finish_link(
518 credentials: &Credentials,
519 state: &str,
520 claim: Option<&str>,
521) -> Result<LinkOutcome> {
522 let response = client()
523 .post(format!("{}/integrations/link/finish", crate::get_url()))
524 .header("Authorization", format!("Token {}", credentials.token))
525 .json(&json!({ "state": state, "claim": claim }))
526 .send()
527 .await?;
528 let json: Value = ok(response).await?.json().await?;
529 LinkOutcome::from_json(&json, credentials)
530}
531
532pub async fn get_accounts(credentials: &Credentials) -> Result<Accounts> {
534 let response = client()
535 .get(format!("{}/integrations/accounts", crate::get_url()))
536 .header("Authorization", format!("Token {}", credentials.token))
537 .send()
538 .await?;
539 let json: Value = ok(response).await?.json().await?;
540 Accounts::from_json(&json, credentials)
541}
542
543#[cfg(test)]
544mod tests {
545 use super::*;
546
547 #[test]
548 fn reads_the_claim_only_for_its_own_link() {
549 let landed = "https://app.faunakit.com/account?tab=1#fauna-link=abc.claim123";
550 assert_eq!(landed_claim(landed, "abc").as_deref(), Some("claim123"));
551 assert_eq!(landed_claim(landed, "xyz"), None);
552 assert_eq!(
553 landed_claim("https://app.faunakit.com/#fauna-link=abc", "abc"),
554 None
555 );
556 assert_eq!(
557 landed_claim("https://app.faunakit.com/account", "abc"),
558 None
559 );
560 assert_eq!(landed_claim("not a url", "abc"), None);
561 }
562}