p2p_chat/sync/engine/mailbox/
processing.rs1use anyhow::Result;
3use tracing::{debug, error, trace};
4use uuid::Uuid;
5use std::ops::Deref;
6
7use crate::cli::UiNotification;
8use crate::types::{ChatRequest, DeliveryConfirmation, DeliveryStatus, EncryptedMessage, Message};
9
10use super::super::SyncEngine;
11
12impl SyncEngine {
13 pub async fn process_mailbox_messages(
30 &self,
31 messages: Vec<EncryptedMessage>,
32 ) -> Result<Vec<Uuid>> {
33 let mut processed_msg_ids = Vec::new();
34
35 for encrypted_msg in messages {
36 if self.seen.is_seen(&encrypted_msg.id).await? {
38 trace!(
39 "Message {} already seen, adding to ACK list",
40 encrypted_msg.id
41 );
42 processed_msg_ids.push(encrypted_msg.id);
43 continue;
44 }
45
46 let message = self
48 .reconstruct_message_from_mailbox(&encrypted_msg)
49 .await?;
50
51 if let Err(e) = self.history.store_message(message.clone()).await {
53 error!(
54 "Failed to store mailbox message {} in history: {}",
55 encrypted_msg.id, e
56 );
57 continue;
58 }
59
60 if let Err(e) = self.seen.mark_seen(encrypted_msg.id).await {
62 error!("Failed to mark message {} as seen: {}", encrypted_msg.id, e);
63 }
64
65 let confirmation = DeliveryConfirmation {
67 original_message_id: encrypted_msg.id,
68 timestamp: chrono::Utc::now().timestamp_millis(),
69 };
70
71 let confirmation_request = ChatRequest::DeliveryConfirmation { confirmation };
72
73 if let Some(ref network) = self.network {
74 let network_clone = network.clone();
75 let sender = encrypted_msg.sender;
76 tokio::spawn(async move {
77 if let Err(e) = network_clone.send_chat_request(sender, confirmation_request).await {
78 debug!("Failed to send delivery confirmation from mailbox: {}", e);
79 }
80 });
81 }
82
83 if let Err(e) = self.ui_notify_tx.send(UiNotification::NewMessage(message.clone())) {
85 trace!("UI notify channel closed while reporting message: {}", e);
86 }
87
88 if let Some(ref web_tx) = self.web_notify_tx {
90 let _ = web_tx.send(UiNotification::NewMessage(message));
91 }
92
93 processed_msg_ids.push(encrypted_msg.id);
94 }
95
96 Ok(processed_msg_ids)
97 }
98
99 pub async fn reconstruct_message_from_mailbox(
115 &self,
116 encrypted_msg: &EncryptedMessage,
117 ) -> Result<Message> {
118 let plaintext_content = self.identity.deref().decrypt_from(
119 &encrypted_msg.sender_pub_key,
120 &encrypted_msg.encrypted_content,
121 )?;
122
123 Ok(Message {
124 id: encrypted_msg.id,
125 sender: encrypted_msg.sender,
126 recipient: self.identity.peer_id, timestamp: encrypted_msg.timestamp,
128 content: plaintext_content,
129 nonce: encrypted_msg.nonce,
130 delivery_status: DeliveryStatus::Delivered, })
132 }
133}