use jmap_chat_types::{Chat, DeliveryState, Message, SenderId, BROADCAST_MENTION_SCOPES};
use jmap_types::{Id, Invocation, JmapError, PatchObject, State, UTCDate};
use serde_json::{json, Value};
use crate::backend::{BackendSetError, ChatBackend, SetError, SetErrorType};
use std::collections::HashSet;
use crate::helpers::{
enforce_max_objects_in_set, extract_account_id, filter_properties, finalize_set_response,
iso8601_before, not_found_json, now_utc_string, serialize_value, set_error_value,
SetAccumulators,
};
use jmap_server::{server_fail_from_backend, server_fail_value_from_backend};
pub async fn handle_message_get<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
let ids: Option<Vec<Id>> = match args.remove("ids") {
None | Some(Value::Null) => None,
Some(v) => Some(
serde_json::from_value(v)
.map_err(|_| JmapError::invalid_arguments("ids must be an Id array"))?,
),
};
let properties: Option<Vec<String>> = match args.remove("properties") {
None | Some(Value::Null) => None,
Some(v) => Some(
serde_json::from_value(v)
.map_err(|_| JmapError::invalid_arguments("properties must be a string array"))?,
),
};
let ids_slice = ids.as_deref();
let (mut list, not_found) = backend
.get_objects::<Message>(caller, &account_id, ids_slice, properties.as_deref())
.await
.map_err(|e| server_fail_from_backend(&e))?;
if !backend.retains_edit_history() {
for msg in list.iter_mut() {
msg.edit_history = None;
}
}
let state = backend
.get_state::<Message>(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let list_json: Vec<Value> = if let Some(ref props) = properties {
let mut prop_set: HashSet<&str> = props.iter().map(|s| s.as_str()).collect();
prop_set.insert("id");
list.iter()
.map(|obj| {
let val = serialize_value(obj)?;
Ok(filter_properties(&val, &prop_set))
})
.collect::<Result<Vec<_>, JmapError>>()?
} else {
list.iter()
.map(serialize_value)
.collect::<Result<Vec<_>, _>>()?
};
Ok((
json!({
"accountId": account_id.as_ref(),
"state": state.as_ref(),
"list": list_json,
"notFound": not_found_json(¬_found),
}),
vec![],
))
}
pub async fn handle_message_changes<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
jmap_server::handlers::handle_changes::<Message, B>(backend, caller, args).await
}
pub async fn handle_message_query<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
let calculate_total: bool = args
.get("calculateTotal")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let limit: Option<u64> = match args.remove("limit") {
None | Some(Value::Null) => None,
Some(v) => match v.as_u64() {
Some(n) => Some(n),
None => {
return Err(JmapError::invalid_arguments(format!(
"limit: expected a non-negative integer, got {v}"
)))
}
},
};
let position: i64 = match args.remove("position") {
None | Some(Value::Null) => 0,
Some(v) => v.as_i64().ok_or_else(|| {
JmapError::invalid_arguments(format!("position: expected an integer, got {v}"))
})?,
};
let filter: Option<serde_json::Value> = match args.remove("filter") {
None | Some(Value::Null) => None,
Some(v) => Some(v),
};
let has_chat_id = filter
.as_ref()
.and_then(|f| f.get("chatId"))
.map(|v| !v.is_null())
.unwrap_or(false);
let has_mention_true = filter
.as_ref()
.and_then(|f| f.get("hasMention"))
.and_then(|v| v.as_bool())
.unwrap_or(false);
if !has_chat_id && !has_mention_true {
return Err(JmapError::unsupported_filter());
}
let sort: Option<Vec<serde_json::Value>> = match args.remove("sort") {
None | Some(Value::Null) => None,
Some(v) => Some(
serde_json::from_value(v)
.map_err(|_| JmapError::invalid_arguments("sort must be an array"))?,
),
};
let result = backend
.query_objects::<Message>(
caller,
&account_id,
filter.as_ref(),
sort.as_deref(),
limit,
position,
)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let mut resp = json!({
"accountId": account_id.as_ref(),
"queryState": result.query_state.as_ref(),
"canCalculateChanges": result.can_calculate_changes,
"position": result.position,
"ids": result.ids.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
});
if calculate_total {
if let Some(t) = result.total {
resp["total"] = json!(t);
}
}
Ok((resp, vec![]))
}
pub async fn handle_message_query_changes<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (account_id, args) = extract_account_id(args)?;
let since_query_state: State = match args.get("sinceQueryState").and_then(|v| v.as_str()) {
Some(s) => State::from(s),
None => return Err(JmapError::invalid_arguments("sinceQueryState is required")),
};
let max_changes: Option<u64> = match args.get("maxChanges") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_u64().filter(|&n| n > 0).ok_or_else(|| {
JmapError::invalid_arguments("maxChanges must be a positive integer")
})?),
};
let up_to_id: Option<Id> = match args.get("upToId") {
None | Some(Value::Null) => None,
Some(Value::String(s)) => Some(Id::from(s.as_str())),
Some(_) => {
return Err(JmapError::invalid_arguments(
"upToId must be a string Id or null",
))
}
};
let calculate_total: bool = args
.get("calculateTotal")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let result = backend
.query_changes::<Message>(
caller,
&account_id,
&since_query_state,
None,
None,
max_changes,
up_to_id.as_ref(),
false,
)
.await
.map_err(JmapError::from)?;
let removed: Vec<&str> = result.removed.iter().map(|id| id.as_ref()).collect();
let added: Vec<Value> = result
.added
.iter()
.map(|item| {
json!({
"id": item.id.as_ref(),
"index": item.index,
})
})
.collect();
let mut resp = json!({
"accountId": account_id.as_ref(),
"oldQueryState": result.old_query_state.as_ref(),
"newQueryState": result.new_query_state.as_ref(),
"removed": removed,
"added": added,
});
if calculate_total {
if let Some(t) = result.total {
resp["total"] = json!(t);
}
}
Ok((resp, vec![]))
}
fn validate_broadcast_mentions(
broadcast_mentions: &[serde_json::Value],
body: &str,
body_type: &str,
) -> Option<String> {
if body_type == "application/jmap-chat-rich" && !broadcast_mentions.is_empty() {
return Some(
"broadcastMentions must be empty when bodyType is application/jmap-chat-rich".into(),
);
}
for (i, bm) in broadcast_mentions.iter().enumerate() {
let scope = match bm.get("scope").and_then(|v| v.as_str()) {
Some(s) => s,
None => {
return Some(format!(
"broadcastMentions[{i}]: missing or non-string scope"
));
}
};
if !BROADCAST_MENTION_SCOPES.contains(&scope) {
return Some(format!(
"broadcastMentions[{i}]: unrecognized scope \"{scope}\""
));
}
let offset = bm.get("offset").and_then(|v| v.as_u64()).unwrap_or(0);
let length = bm.get("length").and_then(|v| v.as_u64()).unwrap_or(0);
let end = match offset.checked_add(length) {
Some(e) => e,
None => {
return Some(format!(
"broadcastMentions[{i}]: offset + length overflows u64"
));
}
};
let body_len = body.len() as u64;
if end > body_len {
return Some(format!(
"broadcastMentions[{i}]: offset({offset}) + length({length}) = {end} exceeds body byte length {body_len}"
));
}
}
None
}
pub async fn handle_message_set<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
let old_state = backend
.get_state::<Message>(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?;
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()) {
for (create_id, obj_val) in create_map {
let Some(chat_id_str) = obj_val.get("chatId").and_then(|v| v.as_str()) else {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["chatId"] }),
);
continue;
};
let chat_id = Id::from(chat_id_str);
let Some(body) = obj_val
.get("body")
.and_then(|v| v.as_str())
.map(str::to_owned)
else {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["body"] }),
);
continue;
};
if body.len() > 100_000 {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["body"] }),
);
continue;
}
let Some(sent_at_str) = obj_val.get("sentAt").and_then(|v| v.as_str()) else {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
);
continue;
};
let Ok(sent_at) = UTCDate::new_validated(sent_at_str) else {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
);
continue;
};
let body_type = obj_val
.get("bodyType")
.and_then(|v| v.as_str())
.unwrap_or("text/plain")
.to_owned();
let broadcast_mentions_val: Vec<Value> = obj_val
.get("broadcastMentions")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
if let Some(desc) =
validate_broadcast_mentions(&broadcast_mentions_val, &body, &body_type)
{
not_created.insert(
create_id.clone(),
json!({ "type": "invalidArguments", "description": desc }),
);
continue;
}
if !broadcast_mentions_val.is_empty() {
let chat_lookup = backend
.get_objects::<Chat>(
caller,
&account_id,
Some(std::slice::from_ref(&chat_id)),
None,
)
.await;
match chat_lookup {
Ok((found, _)) => {
if let Some(chat) = found.first() {
if let Some(ref sid) = chat.space_id {
match backend
.may_broadcast_mention(caller, &account_id, sid)
.await
{
Ok(Ok(())) => {}
Ok(Err(set_err)) => {
not_created
.insert(create_id.clone(), set_error_value(&set_err));
continue;
}
Err(e) => {
not_created.insert(
create_id.clone(),
server_fail_value_from_backend(&e),
);
continue;
}
}
}
}
}
Err(e) => {
not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
continue;
}
}
}
let reply_to: Option<Id> = obj_val
.get("replyTo")
.and_then(|v| v.as_str())
.map(Id::from);
let thread_root_id: Option<Id> = obj_val
.get("threadRootId")
.and_then(|v| v.as_str())
.map(Id::from);
let sender_expires_at: Option<UTCDate> =
if let Some(s) = obj_val.get("senderExpiresAt").and_then(|v| v.as_str()) {
let Ok(d) = UTCDate::new_validated(s) else {
not_created.insert(
create_id.clone(),
json!({
"type": "invalidProperties",
"properties": ["senderExpiresAt"],
}),
);
continue;
};
Some(d)
} else {
None
};
let burn_on_read: Option<bool> = obj_val.get("burnOnRead").and_then(|v| v.as_bool());
if let Some(ref expires_at) = sender_expires_at {
let now = now_utc_string();
if !iso8601_before(&now, expires_at) {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["senderExpiresAt"] }),
);
continue;
}
}
if let Err(slow_err) = backend.slow_mode_check(caller, &account_id, &chat_id).await {
let retry_after_str: String = slow_err.retry_after.as_ref().to_owned();
let set_err = SetError::new(SetErrorType::custom("rateLimited"))
.with_description("Slow mode is active for this chat")
.with_extra("serverRetryAfter", json!(retry_after_str));
not_created.insert(create_id.clone(), set_error_value(&set_err));
continue;
}
let now_str = now_utc_string();
let received_at: UTCDate = UTCDate::from(now_str.as_ref());
let mut msg = Message::new(
Id::from("placeholder"),
Id::from(create_id.as_str()),
SenderId::Owner,
chat_id,
body,
body_type,
sent_at,
received_at,
DeliveryState::Pending,
);
msg.reply_to = reply_to;
msg.thread_root_id = thread_root_id;
if let Some(d) = sender_expires_at {
msg.sender_expires_at = Some(d);
}
msg.burn_on_read = burn_on_read;
match backend
.create_object::<Message>(caller, &account_id, create_id, msg)
.await
{
Ok((_server_id, created_obj)) => {
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(), server_fail_value_from_backend(&e));
}
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 MESSAGE_READONLY: &[&str] = &[
"id",
"senderMsgId",
"senderId",
"chatId",
"sentAt",
"receivedAt",
"deliveryState",
];
let bad_props: Vec<&str> = MESSAGE_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 deletes_for_all =
patch_val.get("deletedForAll").and_then(|v| v.as_bool()) == Some(true);
if deletes_for_all {
match backend
.get_objects::<Message>(
caller,
&account_id,
Some(std::slice::from_ref(&id)),
None,
)
.await
{
Ok((found, _not_found)) => {
if found
.first()
.is_some_and(|m| m.sender_id != SenderId::Owner)
{
not_updated.insert(
id_str,
json!({
"type": "forbidden",
"description": "deletedForAll is only permitted on messages whose senderId is \"self\"",
}),
);
continue;
}
}
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
}
}
let mut augmented = patch_val;
if augmented.get("body").is_some() {
if let Some(obj) = augmented.as_object_mut() {
obj.insert("editedAt".to_owned(), json!(now_utc_string()));
}
}
let deletes =
deletes_for_all || augmented.get("deletedAt").is_some_and(|v| !v.is_null());
if deletes {
if let Some(obj) = augmented.as_object_mut() {
if deletes_for_all {
obj.insert("deletedAt".to_owned(), json!(now_utc_string()));
}
obj.insert("body".to_owned(), json!(""));
obj.insert("attachments".to_owned(), json!([]));
obj.insert("editHistory".to_owned(), Value::Null);
}
}
if let Some(obj) = augmented.as_object_mut() {
if obj.contains_key("readAt") && !obj.contains_key("readDisposition") {
obj.insert("readDisposition".to_owned(), json!("displayed"));
}
}
let reaction_pointer_keys: Vec<String> = augmented
.as_object()
.map(|obj| {
obj.keys()
.filter(|k| k.starts_with("reactions/"))
.cloned()
.collect()
})
.unwrap_or_default();
if !reaction_pointer_keys.is_empty() {
if augmented
.as_object()
.is_some_and(|obj| obj.contains_key("reactions"))
{
not_updated.insert(
id_str,
json!({
"type": "invalidPatch",
"description":
"patch must not combine top-level `reactions` with `reactions/{id}` entries",
}),
);
continue;
}
let decoded: Result<Vec<(String, String)>, String> = reaction_pointer_keys
.iter()
.map(|raw_key| {
let suffix = &raw_key["reactions/".len()..];
if suffix.is_empty() || suffix.contains('/') || suffix.contains('~') {
return Err(format!(
"reactions/{{id}} pointer key {raw_key:?} has empty or forbidden suffix; '/' and '~' are reserved by RFC 6901",
));
}
let val = augmented.get(raw_key).unwrap_or(&Value::Null);
if !val.is_null() {
let ok = val.as_object().is_some_and(|m| {
m.get("emoji")
.and_then(|v| v.as_str())
.is_some_and(|s| !s.is_empty())
});
if !ok {
return Err(format!(
"reaction value for {raw_key:?} must be null or an object with a non-empty `emoji` string",
));
}
}
Ok((raw_key.clone(), suffix.to_owned()))
})
.collect();
let decoded = match decoded {
Ok(d) => d,
Err(desc) => {
not_updated.insert(
id_str,
json!({ "type": "invalidPatch", "description": desc }),
);
continue;
}
};
let forbidden = match backend
.get_objects::<Message>(
caller,
&account_id,
Some(std::slice::from_ref(&id)),
None,
)
.await
{
Ok((found, _not_found)) => {
let mut bad: Vec<String> = Vec::new();
if let Some(msg) = found.first() {
for (_, suffix) in &decoded {
if let Some(existing) = msg.reactions.get(suffix) {
if existing.sender_id != SenderId::Owner {
bad.push(suffix.clone());
}
}
}
}
bad
}
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
};
if !forbidden.is_empty() {
not_updated.insert(
id_str,
json!({
"type": "forbidden",
"description": format!(
"cannot modify reactions authored by another sender: {}",
forbidden.join(", "),
),
}),
);
continue;
}
let now_str = now_utc_string();
if let Some(obj) = augmented.as_object_mut() {
for (raw_key, _) in &decoded {
if let Some(Value::Object(map)) = obj.get_mut(raw_key) {
map.insert("senderId".to_owned(), json!("self"));
map.entry("sentAt").or_insert_with(|| json!(now_str));
}
}
}
}
let patch_sets_read_at = augmented.get("readAt").is_some_and(|v| !v.is_null());
let pre_patch_burn_on_read = if patch_sets_read_at {
match backend
.get_objects::<Message>(
caller,
&account_id,
Some(std::slice::from_ref(&id)),
None,
)
.await
{
Ok((found, _not_found)) => {
found.first().and_then(|m| m.burn_on_read) == Some(true)
}
Err(_) => false,
}
} else {
false
};
let patch_has_bm = augmented
.as_object()
.is_some_and(|obj| obj.contains_key("broadcastMentions"));
if patch_has_bm {
let (current_body, current_body_type, msg_chat_id) = match backend
.get_objects::<Message>(
caller,
&account_id,
Some(std::slice::from_ref(&id)),
None,
)
.await
{
Ok((found, _)) => {
if let Some(msg) = found.first() {
(
msg.body.clone(),
msg.body_type.clone(),
Some(msg.chat_id.clone()),
)
} else {
(String::new(), String::from("text/plain"), None)
}
}
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
};
let post_patch_body = augmented
.get("body")
.and_then(|v| v.as_str())
.unwrap_or(¤t_body);
let post_patch_body_type = augmented
.get("bodyType")
.and_then(|v| v.as_str())
.unwrap_or(¤t_body_type);
let bm_arr: Vec<Value> = augmented
.get("broadcastMentions")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
if let Some(desc) =
validate_broadcast_mentions(&bm_arr, post_patch_body, post_patch_body_type)
{
not_updated.insert(
id_str,
json!({ "type": "invalidArguments", "description": desc }),
);
continue;
}
if !bm_arr.is_empty() {
if let Some(ref cid) = msg_chat_id {
let chat_lookup = backend
.get_objects::<Chat>(
caller,
&account_id,
Some(std::slice::from_ref(cid)),
None,
)
.await;
match chat_lookup {
Ok((found, _)) => {
if let Some(chat) = found.first() {
if let Some(ref sid) = chat.space_id {
match backend
.may_broadcast_mention(caller, &account_id, sid)
.await
{
Ok(Ok(())) => {}
Ok(Err(set_err)) => {
not_updated
.insert(id_str, set_error_value(&set_err));
continue;
}
Err(e) => {
not_updated.insert(
id_str,
server_fail_value_from_backend(&e),
);
continue;
}
}
}
}
}
Err(e) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
}
}
}
}
let patch = match serde_json::from_value::<PatchObject>(augmented) {
Ok(p) => p,
Err(e) => {
not_updated.insert(
id_str,
json!({ "type": "invalidPatch", "description": e.to_string() }),
);
continue;
}
};
let update_outcome = backend
.update_object::<Message>(caller, &account_id, &id, patch)
.await;
let maybe_updated_obj = match update_outcome {
Ok(maybe_obj) => maybe_obj,
Err(BackendSetError::SetError(set_err)) => {
not_updated.insert(id_str, set_error_value(&set_err));
continue;
}
Err(BackendSetError::Other(e)) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
Err(_) => {
not_updated.insert(
id_str,
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
continue;
}
};
if patch_sets_read_at && pre_patch_burn_on_read {
if let Err(burn_err) = backend.expire_message(caller, &account_id, &id).await {
not_updated.insert(id_str, server_fail_value_from_backend(&burn_err));
mutated = true;
continue;
}
}
mutated = true;
match maybe_updated_obj {
Some(obj) => {
updated.insert(
id_str,
serde_json::to_value(&obj)
.expect("derive(Serialize) on plain data is infallible"),
);
}
None => {
updated.insert(id_str, Value::Null);
}
}
}
}
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 Some(id_str) = id_val.as_str() else {
continue; };
let id = Id::from(id_str);
match backend
.destroy_object::<Message>(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(), server_fail_value_from_backend(&e));
}
Err(_) => {
not_destroyed.insert(
id_str.to_owned(),
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
}
finalize_set_response::<B, Message>(
backend,
caller,
&account_id,
old_state,
mutated,
SetAccumulators {
created,
updated,
destroyed: destroyed_list,
not_created,
not_updated,
not_destroyed,
},
)
.await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::memory::MemoryBackend;
use serde_json::json;
const ACCOUNT_ID: &str = "a1";
#[tokio::test]
async fn broadcast_mention_validation_rejects_unknown_scope() {
let backend = MemoryBackend::new();
let (resp, _) = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": "c1",
"body": "Hello @channel",
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "channel", "offset": 6, "length": 8 }
]
}
}
}),
)
.await
.expect("handle_message_set");
assert!(resp["notCreated"]["m0"].is_object());
assert_eq!(resp["notCreated"]["m0"]["type"], "invalidArguments");
let desc = resp["notCreated"]["m0"]["description"]
.as_str()
.expect("description");
assert!(
desc.contains("unrecognized scope"),
"expected 'unrecognized scope' in description, got: {desc}"
);
}
#[tokio::test]
async fn broadcast_mention_validation_rejects_overflow() {
let backend = MemoryBackend::new();
let (resp, _) = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": "c1",
"body": "Hello @everyone",
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "everyone", "offset": u64::MAX, "length": 1 }
]
}
}
}),
)
.await
.expect("handle_message_set");
assert!(resp["notCreated"]["m0"].is_object());
assert_eq!(resp["notCreated"]["m0"]["type"], "invalidArguments");
let desc = resp["notCreated"]["m0"]["description"]
.as_str()
.expect("description");
assert!(
desc.contains("overflows u64"),
"expected 'overflows u64' in description, got: {desc}"
);
}
#[tokio::test]
async fn broadcast_mention_validation_rejects_exceeds_body() {
let backend = MemoryBackend::new();
let (resp, _) = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": "c1",
"body": "short",
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "everyone", "offset": 0, "length": 999 }
]
}
}
}),
)
.await
.expect("handle_message_set");
assert!(resp["notCreated"]["m0"].is_object());
assert_eq!(resp["notCreated"]["m0"]["type"], "invalidArguments");
let desc = resp["notCreated"]["m0"]["description"]
.as_str()
.expect("description");
assert!(
desc.contains("exceeds body byte length"),
"expected 'exceeds body byte length' in description, got: {desc}"
);
}
#[tokio::test]
async fn broadcast_mention_validation_rejects_rich_body_nonempty() {
let backend = MemoryBackend::new();
let (resp, _) = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": "c1",
"body": "Hello @everyone in rich",
"bodyType": "application/jmap-chat-rich",
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "everyone", "offset": 6, "length": 9 }
]
}
}
}),
)
.await
.expect("handle_message_set");
assert!(resp["notCreated"]["m0"].is_object());
assert_eq!(resp["notCreated"]["m0"]["type"], "invalidArguments");
let desc = resp["notCreated"]["m0"]["description"]
.as_str()
.expect("description");
assert!(
desc.contains("application/jmap-chat-rich"),
"expected 'application/jmap-chat-rich' in description, got: {desc}"
);
}
#[tokio::test]
async fn broadcast_mention_validation_accepts_valid() {
let backend = MemoryBackend::new();
let body = "Hello @everyone!";
let (resp, _) = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": "c1",
"body": body,
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "everyone", "offset": 6, "length": 9 }
]
}
}
}),
)
.await
.expect("handle_message_set");
assert!(
resp["created"]["m0"].is_object(),
"expected created, got notCreated: {}",
resp["notCreated"]["m0"]
);
}
#[tokio::test]
async fn broadcast_mention_validation_accepts_empty() {
let backend = MemoryBackend::new();
let (resp, _) = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": "c1",
"body": "Hello, world!",
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": []
}
}
}),
)
.await
.expect("handle_message_set");
assert!(
resp["created"]["m0"].is_object(),
"expected created, got notCreated: {}",
resp["notCreated"]["m0"]
);
}
async fn make_group_chat(backend: &MemoryBackend) -> String {
let (resp, _) = crate::chat::handle_chat_set(
backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": { "c0": { "kind": "group", "name": "test-group" } }
}),
)
.await
.expect("make_group_chat");
resp["created"]["c0"]["id"]
.as_str()
.expect("group chat id")
.to_owned()
}
async fn make_channel_chat(backend: &MemoryBackend) -> String {
let (space_resp, _) = crate::space::handle_space_set(
backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": { "s0": { "name": "test-space" } }
}),
)
.await
.expect("make_channel_chat: space");
let space_id = space_resp["created"]["s0"]["id"]
.as_str()
.expect("space id");
let (chat_resp, _) = crate::chat::handle_chat_set(
backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": { "c0": {
"kind": "channel",
"name": "general",
"spaceId": space_id
} }
}),
)
.await
.expect("make_channel_chat: chat");
chat_resp["created"]["c0"]["id"]
.as_str()
.expect("channel chat id")
.to_owned()
}
#[tokio::test]
async fn broadcast_mention_create_without_space_unrestricted() {
let backend = MemoryBackend::new();
let chat_id = make_group_chat(&backend).await;
let body = "Hello @everyone!";
let (resp, _) = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": chat_id,
"body": body,
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "everyone", "offset": 6, "length": 9 }
]
}
}
}),
)
.await
.expect("handle_message_set");
assert!(
resp["created"]["m0"].is_object(),
"expected created in group chat (no spaceId), got notCreated: {}",
resp["notCreated"]["m0"]
);
}
#[tokio::test]
async fn broadcast_mention_create_in_channel_succeeds() {
let backend = MemoryBackend::new();
let chat_id = make_channel_chat(&backend).await;
let body = "Hello @everyone!";
let (resp, _) = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": chat_id,
"body": body,
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "everyone", "offset": 6, "length": 9 }
]
}
}
}),
)
.await
.expect("handle_message_set");
assert!(
resp["created"]["m0"].is_object(),
"expected created in channel chat, got notCreated: {}",
resp["notCreated"]["m0"]
);
}
#[tokio::test]
async fn broadcast_mention_create_empty_skips_permission_check() {
let backend = MemoryBackend::new();
let chat_id = make_channel_chat(&backend).await;
let (resp, _) = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": chat_id,
"body": "Hello, world!",
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": []
}
}
}),
)
.await
.expect("handle_message_set");
assert!(
resp["created"]["m0"].is_object(),
"expected created with empty broadcastMentions, got notCreated: {}",
resp["notCreated"]["m0"]
);
}
#[tokio::test]
async fn broadcast_mention_update_retaining_broadcast_succeeds() {
let backend = MemoryBackend::new();
let chat_id = make_channel_chat(&backend).await;
let body = "Hello @everyone!";
let (create_resp, _) = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"create": {
"m0": {
"chatId": chat_id,
"body": body,
"sentAt": "2024-01-01T00:00:00Z",
"broadcastMentions": [
{ "scope": "everyone", "offset": 6, "length": 9 }
]
}
}
}),
)
.await
.expect("create message");
let msg_id = create_resp["created"]["m0"]["id"]
.as_str()
.expect("message id");
let new_body = "Hey @here now!";
let (update_resp, _) = handle_message_set(
&backend,
&(),
json!({
"accountId": ACCOUNT_ID,
"update": {
(msg_id): {
"body": new_body,
"broadcastMentions": [
{ "scope": "here", "offset": 4, "length": 5 }
]
}
}
}),
)
.await
.expect("update message");
assert!(
update_resp["updated"][msg_id].is_null() || update_resp["updated"][msg_id].is_object(),
"expected updated, got notUpdated: {}",
update_resp["notUpdated"][msg_id]
);
assert!(
update_resp["notUpdated"].is_null()
|| !update_resp["notUpdated"]
.as_object()
.is_some_and(|m| m.contains_key(msg_id)),
"message should not be in notUpdated"
);
}
}