fauna-api 1.0.759

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

use super::contacts::{Contact, post};
use crate::authentification::CredentialsOrApiKey;
use crate::drive::{self, DriveAuthorization};
use crate::error::Result;
use crate::http::{deserialize_date, serialize_date};
use crate::integrations::Platform;

/// `Contact | string` in the TypeScript SDK: a known contact, or a bare address.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ContactOrString {
    Contact(Contact),
    String(String),
}

fn inbox_id<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> std::result::Result<Option<String>, D::Error> {
    Ok(match Value::deserialize(deserializer)? {
        Value::Null => None,
        Value::String(id) => Some(id),
        id => Some(id.to_string()),
    })
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Conversation {
    pub id: String,
    #[serde(
        default,
        deserialize_with = "inbox_id",
        skip_serializing_if = "Option::is_none"
    )]
    pub inbox_id: Option<String>,
    #[serde(default)]
    pub participants: Vec<ContactOrString>,
    #[serde(
        deserialize_with = "deserialize_date",
        serialize_with = "serialize_date"
    )]
    pub active_at: DateTime<Utc>,
    #[serde(default)]
    pub unread: u64,
}

/// A conversation paired with the time its reminder is due. Returned by
/// list_reminders; the conversation is otherwise an ordinary inbox thread.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Reminder {
    pub conversation: Conversation,
    #[serde(
        deserialize_with = "deserialize_date",
        serialize_with = "serialize_date"
    )]
    pub remind_at: DateTime<Utc>,
}

/// `'broadcast' | 'group'` in the TypeScript SDK: a separate 1:1 to each
/// recipient, or one shared thread.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SendMode {
    Broadcast,
    Group,
}

/// Where a scheduled send goes: a reply into an existing conversation, or a
/// fresh compose to a set of recipients (hydrated to contacts).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ScheduledContext {
    Conversation {
        conversation: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        platform: Option<Platform>,
    },
    Compose {
        recipients: Vec<ContactOrString>,
        mode: SendMode,
        platform: Platform,
    },
}

/// A queued outbound message the server will dispatch at `send_at`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduledSend {
    pub id: String,
    #[serde(
        deserialize_with = "deserialize_date",
        serialize_with = "serialize_date"
    )]
    pub send_at: DateTime<Utc>,
    #[serde(
        deserialize_with = "deserialize_date",
        serialize_with = "serialize_date"
    )]
    pub created_at: DateTime<Utc>,
    pub message: String,
    pub context: ScheduledContext,
}

#[derive(Debug, Clone)]
pub struct Message {
    pub id: String,
    pub author: ContactOrString,
    pub platform: Platform,
    pub created_at: DateTime<Utc>,
    pub message: String,
    pub raw: Option<String>,
    pub attachments: Vec<drive::File>,
    /// Sent by the inbox agent.
    pub agent: bool,
}

impl Message {
    fn from_json(json: &Value, authorization: &CredentialsOrApiKey) -> Option<Message> {
        Some(Message {
            id: json["id"].as_str().unwrap_or_default().to_string(),
            author: serde_json::from_value(json["author"].clone()).ok()?,
            platform: serde_json::from_value(json["platform"].clone()).ok()?,
            created_at: crate::tickets::parse_date(&json["createdAt"]).unwrap_or_default(),
            message: json["message"].as_str().unwrap_or_default().to_string(),
            raw: json["raw"].as_str().map(str::to_string),
            attachments: json["attachments"]
                .as_array()
                .into_iter()
                .flatten()
                .map(|attachment| {
                    let mut meta = attachment.clone();
                    meta["contentLength"] = attachment["size"].clone();
                    drive::File::from_json(
                        &meta,
                        DriveAuthorization::AccessCode {
                            authorization: authorization.clone(),
                            access_code: attachment["accessCode"]
                                .as_str()
                                .unwrap_or_default()
                                .to_string(),
                        },
                    )
                })
                .collect(),
            agent: json["agent"] == true,
        })
    }
}

