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