use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use super::contacts::{Contact, post};
use crate::authentification::CredentialsOrApiKey;
use crate::drive::{self, DriveAuthorization};
use crate::error::Result;
use crate::http::{deserialize_date, serialize_date};
use crate::integrations::Platform;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ContactOrString {
Contact(Contact),
String(String),
}
fn inbox_id<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Option<String>, D::Error> {
Ok(match Value::deserialize(deserializer)? {
Value::Null => None,
Value::String(id) => Some(id),
id => Some(id.to_string()),
})
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Conversation {
pub id: String,
#[serde(
default,
deserialize_with = "inbox_id",
skip_serializing_if = "Option::is_none"
)]
pub inbox_id: Option<String>,
#[serde(default)]
pub participants: Vec<ContactOrString>,
#[serde(
deserialize_with = "deserialize_date",
serialize_with = "serialize_date"
)]
pub active_at: DateTime<Utc>,
#[serde(default)]
pub unread: u64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Reminder {
pub conversation: Conversation,
#[serde(
deserialize_with = "deserialize_date",
serialize_with = "serialize_date"
)]
pub remind_at: DateTime<Utc>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SendMode {
Broadcast,
Group,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ScheduledContext {
Conversation {
conversation: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
platform: Option<Platform>,
},
Compose {
recipients: Vec<ContactOrString>,
mode: SendMode,
platform: Platform,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduledSend {
pub id: String,
#[serde(
deserialize_with = "deserialize_date",
serialize_with = "serialize_date"
)]
pub send_at: DateTime<Utc>,
#[serde(
deserialize_with = "deserialize_date",
serialize_with = "serialize_date"
)]
pub created_at: DateTime<Utc>,
pub message: String,
pub context: ScheduledContext,
}
#[derive(Debug, Clone)]
pub struct Message {
pub id: String,
pub author: ContactOrString,
pub platform: Platform,
pub created_at: DateTime<Utc>,
pub message: String,
pub raw: Option<String>,
pub attachments: Vec<drive::File>,
pub agent: bool,
}
impl Message {
fn from_json(json: &Value, authorization: &CredentialsOrApiKey) -> Option<Message> {
Some(Message {
id: json["id"].as_str().unwrap_or_default().to_string(),
author: serde_json::from_value(json["author"].clone()).ok()?,
platform: serde_json::from_value(json["platform"].clone()).ok()?,
created_at: crate::tickets::parse_date(&json["createdAt"]).unwrap_or_default(),
message: json["message"].as_str().unwrap_or_default().to_string(),
raw: json["raw"].as_str().map(str::to_string),
attachments: json["attachments"]
.as_array()
.into_iter()
.flatten()
.map(|attachment| {
let mut meta = attachment.clone();
meta["contentLength"] = attachment["size"].clone();
drive::File::from_json(
&meta,
DriveAuthorization::AccessCode {
authorization: authorization.clone(),
access_code: attachment["accessCode"]
.as_str()
.unwrap_or_default()
.to_string(),
},
)
})
.collect(),
agent: json["agent"] == true,
})
}
}
fn inbox_body(inbox_id: Option<&str>) -> Value {
match inbox_id.filter(|id| !id.is_empty()) {
Some(inbox_id) => json!({ "inboxId": inbox_id }),
None => json!({}),
}
}
async fn list_view(
authorization: &CredentialsOrApiKey,
path: &str,
inbox_id: Option<&str>,
) -> Result<Vec<Conversation>> {
Ok(post(authorization, path, Some(inbox_body(inbox_id)))
.await?
.json()
.await?)
}
pub async fn list_inbox(
authorization: &CredentialsOrApiKey,
inbox_id: Option<&str>,
) -> Result<Vec<Conversation>> {
list_view(authorization, "/cicada/inbox", inbox_id).await
}
pub async fn list_archived(
authorization: &CredentialsOrApiKey,
inbox_id: Option<&str>,
) -> Result<Vec<Conversation>> {
list_view(authorization, "/cicada/archived", inbox_id).await
}
pub async fn list_reminders(
authorization: &CredentialsOrApiKey,
inbox_id: Option<&str>,
) -> Result<Vec<Reminder>> {
Ok(post(
authorization,
"/cicada/reminders",
Some(inbox_body(inbox_id)),
)
.await?
.json()
.await?)
}
pub async fn get(
authorization: &CredentialsOrApiKey,
conversation: &str,
) -> Result<Option<Conversation>> {
let json: Value = post(
authorization,
"/cicada/conversation/get",
Some(json!({ "conversation": conversation })),
)
.await?
.json()
.await?;
Ok(if json.is_null() || json == false {
None
} else {
Some(serde_json::from_value(json)?)
})
}
pub async fn read(authorization: &CredentialsOrApiKey, conversation: &str) -> Result<Vec<Message>> {
let json: Value = post(
authorization,
"/cicada/conversation",
Some(json!({ "conversation": conversation })),
)
.await?
.json()
.await?;
Ok(json
.as_array()
.into_iter()
.flatten()
.filter_map(|message| Message::from_json(message, authorization))
.collect())
}
pub async fn autocomplete(
authorization: &CredentialsOrApiKey,
conversation: &str,
text: &str,
) -> Result<String> {
Ok(post(
authorization,
"/cicada/autocomplete",
Some(json!({ "conversation": conversation, "text": text })),
)
.await?
.text()
.await?)
}
pub async fn mark_read(authorization: &CredentialsOrApiKey, conversation: &str) -> Result<()> {
post(
authorization,
"/cicada/conversation/mark-read",
Some(json!({ "conversation": conversation })),
)
.await?;
Ok(())
}
pub async fn remove(authorization: &CredentialsOrApiKey, conversation: &str) -> Result<()> {
post(
authorization,
"/cicada/conversation/delete",
Some(json!({ "conversation": conversation })),
)
.await?;
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ComposeOptions {
pub recipients: Vec<String>,
pub platform: Platform,
pub text: String,
pub mode: SendMode,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub inbox_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub account_id: Option<String>,
}
pub async fn compose(
authorization: &CredentialsOrApiKey,
options: &ComposeOptions,
) -> Result<Vec<String>> {
let json: Value = post(
authorization,
"/cicada/compose",
Some(serde_json::to_value(options)?),
)
.await?
.json()
.await?;
Ok(serde_json::from_value(json["conversationIds"].clone()).unwrap_or_default())
}
fn id_of(json: &Value) -> String {
match &json["id"] {
Value::String(id) => id.clone(),
Value::Null => String::new(),
id => id.to_string(),
}
}
pub async fn send(
authorization: &CredentialsOrApiKey,
conversation: &str,
text: &str,
platform: Option<Platform>,
) -> Result<String> {
let mut body = Map::new();
body.insert("conversation".to_string(), Value::from(conversation));
body.insert("text".to_string(), Value::from(text));
if let Some(platform) = platform {
body.insert("platform".to_string(), serde_json::to_value(platform)?);
}
let json: Value = post(authorization, "/cicada/send", Some(Value::Object(body)))
.await?
.json()
.await?;
Ok(id_of(&json))
}
pub async fn archive(
authorization: &CredentialsOrApiKey,
conversation: &str,
archived: bool,
) -> Result<()> {
post(
authorization,
"/cicada/conversation/archive",
Some(json!({ "conversation": conversation, "archived": archived })),
)
.await?;
Ok(())
}
pub async fn remind(
authorization: &CredentialsOrApiKey,
conversation: &str,
at: Option<DateTime<Utc>>,
) -> Result<()> {
post(
authorization,
"/cicada/conversation/remind",
Some(json!({
"conversation": conversation,
"at": at.map(|at| at.to_rfc3339_opts(SecondsFormat::Millis, true)),
})),
)
.await?;
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ComposeTarget {
pub recipients: Vec<String>,
pub mode: SendMode,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduleOptions {
#[serde(
deserialize_with = "deserialize_date",
serialize_with = "serialize_date"
)]
pub send_at: DateTime<Utc>,
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub platform: Option<Platform>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conversation_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compose: Option<ComposeTarget>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub inbox_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub account_id: Option<String>,
}
pub async fn schedule(
authorization: &CredentialsOrApiKey,
options: &ScheduleOptions,
) -> Result<String> {
let json: Value = post(
authorization,
"/cicada/schedule",
Some(serde_json::to_value(options)?),
)
.await?
.json()
.await?;
Ok(id_of(&json))
}
pub async fn list_scheduled(
authorization: &CredentialsOrApiKey,
inbox_id: Option<&str>,
) -> Result<Vec<ScheduledSend>> {
Ok(post(
authorization,
"/cicada/scheduled/list",
Some(inbox_body(inbox_id)),
)
.await?
.json()
.await?)
}
pub async fn cancel_scheduled(authorization: &CredentialsOrApiKey, scheduled: &str) -> Result<()> {
post(
authorization,
"/cicada/scheduled/cancel",
Some(json!({ "scheduled": scheduled })),
)
.await?;
Ok(())
}