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