use serde_json::Value;
use crate::crypto::asymmetric::{open_attachment_with_key, open_with_private_key, AsymmetricBox};
use crate::crypto::cipher::{open_json, SealedBox};
use crate::error::Result;
use crate::keys::Keys;
use crate::models::{Attachment, Message};
use crate::trackers::strip_remote_content;
fn text(value: Option<&Value>) -> String {
value.and_then(Value::as_str).unwrap_or_default().to_string()
}
fn address_of(value: Option<&Value>) -> String {
match value {
Some(Value::String(s)) => s.clone(),
Some(Value::Object(_)) => text(value.and_then(|v| v.get("address"))),
_ => String::new(),
}
}
fn name_of(value: Option<&Value>) -> String {
match value {
Some(Value::Object(_)) => text(value.and_then(|v| v.get("name"))),
_ => String::new(),
}
}
fn attachments_of(value: Option<&Value>) -> Vec<Attachment> {
let Some(Value::Array(items)) = value else { return Vec::new() };
items
.iter()
.enumerate()
.map(|(index, item)| {
let size = item
.get("size")
.and_then(Value::as_u64)
.or_else(|| item.get("sizeBytes").and_then(Value::as_u64))
.unwrap_or(0);
let filename = text(item.get("filename"));
let content_id = text(item.get("contentId"));
Attachment {
index,
filename: if filename.is_empty() { "attachment".into() } else { filename },
mime_type: text(item.get("mimeType")),
size,
content_id: if content_id.is_empty() { None } else { Some(content_id) },
stored: item.get("stored").and_then(Value::as_bool).unwrap_or(true),
}
})
.collect()
}
fn open_content(keys: Option<&Keys>, wire: &Value) -> Option<Value> {
let keys = keys?;
let content = wire.get("content").filter(|v| !v.is_null())?;
let address_id = text(wire.get("inboxId"));
let message_id = text(wire.get("id"));
if content.get("epk").and_then(Value::as_str).is_some() {
let box_: AsymmetricBox = serde_json::from_value(content.clone()).ok()?;
let private_key = keys.address_private_key(&address_id).ok()?;
let plaintext =
open_with_private_key(&private_key, &box_, &format!("{address_id}:{message_id}")).ok()?;
serde_json::from_slice(&plaintext).ok()
} else {
let box_: SealedBox = serde_json::from_value(content.clone()).ok()?;
let key = keys.address_symmetric_key(&address_id).ok()?;
open_json(&key, &box_, &message_id).ok()
}
}
pub fn to_message(keys: Option<&Keys>, wire: &Value) -> Message {
let content = open_content(keys, wire);
let body = content.clone().unwrap_or(Value::Null);
let get = |key: &str| body.get(key);
let html = {
let primary = text(get("html"));
if primary.is_empty() {
text(get("bodyHtml"))
} else {
primary
}
};
let from_address = {
let primary = text(get("fromAddress"));
if primary.is_empty() {
address_of(get("from"))
} else {
primary
}
};
let to = match get("to") {
Some(Value::Array(items)) => address_of(items.first()),
other => address_of(other),
};
let stripped = if html.is_empty() { None } else { Some(strip_remote_content(&html)) };
let from_name = {
let primary = text(get("fromName"));
if primary.is_empty() {
name_of(get("from"))
} else {
primary
}
};
let reply_to = {
let primary = text(get("replyTo"));
if primary.is_empty() {
from_address.clone()
} else {
primary
}
};
let text_body = {
let primary = text(get("text"));
if primary.is_empty() {
text(get("bodyText"))
} else {
primary
}
};
let folder = {
let primary = text(wire.get("folder"));
if primary.is_empty() {
"inbox".to_string()
} else {
primary
}
};
Message {
id: text(wire.get("id")),
address_id: text(wire.get("inboxId")),
received_at: text(wire.get("receivedAt")),
read: wire.get("read").and_then(Value::as_bool).unwrap_or(false),
starred: wire.get("starred").and_then(Value::as_bool).unwrap_or(false),
folder,
size_bytes: wire.get("sizeBytes").and_then(Value::as_u64).unwrap_or(0),
sent_via: wire.get("sentVia").and_then(Value::as_str).map(str::to_string),
opened: content.is_some(),
from_address,
from_name,
reply_to,
to,
subject: text(get("subject")),
text: text_body,
html,
safe_html: stripped.as_ref().map(|s| s.html.clone()).unwrap_or_default(),
blocked: stripped.map(|s| s.blocked).unwrap_or_default(),
message_id: text(get("messageId")),
attachments: attachments_of(get("attachments")),
}
}
pub fn open_attachment_bytes(
keys: &Keys,
address_id: &str,
message_id: &str,
index: usize,
data: &[u8],
) -> Result<Vec<u8>> {
let private_key = keys.address_private_key(address_id)?;
open_attachment_with_key(&private_key, address_id, &format!("{address_id}/{message_id}/{index}"), data)
}