use std::ops::Deref;
use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::contacts::{Contact, Owner, post};
use crate::authentification::CredentialsOrApiKey;
use crate::error::Result;
use crate::http::{deserialize_date, serialize_date};
use crate::integrations::Platform;
use crate::parrot::chat::ChatSummary;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ContactOrOwnerOrString {
Contact(Contact),
Owner(Owner),
String(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Note {
pub position: u32,
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatChannel {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub platform: Option<Platform>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub guild_name: Option<String>,
}
#[derive(Debug, Clone)]
pub struct Chat {
pub summary: ChatSummary,
pub inbox_id: String,
pub participants: Vec<ContactOrOwnerOrString>,
pub channel: Option<ChatChannel>,
pub platform: Option<Platform>,
pub archived: bool,
pub remind_at: Option<DateTime<Utc>>,
pub notes: Vec<Note>,
}
impl Deref for Chat {
type Target = ChatSummary;
fn deref(&self) -> &ChatSummary {
&self.summary
}
}
impl Chat {
pub fn from_json(json: &Value) -> Chat {
Chat {
summary: ChatSummary::from_json(json),
inbox_id: id_text(&json["inboxId"]),
participants: serde_json::from_value(json["participants"].clone()).unwrap_or_default(),
channel: serde_json::from_value(json["channel"].clone()).ok(),
platform: serde_json::from_value(json["platform"].clone()).ok(),
archived: json["archived"] == true,
remind_at: crate::tickets::parse_date(&json["remindAt"]),
notes: serde_json::from_value(json["notes"].clone()).unwrap_or_default(),
}
}
}
#[derive(Debug, Clone)]
pub struct Reminder {
pub chat: Chat,
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 {
Chat {
#[serde(rename = "chatId")]
chat_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
platform: Option<Platform>,
},
Compose {
recipients: Vec<ContactOrOwnerOrString>,
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,
}
fn id_text(json: &Value) -> String {
match json {
Value::String(id) => id.clone(),
Value::Null => String::new(),
id => id.to_string(),
}
}
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<Chat>> {
let rows: Vec<Value> = post(authorization, path, Some(inbox_body(inbox_id)))
.await?
.json()
.await?;
Ok(rows.iter().map(Chat::from_json).collect())
}
pub async fn list_inbox(
authorization: &CredentialsOrApiKey,
inbox_id: Option<&str>,
) -> Result<Vec<Chat>> {
list_view(authorization, "/cicada/inbox", inbox_id).await
}
pub async fn list_archived(
authorization: &CredentialsOrApiKey,
inbox_id: Option<&str>,
) -> Result<Vec<Chat>> {
list_view(authorization, "/cicada/archived", inbox_id).await
}
pub async fn list_reminders(
authorization: &CredentialsOrApiKey,
inbox_id: Option<&str>,
) -> Result<Vec<Reminder>> {
let rows: Vec<Value> = post(
authorization,
"/cicada/reminders",
Some(inbox_body(inbox_id)),
)
.await?
.json()
.await?;
Ok(rows
.iter()
.map(|row| Reminder {
chat: Chat::from_json(&row["chat"]),
remind_at: crate::tickets::parse_date(&row["remindAt"]).unwrap_or_default(),
})
.collect())
}
pub async fn get(authorization: &CredentialsOrApiKey, chat_id: &str) -> Result<Option<Chat>> {
let json: Value = post(
authorization,
"/cicada/chats/get",
Some(json!({ "chatId": chat_id })),
)
.await?
.json()
.await?;
Ok(json.is_object().then(|| Chat::from_json(&json)))
}
pub async fn remove(authorization: &CredentialsOrApiKey, chat_id: &str) -> Result<()> {
post(
authorization,
"/cicada/chats/delete",
Some(json!({ "chatId": chat_id })),
)
.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["chatIds"].clone()).unwrap_or_default())
}
pub async fn archive(
authorization: &CredentialsOrApiKey,
chat_id: &str,
archived: bool,
) -> Result<()> {
post(
authorization,
"/cicada/chats/archive",
Some(json!({ "chatId": chat_id, "archived": archived })),
)
.await?;
Ok(())
}
pub async fn remind(
authorization: &CredentialsOrApiKey,
chat_id: &str,
at: Option<DateTime<Utc>>,
) -> Result<()> {
post(
authorization,
"/cicada/chats/remind",
Some(json!({
"chatId": chat_id,
"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 chat_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_text(&json["id"]))
}
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(())
}