fauna-api 1.0.888

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use std::ops::Deref;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::authentification::Credentials;
use crate::billing::PageQuery;
use crate::error::{Error, Result};
use crate::http::{client, encode, ok};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Platform {
    #[serde(rename = "GOOGLE")]
    Google,
    #[serde(rename = "SLACK")]
    Slack,
    #[serde(rename = "DISCORD")]
    Discord,
    #[serde(rename = "TWILIO")]
    Twilio,
    #[serde(rename = "MICROSOFT")]
    Microsoft,
    #[serde(rename = "WHATSAPP")]
    WhatsApp,
    #[serde(rename = "GITHUB")]
    GitHub,
}

impl Platform {
    fn as_str(self) -> &'static str {
        match self {
            Platform::Google => "GOOGLE",
            Platform::Slack => "SLACK",
            Platform::Discord => "DISCORD",
            Platform::Twilio => "TWILIO",
            Platform::Microsoft => "MICROSOFT",
            Platform::WhatsApp => "WHATSAPP",
            Platform::GitHub => "GITHUB",
        }
    }
}

// One linked account on a platform. A user can link several accounts per
// platform (e.g. two gmails). Tokens stay server-side and are never exposed.
// The platform structs below carry the platform specific surface (vars, calls).
#[derive(Debug, Clone)]
pub struct Account {
    pub authorization: Credentials,

    pub platform: Platform,

    pub authorized: bool,
    pub created_at: DateTime<Utc>,

    pub id: String,
}

impl Account {
    fn new(authorization: &Credentials, platform: Platform, raw: &Value) -> Self {
        Account {
            authorization: authorization.clone(),
            platform,
            authorized: raw["authorized"].as_bool().unwrap_or(false),
            created_at: raw["createdAt"]
                .as_str()
                .and_then(|value| DateTime::parse_from_rfc3339(value).ok())
                .map(|value| value.with_timezone(&Utc))
                .unwrap_or_default(),
            id: raw["id"].as_str().unwrap_or_default().to_string(),
        }
    }

    pub async fn unlink(&self) -> Result<()> {
        let response = client()
            .delete(format!(
                "{}/integrations/accounts/{}?platform={}",
                crate::get_url(),
                encode(&self.id),
                encode(self.platform.as_str())
            ))
            .header(
                "Authorization",
                format!("Token {}", self.authorization.token),
            )
            .send()
            .await?;
        ok(response).await?;
        Ok(())
    }
}

