use std::collections::{HashMap, HashSet};
use jmap_chat_types::{Chat, ChatKind};
use jmap_types::{Id, Invocation, JmapError, PatchObject, UTCDate};
use serde_json::{json, Value};
use crate::backend::{BackendSetError, ChatBackend, SetError, SetErrorType};
use crate::helpers::{
extract_account_id, finalize_set_response, now_utc_string, set_error_value, SetAccumulators,
};
pub async fn handle_chat_get<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
jmap_server::handlers::handle_get::<Chat, B>(backend, caller, args).await
}
pub async fn handle_chat_changes<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
jmap_server::handlers::handle_changes::<Chat, B>(backend, caller, args).await
}
pub async fn handle_chat_query<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
jmap_server::handlers::handle_query::<Chat, B>(backend, caller, args).await
}
pub async fn handle_chat_query_changes<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
jmap_server::handlers::handle_query_changes::<Chat, B>(backend, caller, args).await
}
pub async fn handle_chat_set<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
let old_state = backend
.get_state::<Chat>(caller, &account_id)
.await
.map_err(|e| JmapError::server_fail(e.to_string()))?;
if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str()) {
if if_in_state != old_state.as_ref() {
return Err(JmapError::state_mismatch());
}
}
let mut created = serde_json::Map::new();
let mut not_created = serde_json::Map::new();
let mut updated = serde_json::Map::new();
let mut not_updated = serde_json::Map::new();
let mut destroyed_list: Vec<Value> = Vec::new();
let mut not_destroyed = serde_json::Map::new();
let mut mutated = false;
if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
let has_direct_create = create_map.values().any(|v| {
v.get("kind")
.and_then(|k| k.as_str())
.is_some_and(|s| s.eq_ignore_ascii_case("direct"))
});
let existing_chats: Vec<Chat>;
let mut known_direct_contact_ids: HashSet<String>;
if has_direct_create {
let (chats, _) = backend
.get_objects::<Chat>(caller, &account_id, None, None)
.await
.map_err(|e| JmapError::server_fail(e.to_string()))?;
known_direct_contact_ids = chats
.iter()
.filter(|c| c.kind == ChatKind::Direct)
.filter_map(|c| c.contact_id.as_ref().map(|id| id.as_ref().to_owned()))
.collect();
existing_chats = chats;
} else {
existing_chats = Vec::new();
known_direct_contact_ids = HashSet::new();
}
let mut batch_direct_ids: HashMap<String, Id> = HashMap::new();
for (create_id, obj_val) in create_map {
let kind_str = match obj_val.get("kind").and_then(|v| v.as_str()) {
Some(s) => s.to_owned(),
None => {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["kind"] }),
);
continue;
}
};
let kind: ChatKind = match serde_json::from_value(Value::String(kind_str.clone())) {
Ok(k) => k,
Err(_) => ChatKind::Other(kind_str),
};
let direct_contact_id_str: Option<String> = match &kind {
ChatKind::Direct => {
let contact_id_str = match obj_val.get("contactId").and_then(|v| v.as_str()) {
Some(s) => s.to_owned(),
None => {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["contactId"] }),
);
continue;
}
};
if let Some(dup) = existing_chats.iter().find(|c| {
c.kind == ChatKind::Direct
&& c.contact_id.as_ref().map(|id| id.as_ref())
== Some(contact_id_str.as_str())
}) {
not_created.insert(
create_id.clone(),
serde_json::to_value(
SetError::new(SetErrorType::AlreadyExists)
.with_existing_id(dup.id.clone()),
)
.expect("derive(Serialize) on plain data is infallible"),
);
continue;
}
if known_direct_contact_ids.contains(&contact_id_str) {
let canonical_id = if let Some(c) = existing_chats.iter().find(|c| {
c.kind == ChatKind::Direct
&& c.contact_id.as_ref().map(|id| id.as_ref())
== Some(contact_id_str.as_str())
}) {
c.id.clone()
} else if let Some(id) = batch_direct_ids.get(&contact_id_str) {
id.clone()
} else {
not_created.insert(
create_id.clone(),
json!({
"type": "serverFail",
"description": "direct chat for contact not found after concurrent operation; retry"
}),
);
continue;
};
not_created.insert(
create_id.clone(),
serde_json::to_value(
SetError::new(SetErrorType::AlreadyExists)
.with_existing_id(canonical_id),
)
.expect("derive(Serialize) on plain data is infallible"),
);
continue;
}
Some(contact_id_str)
}
ChatKind::Channel => {
if obj_val.get("spaceId").and_then(|v| v.as_str()).is_none() {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["spaceId"] }),
);
continue;
}
None
}
_ => None,
};
let now_str = now_utc_string();
let now: UTCDate = UTCDate::from(now_str.as_str());
let contact_id: Option<Id> = obj_val
.get("contactId")
.and_then(|v| v.as_str())
.map(Id::from);
let name: Option<String> = obj_val
.get("name")
.and_then(|v| v.as_str())
.map(str::to_owned);
let description: Option<String> = obj_val
.get("description")
.and_then(|v| v.as_str())
.map(str::to_owned);
let space_id: Option<Id> = obj_val
.get("spaceId")
.and_then(|v| v.as_str())
.map(Id::from);
let muted: bool = obj_val
.get("muted")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let receive_typing_indicators: bool = obj_val
.get("receiveTypingIndicators")
.and_then(|v| v.as_bool())
.unwrap_or(true);
let mut chat = Chat::new(
Id::from("placeholder"),
kind,
now,
0,
vec![],
muted,
receive_typing_indicators,
);
chat.contact_id = contact_id;
chat.name = name;
chat.description = description;
chat.space_id = space_id;
match backend
.create_object::<Chat>(caller, &account_id, create_id, chat)
.await
{
Ok((new_id, created_obj)) => {
if let Some(contact_id_str) = direct_contact_id_str.as_deref() {
let (current_chats, _) = backend
.get_objects::<Chat>(caller, &account_id, None, None)
.await
.map_err(|e| JmapError::server_fail(e.to_string()))?;
let duplicates: Vec<&Chat> = current_chats
.iter()
.filter(|c| {
c.kind == ChatKind::Direct
&& c.contact_id.as_ref().map(|id| id.as_ref())
== Some(contact_id_str)
})
.collect();
if duplicates.len() > 1 {
let canonical_id: Id = duplicates
.iter()
.map(|c| c.id.as_ref())
.min()
.map(Id::from)
.unwrap_or_else(|| new_id.clone());
if new_id != canonical_id {
if let Err(e) = backend
.destroy_object::<Chat>(caller, &account_id, &new_id)
.await
{
not_created.insert(
create_id.clone(),
json!({
"type": "serverFail",
"description": format!(
"failed to clean up duplicate Direct chat; retry ({})",
e
)
}),
);
continue;
}
not_created.insert(
create_id.clone(),
serde_json::to_value(
SetError::new(SetErrorType::AlreadyExists)
.with_existing_id(canonical_id),
)
.unwrap_or_else(|e| {
json!({ "type": "serverFail", "description": e.to_string() })
}),
);
continue;
}
}
known_direct_contact_ids.insert(contact_id_str.to_owned());
batch_direct_ids.insert(contact_id_str.to_owned(), new_id.clone());
}
mutated = true;
created.insert(
create_id.clone(),
serde_json::to_value(&created_obj)
.expect("derive(Serialize) on plain data is infallible"),
);
}
Err(BackendSetError::SetError(set_err)) => {
not_created.insert(create_id.clone(), set_error_value(&set_err));
}
Err(BackendSetError::Other(e)) => {
not_created.insert(
create_id.clone(),
json!({ "type": "serverFail", "description": e.to_string() }),
);
}
Err(_) => {
not_created.insert(
create_id.clone(),
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
}
if let Some(Value::Object(update_map)) = args.remove("update") {
for (id_str, patch_val) in update_map {
let id = Id::from(id_str.as_str());
const CHAT_READONLY: &[&str] = &["id", "createdAt", "unreadCount", "pinnedMessageIds"];
let bad_props: Vec<&str> = CHAT_READONLY
.iter()
.copied()
.filter(|&field| patch_val.get(field).is_some())
.collect();
if !bad_props.is_empty() {
not_updated.insert(
id_str,
json!({ "type": "invalidProperties", "properties": bad_props }),
);
continue;
}
let patch = match serde_json::from_value::<PatchObject>(patch_val) {
Ok(p) => p,
Err(e) => {
not_updated.insert(
id_str,
json!({ "type": "invalidPatch", "description": e.to_string() }),
);
continue;
}
};
match backend
.update_object::<Chat>(caller, &account_id, &id, patch)
.await
{
Ok(Some(obj)) => {
mutated = true;
updated.insert(
id_str,
serde_json::to_value(&obj)
.expect("derive(Serialize) on plain data is infallible"),
);
}
Ok(None) => {
mutated = true;
updated.insert(id_str, Value::Null);
}
Err(BackendSetError::SetError(set_err)) => {
not_updated.insert(id_str, set_error_value(&set_err));
}
Err(BackendSetError::Other(e)) => {
not_updated.insert(
id_str,
json!({ "type": "serverFail", "description": e.to_string() }),
);
}
Err(_) => {
not_updated.insert(
id_str,
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
}
if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
if let Some(bad) = destroy_arr.iter().find(|v| !v.is_string()) {
return Err(JmapError::invalid_arguments(format!(
"destroy: every element must be a string Id; got {bad}"
)));
}
for id_val in destroy_arr {
let id_str = match id_val.as_str() {
Some(s) => s,
None => continue, };
let id = Id::from(id_str);
match backend
.destroy_object::<Chat>(caller, &account_id, &id)
.await
{
Ok(()) => {
mutated = true;
destroyed_list.push(Value::String(id_str.to_owned()));
}
Err(BackendSetError::SetError(set_err)) => {
not_destroyed.insert(id_str.to_owned(), set_error_value(&set_err));
}
Err(BackendSetError::Other(e)) => {
not_destroyed.insert(
id_str.to_owned(),
json!({ "type": "serverFail", "description": e.to_string() }),
);
}
Err(_) => {
not_destroyed.insert(
id_str.to_owned(),
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
}
finalize_set_response::<B, Chat>(
backend,
caller,
&account_id,
old_state,
mutated,
SetAccumulators {
created,
updated,
destroyed: destroyed_list,
not_created,
not_updated,
not_destroyed,
},
)
.await
}
pub async fn handle_chat_typing<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (account_id, args) = extract_account_id(args)?;
let chat_id: Id = match args.get("chatId").and_then(|v| v.as_str()) {
Some(s) if !s.is_empty() => Id::from(s),
_ => return Err(JmapError::invalid_arguments("chatId is required")),
};
let _typing: bool = match args.get("typing") {
Some(Value::Bool(b)) => *b,
None => return Err(JmapError::invalid_arguments("typing is required")),
Some(_) => return Err(JmapError::invalid_arguments("typing must be a boolean")),
};
if let Ok((found, _not_found)) = backend
.get_objects::<Chat>(
caller,
&account_id,
Some(std::slice::from_ref(&chat_id)),
None,
)
.await
{
if let Some(chat) = found.first() {
if let Some(contact_id) = chat.contact_id.as_ref() {
let _blocked = backend
.is_contact_blocked(caller, &account_id, contact_id)
.await
.unwrap_or(false);
}
}
}
Ok((
json!({
"accountId": account_id.as_ref(),
}),
vec![],
))
}