use crate::contacts::{Contacts, Receipt, now_ms};
use crate::id::UserId;
use crate::message::Delivery;
use crate::presence::PresenceView;
use crate::service::{Req, Resp, protocol};
use weirdnet_service::{Client, ServiceError, Session};
pub async fn open_session(client: &Client, peer: &UserId) -> Result<Session<Req, Resp>, ServiceError> {
client.session::<Req, Resp>(peer.as_str(), &protocol()).await
}
pub async fn flush(contacts: &Contacts, session: &Session<Req, Resp>, peer: &UserId) -> Result<usize, ServiceError> {
let mut sent = 0;
for m in contacts.outbox(peer) {
let id = m.id.clone();
match session.call(&Req::Deliver(m)).await {
Ok(Resp::Ack(Receipt::Delivered | Receipt::Request | Receipt::Duplicate)) => {
contacts.mark(peer, &id, Delivery::Delivered);
sent += 1;
}
Ok(_) => contacts.mark(peer, &id, Delivery::Failed),
Err(ServiceError::App { .. } | ServiceError::Refused { .. } | ServiceError::BadRequest { .. }) => {
contacts.mark(peer, &id, Delivery::Failed)
}
Err(e) => {
contacts.mark(peer, &id, Delivery::Sent);
return Err(e);
}
}
}
Ok(sent)
}
pub async fn pull(contacts: &Contacts, session: &Session<Req, Resp>, peer: &UserId) -> Result<usize, ServiceError> {
let since = contacts.newest_from(peer);
let Resp::Messages(msgs) = session.call(&Req::Pull { since_ms: since }).await? else {
return Err(ServiceError::App { code: "bad-response".into(), message: "not messages".into() });
};
let now = now_ms();
Ok(msgs
.into_iter()
.filter(|m| &m.from == peer)
.filter(|m| matches!(contacts.receive(m.clone(), now), Ok(Receipt::Delivered | Receipt::Request)))
.count())
}
pub async fn presence(session: &Session<Req, Resp>) -> Result<Option<PresenceView>, ServiceError> {
match session.call(&Req::Presence).await? {
Resp::Presence(p) => Ok(p),
_ => Err(ServiceError::App { code: "bad-response".into(), message: "not presence".into() }),
}
}
pub async fn send_read(contacts: &Contacts, session: &Session<Req, Resp>, peer: &UserId) -> Result<usize, ServiceError> {
let ids = contacts.mark_read(peer);
if ids.is_empty() {
return Ok(0);
}
let n = ids.len();
session.call(&Req::Read { ids }).await?;
Ok(n)
}