1use chrono::{DateTime, SecondsFormat, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::{Map, Value, json};
4
5use super::contacts::{Contact, post};
6use crate::authentification::CredentialsOrApiKey;
7use crate::drive::{self, DriveAuthorization};
8use crate::error::Result;
9use crate::http::{deserialize_date, serialize_date};
10use crate::integrations::Platform;
11
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(untagged)]
15pub enum ContactOrString {
16 Contact(Contact),
17 String(String),
18}
19
20fn inbox_id<'de, D: serde::Deserializer<'de>>(
21 deserializer: D,
22) -> std::result::Result<Option<String>, D::Error> {
23 Ok(match Value::deserialize(deserializer)? {
24 Value::Null => None,
25 Value::String(id) => Some(id),
26 id => Some(id.to_string()),
27 })
28}
29
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
31#[serde(rename_all = "camelCase")]
32pub struct Conversation {
33 pub id: String,
34 #[serde(
35 default,
36 deserialize_with = "inbox_id",
37 skip_serializing_if = "Option::is_none"
38 )]
39 pub inbox_id: Option<String>,
40 #[serde(default)]
41 pub participants: Vec<ContactOrString>,
42 #[serde(
43 deserialize_with = "deserialize_date",
44 serialize_with = "serialize_date"
45 )]
46 pub active_at: DateTime<Utc>,
47 #[serde(default)]
48 pub unread: u64,
49}
50
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54#[serde(rename_all = "camelCase")]
55pub struct Reminder {
56 pub conversation: Conversation,
57 #[serde(
58 deserialize_with = "deserialize_date",
59 serialize_with = "serialize_date"
60 )]
61 pub remind_at: DateTime<Utc>,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
67#[serde(rename_all = "lowercase")]
68pub enum SendMode {
69 Broadcast,
70 Group,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(untagged)]
77pub enum ScheduledContext {
78 Conversation {
79 conversation: String,
80 #[serde(default, skip_serializing_if = "Option::is_none")]
81 platform: Option<Platform>,
82 },
83 Compose {
84 recipients: Vec<ContactOrString>,
85 mode: SendMode,
86 platform: Platform,
87 },
88}
89
90#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
92#[serde(rename_all = "camelCase")]
93pub struct ScheduledSend {
94 pub id: String,
95 #[serde(
96 deserialize_with = "deserialize_date",
97 serialize_with = "serialize_date"
98 )]
99 pub send_at: DateTime<Utc>,
100 #[serde(
101 deserialize_with = "deserialize_date",
102 serialize_with = "serialize_date"
103 )]
104 pub created_at: DateTime<Utc>,
105 pub message: String,
106 pub context: ScheduledContext,
107}
108
109#[derive(Debug, Clone)]
110pub struct Message {
111 pub id: String,
112 pub author: ContactOrString,
113 pub platform: Platform,
114 pub created_at: DateTime<Utc>,
115 pub message: String,
116 pub raw: Option<String>,
117 pub attachments: Vec<drive::File>,
118 pub agent: bool,
120}
121
122impl Message {
123 fn from_json(json: &Value, authorization: &CredentialsOrApiKey) -> Option<Message> {
124 Some(Message {
125 id: json["id"].as_str().unwrap_or_default().to_string(),
126 author: serde_json::from_value(json["author"].clone()).ok()?,
127 platform: serde_json::from_value(json["platform"].clone()).ok()?,
128 created_at: crate::tickets::parse_date(&json["createdAt"]).unwrap_or_default(),
129 message: json["message"].as_str().unwrap_or_default().to_string(),
130 raw: json["raw"].as_str().map(str::to_string),
131 attachments: json["attachments"]
132 .as_array()
133 .into_iter()
134 .flatten()
135 .map(|attachment| {
136 let mut meta = attachment.clone();
137 meta["contentLength"] = attachment["size"].clone();
138 drive::File::from_json(
139 &meta,
140 DriveAuthorization::AccessCode {
141 authorization: authorization.clone(),
142 access_code: attachment["accessCode"]
143 .as_str()
144 .unwrap_or_default()
145 .to_string(),
146 },
147 )
148 })
149 .collect(),
150 agent: json["agent"] == true,
151 })
152 }
153}
154
155fn inbox_body(inbox_id: Option<&str>) -> Value {
156 match inbox_id.filter(|id| !id.is_empty()) {
157 Some(inbox_id) => json!({ "inboxId": inbox_id }),
158 None => json!({}),
159 }
160}
161
162async fn list_view(
163 authorization: &CredentialsOrApiKey,
164 path: &str,
165 inbox_id: Option<&str>,
166) -> Result<Vec<Conversation>> {
167 Ok(post(authorization, path, Some(inbox_body(inbox_id)))
168 .await?
169 .json()
170 .await?)
171}
172
173pub async fn list_inbox(
176 authorization: &CredentialsOrApiKey,
177 inbox_id: Option<&str>,
178) -> Result<Vec<Conversation>> {
179 list_view(authorization, "/cicada/inbox", inbox_id).await
180}
181
182pub async fn list_archived(
184 authorization: &CredentialsOrApiKey,
185 inbox_id: Option<&str>,
186) -> Result<Vec<Conversation>> {
187 list_view(authorization, "/cicada/archived", inbox_id).await
188}
189
190pub async fn list_reminders(
192 authorization: &CredentialsOrApiKey,
193 inbox_id: Option<&str>,
194) -> Result<Vec<Reminder>> {
195 Ok(post(
196 authorization,
197 "/cicada/reminders",
198 Some(inbox_body(inbox_id)),
199 )
200 .await?
201 .json()
202 .await?)
203}
204
205pub async fn get(
208 authorization: &CredentialsOrApiKey,
209 conversation: &str,
210) -> Result<Option<Conversation>> {
211 let json: Value = post(
212 authorization,
213 "/cicada/conversation/get",
214 Some(json!({ "conversation": conversation })),
215 )
216 .await?
217 .json()
218 .await?;
219 Ok(if json.is_null() || json == false {
220 None
221 } else {
222 Some(serde_json::from_value(json)?)
223 })
224}
225
226pub async fn read(authorization: &CredentialsOrApiKey, conversation: &str) -> Result<Vec<Message>> {
227 let json: Value = post(
228 authorization,
229 "/cicada/conversation",
230 Some(json!({ "conversation": conversation })),
231 )
232 .await?
233 .json()
234 .await?;
235 Ok(json
236 .as_array()
237 .into_iter()
238 .flatten()
239 .filter_map(|message| Message::from_json(message, authorization))
240 .collect())
241}
242
243pub async fn autocomplete(
247 authorization: &CredentialsOrApiKey,
248 conversation: &str,
249 text: &str,
250) -> Result<String> {
251 Ok(post(
252 authorization,
253 "/cicada/autocomplete",
254 Some(json!({ "conversation": conversation, "text": text })),
255 )
256 .await?
257 .text()
258 .await?)
259}
260
261pub async fn mark_read(authorization: &CredentialsOrApiKey, conversation: &str) -> Result<()> {
262 post(
263 authorization,
264 "/cicada/conversation/mark-read",
265 Some(json!({ "conversation": conversation })),
266 )
267 .await?;
268 Ok(())
269}
270
271pub async fn remove(authorization: &CredentialsOrApiKey, conversation: &str) -> Result<()> {
275 post(
276 authorization,
277 "/cicada/conversation/delete",
278 Some(json!({ "conversation": conversation })),
279 )
280 .await?;
281 Ok(())
282}
283
284#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
286#[serde(rename_all = "camelCase")]
287pub struct ComposeOptions {
288 pub recipients: Vec<String>,
289 pub platform: Platform,
290 pub text: String,
291 pub mode: SendMode,
292 #[serde(default, skip_serializing_if = "Option::is_none")]
293 pub inbox_id: Option<String>,
294 #[serde(default, skip_serializing_if = "Option::is_none")]
295 pub account_id: Option<String>,
296}
297
298pub async fn compose(
304 authorization: &CredentialsOrApiKey,
305 options: &ComposeOptions,
306) -> Result<Vec<String>> {
307 let json: Value = post(
308 authorization,
309 "/cicada/compose",
310 Some(serde_json::to_value(options)?),
311 )
312 .await?
313 .json()
314 .await?;
315 Ok(serde_json::from_value(json["conversationIds"].clone()).unwrap_or_default())
316}
317
318fn id_of(json: &Value) -> String {
319 match &json["id"] {
320 Value::String(id) => id.clone(),
321 Value::Null => String::new(),
322 id => id.to_string(),
323 }
324}
325
326pub async fn send(
327 authorization: &CredentialsOrApiKey,
328 conversation: &str,
329 text: &str,
330 platform: Option<Platform>,
331) -> Result<String> {
332 let mut body = Map::new();
333 body.insert("conversation".to_string(), Value::from(conversation));
334 body.insert("text".to_string(), Value::from(text));
335 if let Some(platform) = platform {
336 body.insert("platform".to_string(), serde_json::to_value(platform)?);
337 }
338 let json: Value = post(authorization, "/cicada/send", Some(Value::Object(body)))
339 .await?
340 .json()
341 .await?;
342 Ok(id_of(&json))
343}
344
345pub async fn archive(
347 authorization: &CredentialsOrApiKey,
348 conversation: &str,
349 archived: bool,
350) -> Result<()> {
351 post(
352 authorization,
353 "/cicada/conversation/archive",
354 Some(json!({ "conversation": conversation, "archived": archived })),
355 )
356 .await?;
357 Ok(())
358}
359
360pub async fn remind(
363 authorization: &CredentialsOrApiKey,
364 conversation: &str,
365 at: Option<DateTime<Utc>>,
366) -> Result<()> {
367 post(
368 authorization,
369 "/cicada/conversation/remind",
370 Some(json!({
371 "conversation": conversation,
372 "at": at.map(|at| at.to_rfc3339_opts(SecondsFormat::Millis, true)),
373 })),
374 )
375 .await?;
376 Ok(())
377}
378
379#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
381pub struct ComposeTarget {
382 pub recipients: Vec<String>,
383 pub mode: SendMode,
384}
385
386#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
388#[serde(rename_all = "camelCase")]
389pub struct ScheduleOptions {
390 #[serde(
391 deserialize_with = "deserialize_date",
392 serialize_with = "serialize_date"
393 )]
394 pub send_at: DateTime<Utc>,
395 pub text: String,
396 #[serde(default, skip_serializing_if = "Option::is_none")]
397 pub platform: Option<Platform>,
398 #[serde(default, skip_serializing_if = "Option::is_none")]
399 pub conversation_id: Option<String>,
400 #[serde(default, skip_serializing_if = "Option::is_none")]
401 pub compose: Option<ComposeTarget>,
402 #[serde(default, skip_serializing_if = "Option::is_none")]
403 pub inbox_id: Option<String>,
404 #[serde(default, skip_serializing_if = "Option::is_none")]
405 pub account_id: Option<String>,
406}
407
408pub async fn schedule(
411 authorization: &CredentialsOrApiKey,
412 options: &ScheduleOptions,
413) -> Result<String> {
414 let json: Value = post(
415 authorization,
416 "/cicada/schedule",
417 Some(serde_json::to_value(options)?),
418 )
419 .await?
420 .json()
421 .await?;
422 Ok(id_of(&json))
423}
424
425pub async fn list_scheduled(
426 authorization: &CredentialsOrApiKey,
427 inbox_id: Option<&str>,
428) -> Result<Vec<ScheduledSend>> {
429 Ok(post(
430 authorization,
431 "/cicada/scheduled/list",
432 Some(inbox_body(inbox_id)),
433 )
434 .await?
435 .json()
436 .await?)
437}
438
439pub async fn cancel_scheduled(authorization: &CredentialsOrApiKey, scheduled: &str) -> Result<()> {
440 post(
441 authorization,
442 "/cicada/scheduled/cancel",
443 Some(json!({ "scheduled": scheduled })),
444 )
445 .await?;
446 Ok(())
447}