Skip to main content

fauna_api/cicada/
chats.rs

1use std::ops::Deref;
2
3use chrono::{DateTime, SecondsFormat, Utc};
4use serde::{Deserialize, Serialize};
5use serde_json::{Value, json};
6
7use super::contacts::{Contact, Owner, post};
8use crate::authentification::CredentialsOrApiKey;
9use crate::error::Result;
10use crate::http::{deserialize_date, serialize_date};
11use crate::integrations::Platform;
12use crate::parrot::chat::ChatSummary;
13
14/// `Contact | Owner | string` in the TypeScript SDK: a known contact, one of the inbox's
15/// owners, or a bare address.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(untagged)]
18pub enum ContactOrOwnerOrString {
19    Contact(Contact),
20    Owner(Owner),
21    String(String),
22}
23
24/// A line under one of a chat's messages, by its position: why it never arrived, or that it
25/// waits for an owner's approval.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Note {
28    pub position: u32,
29    pub text: String,
30}
31
32/// `{ platform, name, guildName }` in the TypeScript SDK: the Discord or Slack channel a chat is.
33#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
34#[serde(rename_all = "camelCase")]
35pub struct ChatChannel {
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub platform: Option<Platform>,
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub name: Option<String>,
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub guild_name: Option<String>,
42}
43
44/// One of an inbox's chats: the Parrot chat the inbox owns, with who it's with and how
45/// they're reached. Its messages are the chat's: open its room with `parrot::chat::open_room`
46/// on its id. What the inbox's members and its agent write there goes out to its people.
47#[derive(Debug, Clone)]
48pub struct Chat {
49    pub summary: ChatSummary,
50    pub inbox_id: String,
51    pub participants: Vec<ContactOrOwnerOrString>,
52    /// The Discord or Slack channel it is, when it's one.
53    pub channel: Option<ChatChannel>,
54    /// The platform it's reached on.
55    pub platform: Option<Platform>,
56    pub archived: bool,
57    pub remind_at: Option<DateTime<Utc>>,
58    pub notes: Vec<Note>,
59}
60
61impl Deref for Chat {
62    type Target = ChatSummary;
63
64    fn deref(&self) -> &ChatSummary {
65        &self.summary
66    }
67}
68
69impl Chat {
70    pub fn from_json(json: &Value) -> Chat {
71        Chat {
72            summary: ChatSummary::from_json(json),
73            inbox_id: id_text(&json["inboxId"]),
74            participants: serde_json::from_value(json["participants"].clone()).unwrap_or_default(),
75            channel: serde_json::from_value(json["channel"].clone()).ok(),
76            platform: serde_json::from_value(json["platform"].clone()).ok(),
77            archived: json["archived"] == true,
78            remind_at: crate::tickets::parse_date(&json["remindAt"]),
79            notes: serde_json::from_value(json["notes"].clone()).unwrap_or_default(),
80        }
81    }
82}
83
84/// A chat paired with the time its reminder is due.
85#[derive(Debug, Clone)]
86pub struct Reminder {
87    pub chat: Chat,
88    pub remind_at: DateTime<Utc>,
89}
90
91/// `'broadcast' | 'group'` in the TypeScript SDK: a separate one to each recipient, or one
92/// shared thread.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
94#[serde(rename_all = "lowercase")]
95pub enum SendMode {
96    Broadcast,
97    Group,
98}
99
100/// Where a scheduled send goes: a reply in a chat, or a fresh compose to a set of recipients
101/// (hydrated to contacts).
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103#[serde(untagged)]
104pub enum ScheduledContext {
105    Chat {
106        #[serde(rename = "chatId")]
107        chat_id: String,
108        #[serde(default, skip_serializing_if = "Option::is_none")]
109        platform: Option<Platform>,
110    },
111    Compose {
112        recipients: Vec<ContactOrOwnerOrString>,
113        mode: SendMode,
114        platform: Platform,
115    },
116}
117
118/// A queued outbound message the server sends at `send_at`.
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
120#[serde(rename_all = "camelCase")]
121pub struct ScheduledSend {
122    pub id: String,
123    #[serde(
124        deserialize_with = "deserialize_date",
125        serialize_with = "serialize_date"
126    )]
127    pub send_at: DateTime<Utc>,
128    #[serde(
129        deserialize_with = "deserialize_date",
130        serialize_with = "serialize_date"
131    )]
132    pub created_at: DateTime<Utc>,
133    pub message: String,
134    pub context: ScheduledContext,
135}
136
137/// An id the server sent as a string or a number.
138fn id_text(json: &Value) -> String {
139    match json {
140        Value::String(id) => id.clone(),
141        Value::Null => String::new(),
142        id => id.to_string(),
143    }
144}
145
146fn inbox_body(inbox_id: Option<&str>) -> Value {
147    match inbox_id.filter(|id| !id.is_empty()) {
148        Some(inbox_id) => json!({ "inboxId": inbox_id }),
149        None => json!({}),
150    }
151}
152
153async fn list_view(
154    authorization: &CredentialsOrApiKey,
155    path: &str,
156    inbox_id: Option<&str>,
157) -> Result<Vec<Chat>> {
158    let rows: Vec<Value> = post(authorization, path, Some(inbox_body(inbox_id)))
159        .await?
160        .json()
161        .await?;
162    Ok(rows.iter().map(Chat::from_json).collect())
163}
164
165/// The inbox working set: everything except archived chats and chats parked for a future
166/// reminder.
167pub async fn list_inbox(
168    authorization: &CredentialsOrApiKey,
169    inbox_id: Option<&str>,
170) -> Result<Vec<Chat>> {
171    list_view(authorization, "/cicada/inbox", inbox_id).await
172}
173
174/// The archive.
175pub async fn list_archived(
176    authorization: &CredentialsOrApiKey,
177    inbox_id: Option<&str>,
178) -> Result<Vec<Chat>> {
179    list_view(authorization, "/cicada/archived", inbox_id).await
180}
181
182/// Chats with a future reminder, each with its due time.
183pub async fn list_reminders(
184    authorization: &CredentialsOrApiKey,
185    inbox_id: Option<&str>,
186) -> Result<Vec<Reminder>> {
187    let rows: Vec<Value> = post(
188        authorization,
189        "/cicada/reminders",
190        Some(inbox_body(inbox_id)),
191    )
192    .await?
193    .json()
194    .await?;
195    Ok(rows
196        .iter()
197        .map(|row| Reminder {
198            chat: Chat::from_json(&row["chat"]),
199            remind_at: crate::tickets::parse_date(&row["remindAt"]).unwrap_or_default(),
200        })
201        .collect())
202}
203
204/// One chat, or None once it's gone.
205pub async fn get(authorization: &CredentialsOrApiKey, chat_id: &str) -> Result<Option<Chat>> {
206    let json: Value = post(
207        authorization,
208        "/cicada/chats/get",
209        Some(json!({ "chatId": chat_id })),
210    )
211    .await?
212    .json()
213    .await?;
214    Ok(json.is_object().then(|| Chat::from_json(&json)))
215}
216
217/// Deletes a chat and its messages. A history pull never brings them back.
218pub async fn remove(authorization: &CredentialsOrApiKey, chat_id: &str) -> Result<()> {
219    post(
220        authorization,
221        "/cicada/chats/delete",
222        Some(json!({ "chatId": chat_id })),
223    )
224    .await?;
225    Ok(())
226}
227
228/// The `options` argument of `compose`.
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230#[serde(rename_all = "camelCase")]
231pub struct ComposeOptions {
232    pub recipients: Vec<String>,
233    pub platform: Platform,
234    pub text: String,
235    pub mode: SendMode,
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub inbox_id: Option<String>,
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub account_id: Option<String>,
240}
241
242/// Starts (or appends to) chats with picked contacts on a platform. `recipients` are contact
243/// keys (email, handle or phone). `broadcast` sends a separate one to each; `group` sends one
244/// shared thread (one each on platforms without a real group). Resolves to the chats it wrote
245/// in.
246pub async fn compose(
247    authorization: &CredentialsOrApiKey,
248    options: &ComposeOptions,
249) -> Result<Vec<String>> {
250    let json: Value = post(
251        authorization,
252        "/cicada/compose",
253        Some(serde_json::to_value(options)?),
254    )
255    .await?
256    .json()
257    .await?;
258    Ok(serde_json::from_value(json["chatIds"].clone()).unwrap_or_default())
259}
260
261/// Moves a chat in or out of the archive.
262pub async fn archive(
263    authorization: &CredentialsOrApiKey,
264    chat_id: &str,
265    archived: bool,
266) -> Result<()> {
267    post(
268        authorization,
269        "/cicada/chats/archive",
270        Some(json!({ "chatId": chat_id, "archived": archived })),
271    )
272    .await?;
273    Ok(())
274}
275
276/// Sets (or clears, with None) a reminder; when it's due the chat comes back to the top of the
277/// inbox.
278pub async fn remind(
279    authorization: &CredentialsOrApiKey,
280    chat_id: &str,
281    at: Option<DateTime<Utc>>,
282) -> Result<()> {
283    post(
284        authorization,
285        "/cicada/chats/remind",
286        Some(json!({
287            "chatId": chat_id,
288            "at": at.map(|at| at.to_rfc3339_opts(SecondsFormat::Millis, true)),
289        })),
290    )
291    .await?;
292    Ok(())
293}
294
295/// `{ recipients, mode }` in the TypeScript SDK: who a scheduled compose goes to.
296#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
297pub struct ComposeTarget {
298    pub recipients: Vec<String>,
299    pub mode: SendMode,
300}
301
302/// The `options` argument of `schedule`.
303#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
304#[serde(rename_all = "camelCase")]
305pub struct ScheduleOptions {
306    #[serde(
307        deserialize_with = "deserialize_date",
308        serialize_with = "serialize_date"
309    )]
310    pub send_at: DateTime<Utc>,
311    pub text: String,
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    pub platform: Option<Platform>,
314    #[serde(default, skip_serializing_if = "Option::is_none")]
315    pub chat_id: Option<String>,
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub compose: Option<ComposeTarget>,
318    #[serde(default, skip_serializing_if = "Option::is_none")]
319    pub inbox_id: Option<String>,
320    #[serde(default, skip_serializing_if = "Option::is_none")]
321    pub account_id: Option<String>,
322}
323
324/// Queues an outbound message: a reply in `chat_id`, or `compose` for fresh chats. Resolves to
325/// its id.
326pub async fn schedule(
327    authorization: &CredentialsOrApiKey,
328    options: &ScheduleOptions,
329) -> Result<String> {
330    let json: Value = post(
331        authorization,
332        "/cicada/schedule",
333        Some(serde_json::to_value(options)?),
334    )
335    .await?
336    .json()
337    .await?;
338    Ok(id_text(&json["id"]))
339}
340
341pub async fn list_scheduled(
342    authorization: &CredentialsOrApiKey,
343    inbox_id: Option<&str>,
344) -> Result<Vec<ScheduledSend>> {
345    Ok(post(
346        authorization,
347        "/cicada/scheduled/list",
348        Some(inbox_body(inbox_id)),
349    )
350    .await?
351    .json()
352    .await?)
353}
354
355pub async fn cancel_scheduled(authorization: &CredentialsOrApiKey, scheduled: &str) -> Result<()> {
356    post(
357        authorization,
358        "/cicada/scheduled/cancel",
359        Some(json!({ "scheduled": scheduled })),
360    )
361    .await?;
362    Ok(())
363}