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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Note {
28 pub position: u32,
29 pub text: String,
30}
31
32#[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#[derive(Debug, Clone)]
48pub struct Chat {
49 pub summary: ChatSummary,
50 pub inbox_id: String,
51 pub participants: Vec<ContactOrOwnerOrString>,
52 pub channel: Option<ChatChannel>,
54 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#[derive(Debug, Clone)]
86pub struct Reminder {
87 pub chat: Chat,
88 pub remind_at: DateTime<Utc>,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
94#[serde(rename_all = "lowercase")]
95pub enum SendMode {
96 Broadcast,
97 Group,
98}
99
100#[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#[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
137fn 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
165pub 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
174pub 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
182pub 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
204pub 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
217pub 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#[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
242pub 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
261pub 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
276pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
297pub struct ComposeTarget {
298 pub recipients: Vec<String>,
299 pub mode: SendMode,
300}
301
302#[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
324pub 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}