fauna-api 1.0.686

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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::authentification::{Credentials, CredentialsOrApiKey, PartialProfile, Profile};
use crate::error::Result;
use crate::http::{client, encode, ok};
use crate::parrot::chat::ChatSummary;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Group {
    pub id: String,

    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,

    #[serde(default)]
    pub balance: f64,

    #[serde(default)]
    pub members: Vec<Profile>,

    pub created_at: DateTime<Utc>,
}

/// A group as someone outside it sees it: no balance, no member list.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GroupSummary {
    pub id: String,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    pub member_count: u32,
}

/// A person found by `query`, with the groups they belong to.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupMatch {
    pub profile: Profile,
    pub groups: Vec<GroupSummary>,
}

/// `Partial<Group>` in the TypeScript SDK.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PartialGroup {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub balance: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub members: Option<Vec<Profile>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum InviteStatus {
    Added,
    Invited,
}

/// What `invite` resolves to: `added` when the email already had a Fauna
/// account, `invited` with the invite token when a pending invite was stored.
#[derive(Debug, Clone, Deserialize)]
pub struct InviteResult {
    pub status: InviteStatus,
    #[serde(default)]
    pub token: Option<String>,
}

/// The `options` argument of `invite`.
#[derive(Debug, Clone, Copy, Default)]
pub struct InviteOptions {
    pub notify: Option<bool>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JoinResult {
    pub group: Group,
    pub already_member: bool,
}

pub async fn create(credentials: &Credentials, name: &str) -> Result<Group> {
    let response = client()
        .post(format!("{}/groups", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "name": name }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Group>> {
    let response = client()
        .get(format!("{}/groups", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// People matching a partial email or name, best first, each with their
/// groups. Only people in at least one group come back.
pub async fn query(
    authorization: &CredentialsOrApiKey,
    profile: &PartialProfile,
) -> Result<Vec<GroupMatch>> {
    let response = client()
        .post(format!("{}/groups/query", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(&json!({ "email": profile.email, "displayName": profile.display_name }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Name, icon and member count of groups by id, including groups you are not
/// in. Unknown ids are left out.
pub async fn summaries(
    authorization: &CredentialsOrApiKey,
    ids: &[String],
) -> Result<Vec<GroupSummary>> {
    let response = client()
        .post(format!("{}/groups/summaries", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(&json!({ "ids": ids }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn get(authorization: &CredentialsOrApiKey, id: &str) -> Result<Group> {
    let response = client()
        .get(format!("{}/groups/{}", crate::get_url(), encode(id)))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn edit(credentials: &Credentials, id: &str, update: &PartialGroup) -> Result<Group> {
    let response = client()
        .patch(format!("{}/groups/{}", crate::get_url(), encode(id)))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "update": update }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Add a user to a group by email. Resolves `added` if they were added directly
/// (they have a Fauna account), or `invited` with a token if a pending invite was
/// stored instead (no Fauna account for that email yet). Fauna emails the invite
/// unless `notify` is false, so an app can send its own email carrying the token.
pub async fn invite(
    credentials: &Credentials,
    id: &str,
    email: &str,
    options: InviteOptions,
) -> Result<InviteResult> {
    let response = client()
        .post(format!("{}/groups/{}/invite", crate::get_url(), encode(id)))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "email": email, "notify": options.notify }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Join the group an email invite points at, using the token from the invite.
pub async fn accept_invite(credentials: &Credentials, token: &str) -> Result<JoinResult> {
    let response = client()
        .post(format!("{}/groups/invites/accept", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "token": token }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn generate_link(credentials: &Credentials, id: &str) -> Result<String> {
    let response = client()
        .post(format!("{}/groups/{}/link", crate::get_url(), encode(id)))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    let json: serde_json::Value = ok(response).await?.json().await?;
    Ok(json["code"].as_str().unwrap_or_default().to_string())
}

pub async fn join(credentials: &Credentials, code: &str) -> Result<JoinResult> {
    let response = client()
        .post(format!("{}/groups/join", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "code": code }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn leave(credentials: &Credentials, id: &str) -> Result<()> {
    let response = client()
        .delete(format!(
            "{}/groups/{}/membership",
            crate::get_url(),
            encode(id)
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}

pub async fn kick(credentials: &Credentials, id: &str, email: &str) -> Result<()> {
    let response = client()
        .delete(format!(
            "{}/groups/{}/members/{}",
            crate::get_url(),
            encode(id),
            encode(email)
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}

/// Two groups with people only chats between them. `group` is the one of yours
/// it was listed for.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Partnership {
    pub id: String,
    pub group: String,
    pub partner: GroupSummary,
    /// Under Hidden: the partner started at no trust while you hide strangers,
    /// and your group hasn't engaged.
    pub hidden: bool,
    #[serde(default)]
    pub chats: Vec<ChatSummary>,
    pub created: DateTime<Utc>,
}

/// The `{ partnership, chat }` `start_partnership_chat` resolves to.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StartedPartnershipChat {
    pub partnership: Partnership,
    pub chat: String,
}

#[derive(Deserialize)]
struct CreatedChat {
    id: String,
}

/// A group's partnerships, each with their chats and what you haven't read. An
/// API key reads them too.
pub async fn list_partnerships(
    authorization: &CredentialsOrApiKey,
    id: &str,
) -> Result<Vec<Partnership>> {
    let response = client()
        .get(format!(
            "{}/groups/{}/partnerships",
            crate::get_url(),
            encode(id)
        ))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Start a chat between your group `id` and `partner`. The first chat partners
/// the groups.
pub async fn start_partnership_chat(
    credentials: &Credentials,
    id: &str,
    partner: &str,
    name: Option<&str>,
) -> Result<StartedPartnershipChat> {
    let response = client()
        .post(format!(
            "{}/groups/{}/partnerships",
            crate::get_url(),
            encode(id)
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "partner": partner, "name": name }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Another chat in a partnership. Resolves to its id.
pub async fn create_partnership_chat(
    credentials: &Credentials,
    partnership: &str,
    name: Option<&str>,
) -> Result<String> {
    let response = client()
        .post(format!(
            "{}/partnerships/{}/chats",
            crate::get_url(),
            encode(partnership)
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "name": name }))
        .send()
        .await?;
    let created: CreatedChat = ok(response).await?.json().await?;
    Ok(created.id)
}

/// Delete a partnership chat, for both groups.
pub async fn delete_partnership_chat(
    credentials: &Credentials,
    partnership: &str,
    chat: &str,
) -> Result<()> {
    let response = client()
        .delete(format!(
            "{}/partnerships/{}/chats/{}",
            crate::get_url(),
            encode(partnership),
            encode(chat)
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}

/// Bring a hidden partnership out of Hidden for your group.
pub async fn show_partnership(credentials: &Credentials, partnership: &str) -> Result<Partnership> {
    let response = client()
        .post(format!(
            "{}/partnerships/{}/show",
            crate::get_url(),
            encode(partnership)
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// End a partnership. Its chats and their files go with it, for both groups.
pub async fn end_partnership(credentials: &Credentials, partnership: &str) -> Result<()> {
    let response = client()
        .delete(format!(
            "{}/partnerships/{}",
            crate::get_url(),
            encode(partnership)
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}