fn strings(raw: &Value, key: &str) -> Vec<String> {
    raw[key]
        .as_array()
        .map(|values| {
            values
                .iter()
                .filter_map(|value| value.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

fn string(raw: &Value, key: &str) -> String {
    raw[key].as_str().unwrap_or_default().to_string()
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Demographic {
    pub age_range: [f64; 2],
    pub gender: String,
    pub percentage: f64,
}

#[derive(Debug, Clone)]
pub struct Google {
    account: Account,

    pub email: String,
    pub scopes: Vec<String>,
}

impl Google {
    fn new(authorization: &Credentials, raw: &Value) -> Self {
        Google {
            account: Account::new(authorization, Platform::Google, raw),
            email: string(raw, "email"),
            scopes: strings(raw, "scopes"),
        }
    }

    pub async fn get_demographics(&self) -> Result<Vec<Demographic>> {
        let response = client()
            .post(format!(
                "{}/integrations/google/youtube/demographics",
                crate::get_url()
            ))
            .header(
                "Authorization",
                format!("Token {}", self.authorization.token),
            )
            .json(&json!({ "accountId": self.id }))
            .send()
            .await?;
        Ok(ok(response).await?.json().await?)
    }
}

impl Deref for Google {
    type Target = Account;
    fn deref(&self) -> &Account {
        &self.account
    }
}

#[derive(Debug, Clone)]
pub struct Slack {
    account: Account,

    pub email: String,
    pub scopes: Vec<String>,
}

impl Slack {
    fn new(authorization: &Credentials, raw: &Value) -> Self {
        Slack {
            account: Account::new(authorization, Platform::Slack, raw),
            email: string(raw, "email"),
            scopes: strings(raw, "scopes"),
        }
    }
}

impl Deref for Slack {
    type Target = Account;
    fn deref(&self) -> &Account {
        &self.account
    }
}

#[derive(Debug, Clone)]
pub struct Discord {
    account: Account,

    pub handle: String,
}

impl Discord {
    fn new(authorization: &Credentials, raw: &Value) -> Self {
        Discord {
            account: Account::new(authorization, Platform::Discord, raw),
            handle: string(raw, "handle"),
        }
    }
}

impl Deref for Discord {
    type Target = Account;
    fn deref(&self) -> &Account {
        &self.account
    }
}

#[derive(Debug, Clone)]
pub struct Twilio {
    account: Account,

    pub phone: String,
}

impl Twilio {
    fn new(authorization: &Credentials, raw: &Value) -> Self {
        Twilio {
            account: Account::new(authorization, Platform::Twilio, raw),
            phone: string(raw, "phone"),
        }
    }
}

impl Deref for Twilio {
    type Target = Account;
    fn deref(&self) -> &Account {
        &self.account
    }
}

#[derive(Debug, Clone)]
pub struct Microsoft {
    account: Account,

    pub email: String,
    pub scopes: Vec<String>,
}

impl Microsoft {
    fn new(authorization: &Credentials, raw: &Value) -> Self {
        Microsoft {
            account: Account::new(authorization, Platform::Microsoft, raw),
            email: string(raw, "email"),
            scopes: strings(raw, "scopes"),
        }
    }
}

impl Deref for Microsoft {
    type Target = Account;
    fn deref(&self) -> &Account {
        &self.account
    }
}

#[derive(Debug, Clone)]
pub struct WhatsApp {
    account: Account,

    pub phone: String,
}

impl WhatsApp {
    fn new(authorization: &Credentials, raw: &Value) -> Self {
        WhatsApp {
            account: Account::new(authorization, Platform::WhatsApp, raw),
            phone: string(raw, "phone"),
        }
    }
}

impl Deref for WhatsApp {
    type Target = Account;
    fn deref(&self) -> &Account {
        &self.account
    }
}

/// A repository on GitHub that a linked account lets Fauna see.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GitHubRepository {
    /// `owner/name`.
    pub name: String,
    /// Its address, `https://github.com/{owner}/{name}`, which `termite::versioning::create` imports.
    pub url: String,
    pub private: bool,
    /// Its default branch.
    pub branch: String,
    /// Whether the account can push to it.
    pub writable: bool,
}

impl GitHubRepository {
    pub fn from_json(json: &Value) -> GitHubRepository {
        GitHubRepository {
            name: string(json, "name"),
            url: string(json, "url"),
            private: json["private"].as_bool() == Some(true),
            branch: string(json, "branch"),
            writable: json["writable"].as_bool() == Some(true),
        }
    }
}

// A linked GitHub account says who the person is on GitHub. The repositories Fauna can see
// are the ones they picked where they installed Fauna's GitHub App (`install_url`), and
// Fauna only ever uses them through a token for one repository at a time.
#[derive(Debug, Clone)]
pub struct GitHub {
    account: Account,

    /// Their GitHub username.
    pub handle: String,
    /// Where they install Fauna's GitHub App and pick the repositories it sees.
    pub install_url: String,
}

impl GitHub {
    fn new(authorization: &Credentials, raw: &Value) -> Self {
        GitHub {
            account: Account::new(authorization, Platform::GitHub, raw),
            handle: string(raw, "handle"),
            install_url: string(raw, "installUrl"),
        }
    }

    /// The repositories this account lets Fauna see, in GitHub's order.
    pub async fn repositories(&self, query: PageQuery) -> Result<Vec<GitHubRepository>> {
        let response = client()
            .post(format!(
                "{}/integrations/github/repositories",
                crate::get_url()
            ))
            .header(
                "Authorization",
                format!("Token {}", self.authorization.token),
            )
            .json(&json!({ "accountId": self.id, "cursor": query.cursor, "max": query.max }))
            .send()
            .await?;
        let json: Value = ok(response).await?.json().await?;
        Ok(json
            .as_array()
            .into_iter()
            .flatten()
            .map(GitHubRepository::from_json)
            .collect())
    }
}

impl Deref for GitHub {
    type Target = Account;
    fn deref(&self) -> &Account {
        &self.account
    }
}

/// The `Account` subclass instances `Account.fromJSON` makes in the TypeScript SDK.
#[derive(Debug, Clone)]
pub enum PlatformAccount {
    Google(Google),
    Slack(Slack),
    Discord(Discord),
    Twilio(Twilio),
    Microsoft(Microsoft),
    WhatsApp(WhatsApp),
    GitHub(GitHub),
}

impl Deref for PlatformAccount {
    type Target = Account;
    fn deref(&self) -> &Account {
        match self {
            PlatformAccount::Google(account) => account,
            PlatformAccount::Slack(account) => account,
            PlatformAccount::Discord(account) => account,
            PlatformAccount::Twilio(account) => account,
            PlatformAccount::Microsoft(account) => account,
            PlatformAccount::WhatsApp(account) => account,
            PlatformAccount::GitHub(account) => account,
        }
    }
}

impl PlatformAccount {
    /// The account as its platform's struct.
    pub fn from_json(json: &Value, authorization: &Credentials) -> Result<PlatformAccount> {
        let platform: Platform = serde_json::from_value(json["platform"].clone())
            .map_err(|_| Error::Message(format!("Unknown platform {}.", json["platform"])))?;
        Ok(match platform {
            Platform::Google => PlatformAccount::Google(Google::new(authorization, json)),
            Platform::Slack => PlatformAccount::Slack(Slack::new(authorization, json)),
            Platform::Discord => PlatformAccount::Discord(Discord::new(authorization, json)),
            Platform::Twilio => PlatformAccount::Twilio(Twilio::new(authorization, json)),
            Platform::Microsoft => PlatformAccount::Microsoft(Microsoft::new(authorization, json)),
            Platform::WhatsApp => PlatformAccount::WhatsApp(WhatsApp::new(authorization, json)),
            Platform::GitHub => PlatformAccount::GitHub(GitHub::new(authorization, json)),
        })
    }
}

/// A platform people link, as Fauna shows it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlatformBrand {
    pub id: Platform,
    pub name: String,
    /// Its logo, a square SVG tile as a data URI.
    pub logo: String,
}

impl PlatformBrand {
    pub fn from_json(json: &Value) -> Result<PlatformBrand> {
        Ok(PlatformBrand {
            id: serde_json::from_value(json["id"].clone())
                .map_err(|_| Error::Message(format!("Unknown platform {}.", json["id"])))?,
            name: string(json, "name"),
            logo: string(json, "logo"),
        })
    }
}

/// Every platform people link, in the order Fauna lists them, and the accounts this person
/// linked.
#[derive(Debug, Clone)]
pub struct Accounts {
    pub platforms: Vec<PlatformBrand>,
    pub accounts: Vec<PlatformAccount>,
}

impl Accounts {
    pub fn from_json(json: &Value, authorization: &Credentials) -> Result<Accounts> {
        let list = |key: &str| json[key].as_array().cloned().unwrap_or_default();
        Ok(Accounts {
            platforms: list("platforms")
                .iter()
                .map(PlatformBrand::from_json)
                .collect::<Result<_>>()?,
            accounts: list("accounts")
                .iter()
                .map(|account| PlatformAccount::from_json(account, authorization))
                .collect::<Result<_>>()?,
        })
    }
}

/// How a link ended.
#[derive(Debug, Clone)]
pub enum LinkOutcome {
    /// The account it linked.
    Linked(Box<PlatformAccount>),
    /// The person turned the provider down, or closed its page before anything came back.
    Cancelled,
    /// Nothing was linked, and why, in words for the person.
    Failed(String),
}

impl LinkOutcome {
    pub fn from_json(json: &Value, authorization: &Credentials) -> Result<LinkOutcome> {
        match json["outcome"].as_str() {
            Some("linked") => Ok(LinkOutcome::Linked(Box::new(PlatformAccount::from_json(
                &json["account"],
                authorization,
            )?))),
            Some("cancelled") => Ok(LinkOutcome::Cancelled),
            Some("failed") => Ok(LinkOutcome::Failed(string(json, "reason"))),
            _ => Err(Error::Message(format!(
                "Unknown link outcome {}.",
                json["outcome"]
            ))),
        }
    }
}

/// The claim a link's popup landed back with, when the URL it landed on carries this link's
/// fragment (`fauna-link={state}.{claim}`).
fn landed_claim(landed: &str, state: &str) -> Option<String> {
    let landed = reqwest::Url::parse(landed).ok()?;
    let (landed_state, claim) = landed
        .fragment()?
        .strip_prefix("fauna-link=")?
        .split_once('.')?;
    (landed_state == state).then(|| claim.to_string())
}

/// Links `integration` and answers how the link ended. `open` gets the page to open (the
/// provider's consent page, or Fauna's own form) and returns the URL the browser landed back on,
/// `return_to` (a page on a site Fauna trusts) with the link's state and, when an account came
/// back, a one time claim in its fragment, which links the account with these credentials
/// (`finish_link`). Whatever lands without the claim links nothing, and a link nothing ended is
/// cancelled.
pub async fn link_platform<F, Fut>(
    credentials: &Credentials,
    integration: Platform,
    return_to: &str,
    open: F,
) -> Result<LinkOutcome>
where
    F: FnOnce(String) -> Fut,
    Fut: Future<Output = String>,
{
    let response = client()
        .post(format!("{}/integrations/link", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "integration": integration, "returnTo": return_to }))
        .send()
        .await?;
    let link: Value = ok(response).await?.json().await?;
    let (Some(url), Some(state)) = (link["url"].as_str(), link["state"].as_str()) else {
        return Err(Error::Message("Invalid link response.".into()));
    };
    let landed = open(url.to_string()).await;
    finish_link(credentials, state, landed_claim(&landed, state).as_deref()).await
}

/// Finishes a link this person started, by its `state`, and returns how it ended, using the
/// state up. With the `claim` its popup landed back with, the account it brought back is
/// linked; without one, nothing it brought back is, and a link nothing ended is cancelled.
pub async fn finish_link(
    credentials: &Credentials,
    state: &str,
    claim: Option<&str>,
) -> Result<LinkOutcome> {
    let response = client()
        .post(format!("{}/integrations/link/finish", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "state": state, "claim": claim }))
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    LinkOutcome::from_json(&json, credentials)
}

/// Every platform people link, with its name and logo, and the accounts this person linked.
pub async fn get_accounts(credentials: &Credentials) -> Result<Accounts> {
    let response = client()
        .get(format!("{}/integrations/accounts", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Accounts::from_json(&json, credentials)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_the_claim_only_for_its_own_link() {
        let landed = "https://app.faunakit.com/account?tab=1#fauna-link=abc.claim123";
        assert_eq!(landed_claim(landed, "abc").as_deref(), Some("claim123"));
        assert_eq!(landed_claim(landed, "xyz"), None);
        assert_eq!(
            landed_claim("https://app.faunakit.com/#fauna-link=abc", "abc"),
            None
        );
        assert_eq!(
            landed_claim("https://app.faunakit.com/account", "abc"),
            None
        );
        assert_eq!(landed_claim("not a url", "abc"), None);
    }
}