use nostr_sdk::nips::nip44;
use nostr_sdk::prelude::*;
use crate::error::{MostroError, ServiceError};
#[derive(Debug, Clone)]
pub struct ChatMessage {
pub content: String,
pub sender: PublicKey,
pub created_at: Timestamp,
}
pub async fn unwrap_chat_message(
shared_keys: &Keys,
event: &Event,
) -> Result<ChatMessage, MostroError> {
if event.kind != Kind::GiftWrap {
return Err(MostroError::MostroInternalErr(
ServiceError::UnexpectedError("event is not a GiftWrap".to_string()),
));
}
let decrypted = nip44::decrypt(shared_keys.secret_key(), &event.pubkey, &event.content)
.map_err(|e| {
MostroError::MostroInternalErr(ServiceError::DecryptionError(format!(
"shared-key decrypt failed: {e}"
)))
})?;
let inner = Event::from_json(&decrypted).map_err(|e| {
MostroError::MostroInternalErr(ServiceError::NostrError(format!(
"malformed inner chat event: {e}"
)))
})?;
if inner.kind != Kind::TextNote {
return Err(MostroError::MostroInternalErr(
ServiceError::UnexpectedError("inner chat event is not a TextNote".to_string()),
));
}
inner.verify().map_err(|e| {
MostroError::MostroInternalErr(ServiceError::NostrError(format!(
"invalid inner chat signature: {e}"
)))
})?;
Ok(ChatMessage {
content: inner.content,
sender: inner.pubkey,
created_at: inner.created_at,
})
}