use std::time::{SystemTime, UNIX_EPOCH};
use jmap_chat_types::{Chat, ChatBan, Message, PresenceStatus, SpaceBan};
use jmap_types::{Id, PatchObject, UTCDate};
use serde_json::{Map, Value, json};
use crate::ChatBackend;
use crate::chat::record_unread_count_changes;
use jmap_server::BackendSetError;
pub async fn sweep_expired<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
now: SystemTime,
) -> Result<(), BackendSetError<B::Error>> {
let now = now
.duration_since(UNIX_EPOCH)
.map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX));
let (chats, _) = backend
.get_objects::<Chat>(caller, account_id, None, None)
.await
.map_err(BackendSetError::Other)?;
expire_messages(backend, caller, account_id, now, &chats).await?;
for chat in &chats {
if chat.mute_until.as_ref().is_some_and(|t| passed(now, t, 0)) {
let patch = patch([("muted", json!(false)), ("muteUntil", Value::Null)]);
backend
.update_object::<Chat>(caller, account_id, &chat.id, patch)
.await?;
}
}
let (presences, _) = backend
.get_objects::<PresenceStatus>(caller, account_id, None, None)
.await
.map_err(BackendSetError::Other)?;
for status in &presences {
if status
.expires_at
.as_ref()
.is_some_and(|t| passed(now, t, 0))
{
let patch = patch([
("statusText", Value::Null),
("statusEmoji", Value::Null),
("presence", json!("online")),
("expiresAt", Value::Null),
]);
backend
.update_object::<PresenceStatus>(caller, account_id, &status.id, patch)
.await?;
}
}
lift_expired_bans(backend, caller, account_id, now).await
}
fn passed(now: i64, t: &UTCDate, offset: u64) -> bool {
t.to_epoch_seconds().is_ok_and(|t| {
i64::try_from(offset).is_ok_and(|o| t.checked_add(o).is_some_and(|d| now >= d))
})
}
async fn expire_messages<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
now: i64,
chats: &[Chat],
) -> Result<(), BackendSetError<B::Error>> {
let (messages, _) = backend
.get_objects::<Message>(caller, account_id, None, None)
.await
.map_err(BackendSetError::Other)?;
let mut expired_chat_ids = Vec::new();
let mut expire_result = Ok(());
for msg in &messages {
let policy = chats
.iter()
.find(|c| c.id == msg.chat_id)
.and_then(|c| c.message_expiry_seconds)
.filter(|&s| s > 0);
let read_deadline = msg.sender_id != *account_id
&& msg.read_at.as_ref().is_some_and(|read| {
msg.burn_on_read == Some(true)
|| msg
.expires_after_read_seconds
.is_some_and(|s| passed(now, read, s))
});
let expired = msg
.sender_expires_at
.as_ref()
.is_some_and(|t| passed(now, t, 0))
|| policy.is_some_and(|s| s < u64::MAX && passed(now, &msg.received_at, s + 1))
|| read_deadline;
if expired {
if let Err(e) = backend.expire_message(caller, account_id, &msg.id).await {
expire_result = Err(BackendSetError::Other(e));
break;
}
expired_chat_ids.push(msg.chat_id.clone());
}
}
record_unread_count_changes(backend, caller, account_id, expired_chat_ids).await;
expire_result
}
async fn lift_expired_bans<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
now: i64,
) -> Result<(), BackendSetError<B::Error>> {
let (bans, _) = backend
.get_objects::<ChatBan>(caller, account_id, None, None)
.await
.map_err(BackendSetError::Other)?;
for ban in &bans {
if ban.expires_at.as_ref().is_some_and(|t| passed(now, t, 0)) {
backend
.destroy_chat_ban(caller, account_id, &ban.id)
.await?;
}
}
let (space_bans, _) = backend
.get_objects::<SpaceBan>(caller, account_id, None, None)
.await
.map_err(BackendSetError::Other)?;
for ban in &space_bans {
if ban.expires_at.as_ref().is_some_and(|t| passed(now, t, 0)) {
backend
.destroy_object::<SpaceBan>(caller, account_id, &ban.id)
.await?;
}
}
Ok(())
}
fn patch<const N: usize>(entries: [(&str, Value); N]) -> PatchObject {
PatchObject::from(
entries
.into_iter()
.map(|(k, v)| (k.to_owned(), v))
.collect::<Map<_, _>>(),
)
}