use crate::enc::{Enc, signed_by};
use crate::ids::{Permission, ProjectId, RecordId};
use crate::project::{Ctx, Project};
use crate::records::SignError;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use weirdnet_contacts::UserId;
use weirdnet_net::Keypair;
pub const MAX_TEXT: usize = 4000;
pub const MAX_REACTION: usize = 16;
pub const MAX_REACTIONS: usize = 24;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChatPerms {
pub read: Permission,
pub write: Permission,
pub manage: Permission,
}
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum ChatError {
#[error("not allowed")]
NotAllowed,
#[error("bad signature")]
BadSignature,
#[error("wrong project")]
WrongProject,
#[error("not your message")]
NotYours,
#[error("the text is empty or too long")]
BadText,
#[error("duplicate message")]
Duplicate,
#[error("no such message")]
NoSuchMessage,
#[error("mentions someone who is not in the project")]
UnknownMention,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatMessage {
pub id: RecordId,
pub project: ProjectId,
pub author: UserId,
pub text: String,
pub mentions: Vec<UserId>,
pub at_ms: i64,
pub key: Vec<u8>,
pub sig: Vec<u8>,
}
impl ChatMessage {
fn bytes(&self) -> Vec<u8> {
let e = Enc::new("chat").s(self.id.as_str()).s(self.project.as_str()).s(self.author.as_str()).s(&self.text);
self.mentions.iter().fold(e.u32(self.mentions.len() as u32), |e, u| e.s(u.as_str())).i64(self.at_ms).b(&self.key).done()
}
pub fn sign(author: &Keypair, project: &ProjectId, text: &str, mentions: Vec<UserId>, now: i64) -> Result<ChatMessage, SignError> {
let mut b = [0u8; 16];
getrandom::fill(&mut b).map_err(|e| SignError(e.to_string()))?;
let id: String = std::iter::once('m').chain(b.iter().flat_map(|x| format!("{x:02x}").chars().collect::<Vec<_>>())).collect();
let mut m = ChatMessage {
id: RecordId::new(&id),
project: project.clone(),
author: UserId::of_keypair(author),
text: text.to_string(),
mentions,
at_ms: now,
key: author.public().encode_protobuf(),
sig: Vec::new(),
};
m.sig = author.sign(&m.bytes()).map_err(|e| SignError(e.to_string()))?;
Ok(m)
}
pub fn verify(&self) -> bool {
signed_by(&self.author, &self.key, &self.bytes(), &self.sig)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatItem {
pub message: ChatMessage,
pub reactions: BTreeMap<String, BTreeSet<UserId>>,
pub deleted: Option<(UserId, i64)>,
pub posted_ms: i64,
pub seq: u64,
}
impl ChatItem {
pub fn mentions(&self, user: &UserId) -> bool {
self.deleted.is_none() && self.message.mentions.contains(user)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatLog {
items: Vec<ChatItem>,
seq: u64,
}
impl ChatLog {
fn may(p: &Project, who: &UserId, perm: &Permission, now: i64) -> Result<(), ChatError> {
if p.can(who, perm.as_str(), &Ctx::at(now)) { Ok(()) } else { Err(ChatError::NotAllowed) }
}
fn bump(&mut self) -> u64 {
self.seq += 1;
self.seq
}
pub fn seq(&self) -> u64 {
self.seq
}
pub fn post(&mut self, p: &Project, perms: &ChatPerms, from: &UserId, m: ChatMessage, now: i64) -> Result<u64, ChatError> {
if &m.author != from {
return Err(ChatError::NotYours);
}
if &m.project != p.id() {
return Err(ChatError::WrongProject);
}
if !m.verify() {
return Err(ChatError::BadSignature);
}
Self::may(p, from, &perms.write, now)?;
if m.text.trim().is_empty() || m.text.len() > MAX_TEXT {
return Err(ChatError::BadText);
}
if self.items.iter().any(|i| i.message.id == m.id) {
return Err(ChatError::Duplicate);
}
if m.mentions.iter().any(|u| p.member(u).is_none()) {
return Err(ChatError::UnknownMention);
}
let seq = self.bump();
self.items.push(ChatItem { message: m, reactions: BTreeMap::new(), deleted: None, posted_ms: now, seq });
Ok(seq)
}
fn item_mut(&mut self, id: &RecordId) -> Result<&mut ChatItem, ChatError> {
self.items.iter_mut().find(|i| &i.message.id == id && i.deleted.is_none()).ok_or(ChatError::NoSuchMessage)
}
#[allow(clippy::too_many_arguments)]
pub fn react(
&mut self,
p: &Project,
perms: &ChatPerms,
who: &UserId,
id: &RecordId,
reaction: &str,
on: bool,
now: i64,
) -> Result<u64, ChatError> {
Self::may(p, who, &perms.write, now)?;
if reaction.is_empty() || reaction.len() > MAX_REACTION || reaction.chars().any(char::is_whitespace) {
return Err(ChatError::BadText);
}
let item = self.item_mut(id)?;
if on && !item.reactions.contains_key(reaction) && item.reactions.len() >= MAX_REACTIONS {
return Err(ChatError::BadText);
}
let changed = if on {
item.reactions.entry(reaction.to_string()).or_default().insert(who.clone())
} else {
let r = item.reactions.get_mut(reaction).is_some_and(|s| s.remove(who));
item.reactions.retain(|_, s| !s.is_empty());
r
};
if !changed {
return Ok(self.seq);
}
let seq = self.bump();
self.item_mut(id)?.seq = seq;
Ok(seq)
}
pub fn delete(&mut self, p: &Project, perms: &ChatPerms, who: &UserId, id: &RecordId, now: i64) -> Result<u64, ChatError> {
let author = self.item_mut(id)?.message.author.clone();
if &author == who {
Self::may(p, who, &perms.write, now).or_else(|_| Self::may(p, who, &perms.manage, now))?;
} else {
Self::may(p, who, &perms.manage, now)?;
}
let seq = self.bump();
let item = self.item_mut(id)?;
item.message.text.clear();
item.message.mentions.clear();
item.reactions.clear();
item.deleted = Some((who.clone(), now));
item.seq = seq;
Ok(seq)
}
pub fn since(&self, p: &Project, perms: &ChatPerms, who: &UserId, since: u64, now: i64) -> Result<Vec<ChatItem>, ChatError> {
Self::may(p, who, &perms.read, now)?;
let mut v: Vec<ChatItem> = self.items.iter().filter(|i| i.seq > since).cloned().collect();
v.sort_by_key(|i| i.seq);
Ok(v)
}
pub fn items(&self) -> &[ChatItem] {
&self.items
}
}
pub fn merge(into: &mut Vec<ChatItem>, changed: Vec<ChatItem>) {
for c in changed {
match into.iter_mut().find(|i| i.message.id == c.message.id) {
Some(i) => *i = c,
None => into.push(c),
}
}
into.sort_by(|a, b| a.posted_ms.cmp(&b.posted_ms).then(a.message.id.cmp(&b.message.id)));
}