1use crate::enc::{Enc, signed_by};
10use crate::ids::{Permission, ProjectId, RecordId};
11use crate::project::{Ctx, Project};
12use crate::records::SignError;
13use serde::{Deserialize, Serialize};
14use std::collections::{BTreeMap, BTreeSet};
15use weirdnet_contacts::UserId;
16use weirdnet_net::Keypair;
17
18pub const MAX_TEXT: usize = 4000;
20pub const MAX_REACTION: usize = 16;
22pub const MAX_REACTIONS: usize = 24;
24
25#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct ChatPerms {
28 pub read: Permission,
30 pub write: Permission,
32 pub manage: Permission,
34}
35
36#[derive(Debug, PartialEq, Eq, thiserror::Error)]
38pub enum ChatError {
39 #[error("not allowed")]
41 NotAllowed,
42 #[error("bad signature")]
44 BadSignature,
45 #[error("wrong project")]
47 WrongProject,
48 #[error("not your message")]
50 NotYours,
51 #[error("the text is empty or too long")]
53 BadText,
54 #[error("duplicate message")]
56 Duplicate,
57 #[error("no such message")]
59 NoSuchMessage,
60 #[error("mentions someone who is not in the project")]
62 UnknownMention,
63}
64
65#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
67pub struct ChatMessage {
68 pub id: RecordId,
70 pub project: ProjectId,
72 pub author: UserId,
74 pub text: String,
76 pub mentions: Vec<UserId>,
78 pub at_ms: i64,
80 pub key: Vec<u8>,
82 pub sig: Vec<u8>,
84}
85
86impl ChatMessage {
87 fn bytes(&self) -> Vec<u8> {
88 let e = Enc::new("chat").s(self.id.as_str()).s(self.project.as_str()).s(self.author.as_str()).s(&self.text);
89 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()
90 }
91
92 pub fn sign(author: &Keypair, project: &ProjectId, text: &str, mentions: Vec<UserId>, now: i64) -> Result<ChatMessage, SignError> {
94 let mut b = [0u8; 16];
95 getrandom::fill(&mut b).map_err(|e| SignError(e.to_string()))?;
96 let id: String = std::iter::once('m').chain(b.iter().flat_map(|x| format!("{x:02x}").chars().collect::<Vec<_>>())).collect();
97 let mut m = ChatMessage {
98 id: RecordId::new(&id),
99 project: project.clone(),
100 author: UserId::of_keypair(author),
101 text: text.to_string(),
102 mentions,
103 at_ms: now,
104 key: author.public().encode_protobuf(),
105 sig: Vec::new(),
106 };
107 m.sig = author.sign(&m.bytes()).map_err(|e| SignError(e.to_string()))?;
108 Ok(m)
109 }
110
111 pub fn verify(&self) -> bool {
113 signed_by(&self.author, &self.key, &self.bytes(), &self.sig)
114 }
115}
116
117#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
119pub struct ChatItem {
120 pub message: ChatMessage,
122 pub reactions: BTreeMap<String, BTreeSet<UserId>>,
124 pub deleted: Option<(UserId, i64)>,
126 pub posted_ms: i64,
128 pub seq: u64,
130}
131
132impl ChatItem {
133 pub fn mentions(&self, user: &UserId) -> bool {
135 self.deleted.is_none() && self.message.mentions.contains(user)
136 }
137}
138
139#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
141pub struct ChatLog {
142 items: Vec<ChatItem>,
143 seq: u64,
144}
145
146impl ChatLog {
147 fn may(p: &Project, who: &UserId, perm: &Permission, now: i64) -> Result<(), ChatError> {
148 if p.can(who, perm.as_str(), &Ctx::at(now)) { Ok(()) } else { Err(ChatError::NotAllowed) }
149 }
150
151 fn bump(&mut self) -> u64 {
152 self.seq += 1;
153 self.seq
154 }
155
156 pub fn seq(&self) -> u64 {
158 self.seq
159 }
160
161 pub fn post(&mut self, p: &Project, perms: &ChatPerms, from: &UserId, m: ChatMessage, now: i64) -> Result<u64, ChatError> {
165 if &m.author != from {
166 return Err(ChatError::NotYours);
167 }
168 if &m.project != p.id() {
169 return Err(ChatError::WrongProject);
170 }
171 if !m.verify() {
172 return Err(ChatError::BadSignature);
173 }
174 Self::may(p, from, &perms.write, now)?;
175 if m.text.trim().is_empty() || m.text.len() > MAX_TEXT {
176 return Err(ChatError::BadText);
177 }
178 if self.items.iter().any(|i| i.message.id == m.id) {
179 return Err(ChatError::Duplicate);
180 }
181 if m.mentions.iter().any(|u| p.member(u).is_none()) {
182 return Err(ChatError::UnknownMention);
183 }
184 let seq = self.bump();
185 self.items.push(ChatItem { message: m, reactions: BTreeMap::new(), deleted: None, posted_ms: now, seq });
186 Ok(seq)
187 }
188
189 fn item_mut(&mut self, id: &RecordId) -> Result<&mut ChatItem, ChatError> {
190 self.items.iter_mut().find(|i| &i.message.id == id && i.deleted.is_none()).ok_or(ChatError::NoSuchMessage)
191 }
192
193 #[allow(clippy::too_many_arguments)]
195 pub fn react(
196 &mut self,
197 p: &Project,
198 perms: &ChatPerms,
199 who: &UserId,
200 id: &RecordId,
201 reaction: &str,
202 on: bool,
203 now: i64,
204 ) -> Result<u64, ChatError> {
205 Self::may(p, who, &perms.write, now)?;
206 if reaction.is_empty() || reaction.len() > MAX_REACTION || reaction.chars().any(char::is_whitespace) {
207 return Err(ChatError::BadText);
208 }
209 let item = self.item_mut(id)?;
210 if on && !item.reactions.contains_key(reaction) && item.reactions.len() >= MAX_REACTIONS {
211 return Err(ChatError::BadText);
212 }
213 let changed = if on {
214 item.reactions.entry(reaction.to_string()).or_default().insert(who.clone())
215 } else {
216 let r = item.reactions.get_mut(reaction).is_some_and(|s| s.remove(who));
217 item.reactions.retain(|_, s| !s.is_empty());
218 r
219 };
220 if !changed {
221 return Ok(self.seq);
222 }
223 let seq = self.bump();
224 self.item_mut(id)?.seq = seq;
225 Ok(seq)
226 }
227
228 pub fn delete(&mut self, p: &Project, perms: &ChatPerms, who: &UserId, id: &RecordId, now: i64) -> Result<u64, ChatError> {
230 let author = self.item_mut(id)?.message.author.clone();
231 if &author == who {
232 Self::may(p, who, &perms.write, now).or_else(|_| Self::may(p, who, &perms.manage, now))?;
233 } else {
234 Self::may(p, who, &perms.manage, now)?;
235 }
236 let seq = self.bump();
237 let item = self.item_mut(id)?;
238 item.message.text.clear();
239 item.message.mentions.clear();
240 item.reactions.clear();
241 item.deleted = Some((who.clone(), now));
242 item.seq = seq;
243 Ok(seq)
244 }
245
246 pub fn since(&self, p: &Project, perms: &ChatPerms, who: &UserId, since: u64, now: i64) -> Result<Vec<ChatItem>, ChatError> {
248 Self::may(p, who, &perms.read, now)?;
249 let mut v: Vec<ChatItem> = self.items.iter().filter(|i| i.seq > since).cloned().collect();
250 v.sort_by_key(|i| i.seq);
251 Ok(v)
252 }
253
254 pub fn items(&self) -> &[ChatItem] {
256 &self.items
257 }
258}
259
260pub fn merge(into: &mut Vec<ChatItem>, changed: Vec<ChatItem>) {
262 for c in changed {
263 match into.iter_mut().find(|i| i.message.id == c.message.id) {
264 Some(i) => *i = c,
265 None => into.push(c),
266 }
267 }
268 into.sort_by(|a, b| a.posted_ms.cmp(&b.posted_ms).then(a.message.id.cmp(&b.message.id)));
269}