fn inbox_body(inbox_id: Option<&str>) -> Value {
    match inbox_id.filter(|id| !id.is_empty()) {
        Some(inbox_id) => json!({ "inboxId": inbox_id }),
        None => json!({}),
    }
}

async fn list_view(
    authorization: &CredentialsOrApiKey,
    path: &str,
    inbox_id: Option<&str>,
) -> Result<Vec<Conversation>> {
    Ok(post(authorization, path, Some(inbox_body(inbox_id)))
        .await?
        .json()
        .await?)
}

/// The inbox working set: everything except archived threads and conversations
/// parked for a future reminder.
pub async fn list_inbox(
    authorization: &CredentialsOrApiKey,
    inbox_id: Option<&str>,
) -> Result<Vec<Conversation>> {
    list_view(authorization, "/cicada/inbox", inbox_id).await
}

/// The archive.
pub async fn list_archived(
    authorization: &CredentialsOrApiKey,
    inbox_id: Option<&str>,
) -> Result<Vec<Conversation>> {
    list_view(authorization, "/cicada/archived", inbox_id).await
}

/// Threads with a pending (future) remind_at, each paired with its due time.
pub async fn list_reminders(
    authorization: &CredentialsOrApiKey,
    inbox_id: Option<&str>,
) -> Result<Vec<Reminder>> {
    Ok(post(
        authorization,
        "/cicada/reminders",
        Some(inbox_body(inbox_id)),
    )
    .await?
    .json()
    .await?)
}

/// Fetch a single conversation's metadata by id (hydrated participants), or None
/// if it no longer exists.
pub async fn get(
    authorization: &CredentialsOrApiKey,
    conversation: &str,
) -> Result<Option<Conversation>> {
    let json: Value = post(
        authorization,
        "/cicada/conversation/get",
        Some(json!({ "conversation": conversation })),
    )
    .await?
    .json()
    .await?;
    Ok(if json.is_null() || json == false {
        None
    } else {
        Some(serde_json::from_value(json)?)
    })
}

pub async fn read(authorization: &CredentialsOrApiKey, conversation: &str) -> Result<Vec<Message>> {
    let json: Value = post(
        authorization,
        "/cicada/conversation",
        Some(json!({ "conversation": conversation })),
    )
    .await?
    .json()
    .await?;
    Ok(json
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|message| Message::from_json(message, authorization))
        .collect())
}

/// Suggest a continuation of an in-progress reply for a conversation. Returns
/// the raw completion text (the part that should follow the current draft); an
/// empty string means no suggestion.
pub async fn autocomplete(
    authorization: &CredentialsOrApiKey,
    conversation: &str,
    text: &str,
) -> Result<String> {
    Ok(post(
        authorization,
        "/cicada/autocomplete",
        Some(json!({ "conversation": conversation, "text": text })),
    )
    .await?
    .text()
    .await?)
}

pub async fn mark_read(authorization: &CredentialsOrApiKey, conversation: &str) -> Result<()> {
    post(
        authorization,
        "/cicada/conversation/mark-read",
        Some(json!({ "conversation": conversation })),
    )
    .await?;
    Ok(())
}

/// Permanently delete a conversation (index entry + stored messages). Backfill
/// won't repopulate it: it only runs on account link, and polling fetches
/// deltas, so old messages never re-arrive.
pub async fn remove(authorization: &CredentialsOrApiKey, conversation: &str) -> Result<()> {
    post(
        authorization,
        "/cicada/conversation/delete",
        Some(json!({ "conversation": conversation })),
    )
    .await?;
    Ok(())
}

/// The `options` argument of `compose`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ComposeOptions {
    pub recipients: Vec<String>,
    pub platform: Platform,
    pub text: String,
    pub mode: SendMode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inbox_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub account_id: Option<String>,
}

/// Start (or append to) conversations with picked contacts on a platform.
/// `recipients` are contact keys (email/handle/phone). `broadcast` sends a
/// separate 1:1 to each; `group` sends one shared thread (collapsing to
/// broadcast on platforms without a real group path). Returns the affected
/// conversation ids: open the first to show the resulting thread.
pub async fn compose(
    authorization: &CredentialsOrApiKey,
    options: &ComposeOptions,
) -> Result<Vec<String>> {
    let json: Value = post(
        authorization,
        "/cicada/compose",
        Some(serde_json::to_value(options)?),
    )
    .await?
    .json()
    .await?;
    Ok(serde_json::from_value(json["conversationIds"].clone()).unwrap_or_default())
}

fn id_of(json: &Value) -> String {
    match &json["id"] {
        Value::String(id) => id.clone(),
        Value::Null => String::new(),
        id => id.to_string(),
    }
}

pub async fn send(
    authorization: &CredentialsOrApiKey,
    conversation: &str,
    text: &str,
    platform: Option<Platform>,
) -> Result<String> {
    let mut body = Map::new();
    body.insert("conversation".to_string(), Value::from(conversation));
    body.insert("text".to_string(), Value::from(text));
    if let Some(platform) = platform {
        body.insert("platform".to_string(), serde_json::to_value(platform)?);
    }
    let json: Value = post(authorization, "/cicada/send", Some(Value::Object(body)))
        .await?
        .json()
        .await?;
    Ok(id_of(&json))
}

/// Move a conversation in/out of the archive.
pub async fn archive(
    authorization: &CredentialsOrApiKey,
    conversation: &str,
    archived: bool,
) -> Result<()> {
    post(
        authorization,
        "/cicada/conversation/archive",
        Some(json!({ "conversation": conversation, "archived": archived })),
    )
    .await?;
    Ok(())
}

/// Set (or clear, with `at = None`) a reminder on a conversation. When the time
/// arrives the server re-surfaces the thread at the top of the inbox.
pub async fn remind(
    authorization: &CredentialsOrApiKey,
    conversation: &str,
    at: Option<DateTime<Utc>>,
) -> Result<()> {
    post(
        authorization,
        "/cicada/conversation/remind",
        Some(json!({
            "conversation": conversation,
            "at": at.map(|at| at.to_rfc3339_opts(SecondsFormat::Millis, true)),
        })),
    )
    .await?;
    Ok(())
}

/// `{ recipients, mode }` in the TypeScript SDK: who a scheduled compose goes to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ComposeTarget {
    pub recipients: Vec<String>,
    pub mode: SendMode,
}

/// The `options` argument of `schedule`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduleOptions {
    #[serde(
        deserialize_with = "deserialize_date",
        serialize_with = "serialize_date"
    )]
    pub send_at: DateTime<Utc>,
    pub text: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub platform: Option<Platform>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub conversation_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compose: Option<ComposeTarget>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inbox_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub account_id: Option<String>,
}

/// Queue an outbound message for later. Provide `conversation_id` to reply into an
/// existing thread, or `compose` to start a fresh one. Returns the queue id.
pub async fn schedule(
    authorization: &CredentialsOrApiKey,
    options: &ScheduleOptions,
) -> Result<String> {
    let json: Value = post(
        authorization,
        "/cicada/schedule",
        Some(serde_json::to_value(options)?),
    )
    .await?
    .json()
    .await?;
    Ok(id_of(&json))
}

pub async fn list_scheduled(
    authorization: &CredentialsOrApiKey,
    inbox_id: Option<&str>,
) -> Result<Vec<ScheduledSend>> {
    Ok(post(
        authorization,
        "/cicada/scheduled/list",
        Some(inbox_body(inbox_id)),
    )
    .await?
    .json()
    .await?)
}

pub async fn cancel_scheduled(authorization: &CredentialsOrApiKey, scheduled: &str) -> Result<()> {
    post(
        authorization,
        "/cicada/scheduled/cancel",
        Some(json!({ "scheduled": scheduled })),
    )
    .await?;
    Ok(())
}