forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

message.rs608 lines, 17.5 KiBHistoryRawDownload
1use common::{
2 constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT},
3 error::{Error, Field, Problem},
4 model::{CallLog, Edit, Id, Message, MessageHit, Quote, Reaction, Reply, SnippetMessage},
5 time::now_ms,
6};
7
8use super::{Connection, Reader, all, attachment, community, maybe, one, poll, run, snippet, user};
9use crate::error::{ServerError, ensure_with};
10
11const SEARCH_LIMIT: u32 = 200;
12const PAGE_LIMIT: u32 = MESSAGE_PAGE_LIMIT as u32;
13
14const SELECT: &str = "SELECT m.id, m.user_id, m.community_id, m.created_at, m.body, m.edited, m.reply_to, r.id, r.user_id, COALESCE(NULLIF(r.body, ''), (SELECT question FROM poll p WHERE p.message_id = r.id), r.body), (SELECT COUNT(*) FROM attachment a WHERE a.message_id = r.id AND a.snippet_position IS NULL), m.call, m.call_seconds, m.pinned, m.deleted_at IS NOT NULL, r.deleted_at IS NOT NULL FROM message m LEFT JOIN message r ON r.id = m.reply_to";
15
16fn row(r: &mut Reader) -> Result<Message, ServerError> {
17 let id = r.get()?;
18 let user_id = r.get()?;
19 let community_id = r.get()?;
20 let created_at = r.get()?;
21 let body = r.get()?;
22 let edited = r.get()?;
23 let reply_to: Option<Id> = r.get()?;
24 let reply_id: Option<Id> = r.get()?;
25 let reply_user_id: Option<Id> = r.get()?;
26 let reply_body: Option<String> = r.get()?;
27 let reply_attachments: u32 = r.get()?;
28 let call: Option<String> = r.get()?;
29 let call_seconds: u64 = r.get()?;
30 let pinned = r.get()?;
31 let deleted = r.get()?;
32 let reply_deleted: bool = r.get()?;
33
34 let reply = match (reply_id, reply_user_id, reply_body) {
35 (Some(message_id), Some(user_id), Some(body)) => {
36 let quote = Quote {
37 message_id,
38 user_id,
39 body: body.chars().take(MAXIMUM_QUOTE_LENGTH).collect(),
40 attachments: reply_attachments,
41 };
42 Some(if reply_deleted {
43 Reply::Deleted(Some(quote))
44 } else {
45 Reply::Quote(quote)
46 })
47 }
48 _ => reply_to.map(|_| Reply::Deleted(None)),
49 };
50
51 Ok(Message {
52 id,
53 user_id,
54 community_id,
55 created_at,
56 body,
57 attachments: Vec::new(),
58 reactions: Vec::new(),
59 reply,
60 snippet: None,
61 poll: None,
62 edited,
63 pinned,
64 deleted,
65 call: call.and_then(|text| CallLog::parse(&text, call_seconds)),
66 })
67}
68
69async fn reactions(message_id: Id, db: &Connection) -> Result<Vec<Reaction>, ServerError> {
70 let rows: Vec<(String, Id)> = all(
71 db,
72 "SELECT emoji, user_id FROM reaction WHERE message_id = ?1 ORDER BY emoji, user_id",
73 (message_id,),
74 |r| Ok((r.get()?, r.get()?)),
75 )
76 .await?;
77
78 let mut reactions: Vec<Reaction> = Vec::new();
79 for (emoji, user_id) in rows {
80 match reactions
81 .last_mut()
82 .filter(|reaction| reaction.emoji == emoji)
83 {
84 Some(reaction) => reaction.user_ids.push(user_id),
85 None => reactions.push(Reaction {
86 emoji,
87 user_ids: vec![user_id],
88 }),
89 }
90 }
91
92 Ok(reactions)
93}
94
95async fn insert(
96 user_id: Id,
97 community_id: Id,
98 body: &str,
99 reply_to: Option<Id>,
100 db: &Connection,
101) -> Result<Id, ServerError> {
102 one(
103 db,
104 "INSERT INTO message (community_id, user_id, created_at, body, reply_to) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id",
105 (community_id, user_id, now_ms(), body, reply_to),
106 |r| r.get(),
107 )
108 .await
109}
110
111pub async fn community_of(message_id: Id, db: &Connection) -> Result<Id, ServerError> {
112 one(
113 db,
114 "SELECT community_id FROM message WHERE id = ?1",
115 (message_id,),
116 |r| r.get(),
117 )
118 .await
119}
120
121pub async fn create_call_log(
122 community_id: Id,
123 user_id: Id,
124 call: CallLog,
125 db: &Connection,
126) -> Result<Message, ServerError> {
127 let id: Id = one(
128 db,
129 "INSERT INTO message (community_id, user_id, created_at, body, call, call_seconds) VALUES (?1, ?2, ?3, '', ?4, ?5) RETURNING id",
130 (community_id, user_id, now_ms(), call.as_str(), call.seconds()),
131 |r| r.get(),
132 )
133 .await?;
134
135 read(id, db).await
136}
137
138pub async fn create(
139 user_id: Id,
140 community_id: Id,
141 body: &str,
142 attachments: &[Id],
143 reply_to: Option<Id>,
144 db: &Connection,
145) -> Result<Message, ServerError> {
146 let id = insert(user_id, community_id, body, reply_to, db).await?;
147 attachment::bind(id, user_id, community_id, attachments, db).await?;
148
149 read(id, db).await
150}
151
152pub async fn read(id: Id, db: &Connection) -> Result<Message, ServerError> {
153 let message = read_any(id, db).await?;
154 ensure_with(!message.deleted, Error::NotFound)?;
155
156 Ok(message)
157}
158
159pub async fn read_any(id: Id, db: &Connection) -> Result<Message, ServerError> {
160 let mut message = one(db, &format!("{SELECT} WHERE m.id = ?1"), (id,), row).await?;
161 message.reactions = reactions(id, db).await?;
162 message.poll = poll::of(id, db).await?;
163 message.attachments = attachment::of_message(id, None, db).await?;
164 message.snippet = snippet::of(id, db).await?;
165
166 Ok(message)
167}
168
169async fn read_all(ids: Vec<Id>, db: &Connection) -> Result<Vec<Message>, ServerError> {
170 let mut messages = Vec::new();
171 for id in ids {
172 messages.push(read_any(id, db).await?);
173 }
174
175 Ok(messages)
176}
177
178pub async fn read_page(
179 community_id: Id,
180 before: Option<Id>,
181 with_deleted: bool,
182 db: &Connection,
183) -> Result<Vec<Message>, ServerError> {
184 let mut ids = all(
185 db,
186 "SELECT id FROM message WHERE community_id = ?1 AND (?2 IS NULL OR id < ?2) AND (?4 OR deleted_at IS NULL) ORDER BY id DESC LIMIT ?3",
187 (community_id, before, PAGE_LIMIT, with_deleted),
188 |r| r.get(),
189 )
190 .await?;
191 ids.reverse();
192
193 read_all(ids, db).await
194}
195
196pub async fn pinned(community_id: Id, db: &Connection) -> Result<Vec<Message>, ServerError> {
197 let ids = all(
198 db,
199 "SELECT id FROM message WHERE community_id = ?1 AND pinned = 1 AND deleted_at IS NULL ORDER BY id DESC",
200 (community_id,),
201 |r| r.get(),
202 )
203 .await?;
204
205 read_all(ids, db).await
206}
207
208pub async fn create_poll(
209 user_id: Id,
210 poll: &common::call::CreatePoll,
211 db: &Connection,
212) -> Result<Message, ServerError> {
213 let id = insert(user_id, poll.community_id, "", None, db).await?;
214 poll::create(id, poll, db).await?;
215
216 read(id, db).await
217}
218
219pub async fn vote(
220 message_id: Id,
221 user_id: Id,
222 positions: &[u32],
223 db: &Connection,
224) -> Result<Message, ServerError> {
225 poll::set_votes(message_id, user_id, positions, db).await?;
226
227 read(message_id, db).await
228}
229
230pub async fn close_poll(message_id: Id, db: &Connection) -> Result<Message, ServerError> {
231 poll::close(message_id, db).await?;
232
233 read(message_id, db).await
234}
235
236pub async fn react(
237 message_id: Id,
238 user_id: Id,
239 emoji: &str,
240 db: &Connection,
241) -> Result<Message, ServerError> {
242 let removed = run(
243 db,
244 "DELETE FROM reaction WHERE message_id = ?1 AND user_id = ?2 AND emoji = ?3",
245 (message_id, user_id, emoji),
246 )
247 .await?;
248 if removed == 0 {
249 run(
250 db,
251 "INSERT INTO reaction (message_id, user_id, emoji) VALUES (?1, ?2, ?3)",
252 (message_id, user_id, emoji),
253 )
254 .await?;
255 }
256
257 read(message_id, db).await
258}
259
260pub async fn pin(message_id: Id, pinned: bool, db: &Connection) -> Result<Message, ServerError> {
261 run(
262 db,
263 "UPDATE message SET pinned = ?2 WHERE id = ?1",
264 (message_id, pinned),
265 )
266 .await?;
267
268 read(message_id, db).await
269}
270
271pub async fn update(message_id: Id, body: &str, db: &Connection) -> Result<Message, ServerError> {
272 run(
273 db,
274 "INSERT INTO message_edit (message_id, body, edited_at) SELECT id, body, ?2 FROM message WHERE id = ?1 AND deleted_at IS NULL",
275 (message_id, now_ms()),
276 )
277 .await?;
278 ensure_with(
279 run(
280 db,
281 "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1 AND deleted_at IS NULL",
282 (message_id, body),
283 )
284 .await?
285 == 1,
286 Error::NotFound,
287 )?;
288
289 read(message_id, db).await
290}
291
292pub async fn delete(message_id: Id, db: &Connection) -> Result<(), ServerError> {
293 ensure_with(
294 run(
295 db,
296 "UPDATE message SET deleted_at = ?2, pinned = 0 WHERE id = ?1 AND deleted_at IS NULL",
297 (message_id, now_ms()),
298 )
299 .await?
300 == 1,
301 Error::NotFound,
302 )
303}
304
305pub async fn edits(message_id: Id, db: &Connection) -> Result<Vec<Edit>, ServerError> {
306 all(
307 db,
308 "SELECT body, edited_at FROM message_edit WHERE message_id = ?1 ORDER BY id DESC",
309 (message_id,),
310 |r| {
311 Ok(Edit {
312 body: r.get()?,
313 edited_at: r.get()?,
314 })
315 },
316 )
317 .await
318}
319
320pub async fn delete_where_user(user_id: Id, db: &Connection) -> Result<Vec<(Id, Id)>, ServerError> {
321 all(
322 db,
323 "DELETE FROM message WHERE user_id = ?1 RETURNING community_id, id",
324 (user_id,),
325 |r| Ok((r.get()?, r.get()?)),
326 )
327 .await
328}
329
330pub async fn delete_before(
331 cutoff: u64,
332 limit: u32,
333 db: &Connection,
334) -> Result<Vec<(Id, Id)>, ServerError> {
335 all(
336 db,
337 "DELETE FROM message WHERE id IN (SELECT id FROM message WHERE created_at < ?1 ORDER BY id LIMIT ?2) RETURNING community_id, id",
338 (cutoff, limit),
339 |r| Ok((r.get()?, r.get()?)),
340 )
341 .await
342}
343
344pub async fn search(
345 text: Option<&str>,
346 user_id: Option<Id>,
347 community_id: Option<Id>,
348 after_ms: Option<u64>,
349 before_ms: Option<u64>,
350 db: &Connection,
351) -> Result<Vec<MessageHit>, ServerError> {
352 let ids: Vec<Id> = all(
353 db,
354 "SELECT id FROM message WHERE deleted_at IS NULL AND (?1 IS NULL OR instr(lower(body), lower(?1)) > 0) AND (?2 IS NULL OR user_id = ?2) AND (?3 IS NULL OR community_id = ?3) AND (?4 IS NULL OR created_at >= ?4) AND (?5 IS NULL OR created_at < ?5) ORDER BY id DESC LIMIT ?6",
355 (
356 text,
357 user_id,
358 community_id,
359 after_ms.map(|ms| ms as i64),
360 before_ms.map(|ms| ms as i64),
361 SEARCH_LIMIT,
362 ),
363 |r| r.get(),
364 )
365 .await?;
366
367 let mut hits = Vec::new();
368 for id in ids {
369 let message = read(id, db).await?;
370 let community = community::label(message.community_id, db).await?;
371 let author = user::read(message.user_id, db).await?;
372 hits.push(MessageHit {
373 message,
374 community,
375 author: Some(author),
376 });
377 }
378
379 Ok(hits)
380}
381
382async fn origin(sources: &[Message], db: &Connection) -> Result<Option<String>, ServerError> {
383 let Some(first) = sources.first() else {
384 return Ok(None);
385 };
386 if sources
387 .iter()
388 .any(|source| source.community_id != first.community_id)
389 {
390 return Ok(None);
391 }
392
393 maybe(
394 db,
395 "SELECT name FROM community WHERE id = ?1 AND kind = ?2",
396 (first.community_id, community::Kind::Group.as_str()),
397 |r| r.get(),
398 )
399 .await
400}
401
402async fn entry(source: &Message, db: &Connection) -> Result<SnippetMessage, ServerError> {
403 let author = user::read(source.user_id, db).await?;
404
405 Ok(SnippetMessage {
406 id: source.id,
407 user_id: author.id,
408 username: author.username,
409 avatar_id: author.avatar_id,
410 created_at: source.created_at,
411 body: source.body.clone(),
412 attachments: source.attachments.clone(),
413 poll: source.poll.clone(),
414 })
415}
416
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418pub enum ForwardMode {
419 Copy,
420 Snippet,
421}
422
423pub async fn forward(
424 user_id: Id,
425 community_id: Id,
426 sources: &[Message],
427 mode: ForwardMode,
428 db: &Connection,
429) -> Result<Vec<Message>, ServerError> {
430 if mode == ForwardMode::Copy {
431 let mut created = Vec::new();
432 for source in sources {
433 let id = insert(user_id, community_id, &source.body, None, db).await?;
434 for attachment in &source.attachments {
435 attachment::copy_row(attachment.id, id, user_id, community_id, None, db).await?;
436 }
437 if let Some(inner) = &source.snippet {
438 snippet::write(
439 id,
440 user_id,
441 community_id,
442 inner.origin.as_deref(),
443 &inner.messages,
444 db,
445 )
446 .await?;
447 }
448 created.push(read(id, db).await?);
449 }
450
451 return Ok(created);
452 }
453
454 let mut entries = Vec::new();
455 for source in sources {
456 match &source.snippet {
457 Some(inner) => entries.extend(inner.messages.iter().cloned()),
458 None => entries.push(entry(source, db).await?),
459 }
460 }
461 if entries.len() > MAXIMUM_FORWARD_MESSAGES {
462 return Err(Error::Invalid {
463 field: Field::Forward,
464 problem: Problem::Length {
465 min: 1,
466 max: MAXIMUM_FORWARD_MESSAGES as u64,
467 actual: entries.len() as u64,
468 },
469 }
470 .into());
471 }
472
473 let origin = origin(sources, db).await?;
474 let id = insert(user_id, community_id, "", None, db).await?;
475 snippet::write(id, user_id, community_id, origin.as_deref(), &entries, db).await?;
476
477 Ok(vec![read(id, db).await?])
478}
479
480#[cfg(test)]
481mod tests {
482 use common::model::Role;
483
484 use common::model::Reply;
485
486 use super::{ForwardMode, create, delete, edits, forward, read, read_page, update};
487 use crate::{
488 db::{community, user},
489 test,
490 };
491
492 #[tokio::test]
493 async fn read_page_orders_and_pages() {
494 let db = test::db().await;
495 let conn = db.lock().await.unwrap();
496 let user_1 = user::create("Tahinli", "hash", Role::User, &conn)
497 .await
498 .unwrap();
499 let user_2 = user::create("Not Tahinli", "hash", Role::User, &conn)
500 .await
501 .unwrap();
502 let community = community::create(community::Kind::Group, "Tahinli", &conn)
503 .await
504 .unwrap();
505
506 let message_1 = create(user_1.id, community, "Tahinli", &[], None, &conn)
507 .await
508 .unwrap();
509 let message_2 = create(user_2.id, community, "Tahinli", &[], None, &conn)
510 .await
511 .unwrap();
512 let message_3 = create(user_2.id, community, "Tahinli", &[], None, &conn)
513 .await
514 .unwrap();
515
516 let newest = read_page(community, None, false, &conn).await.unwrap();
517 let older = read_page(community, Some(message_3.id), false, &conn)
518 .await
519 .unwrap();
520
521 assert_eq!(
522 vec![message_1.clone(), message_2.clone(), message_3],
523 newest
524 );
525 assert_eq!(vec![message_1, message_2], older);
526 }
527
528 #[tokio::test]
529 async fn deleted_and_edited_stay_for_builders_only() {
530 let db = test::db().await;
531 let conn = db.lock().await.unwrap();
532 let author = user::create("Tahinli", "hash", Role::User, &conn)
533 .await
534 .unwrap();
535 let community = community::create(community::Kind::Group, "Tahinli", &conn)
536 .await
537 .unwrap();
538 let original = create(author.id, community, "first", &[], None, &conn)
539 .await
540 .unwrap();
541 let reply = create(author.id, community, "reply", &[], Some(original.id), &conn)
542 .await
543 .unwrap();
544
545 update(original.id, "second", &conn).await.unwrap();
546 delete(original.id, &conn).await.unwrap();
547
548 assert!(read(original.id, &conn).await.is_err());
549 assert!(delete(original.id, &conn).await.is_err());
550 assert_eq!(
551 vec![reply.id],
552 read_page(community, None, false, &conn)
553 .await
554 .unwrap()
555 .iter()
556 .map(|message| message.id)
557 .collect::<Vec<_>>()
558 );
559 let all = read_page(community, None, true, &conn).await.unwrap();
560 assert!(all[0].deleted && all[0].body == "second");
561 assert!(
562 matches!(&all[1].reply, Some(Reply::Deleted(Some(quote))) if quote.body == "second")
563 );
564 let mut redacted = all[1].reply.clone().unwrap();
565 redacted.redact();
566 assert_eq!(Reply::Deleted(None), redacted);
567 assert_eq!(
568 vec!["first".to_string()],
569 edits(original.id, &conn)
570 .await
571 .unwrap()
572 .into_iter()
573 .map(|edit| edit.body)
574 .collect::<Vec<_>>()
575 );
576 }
577
578 #[tokio::test]
579 async fn forward_two_as_snippet() {
580 let db = test::db().await;
581 let conn = db.lock().await.unwrap();
582 let user = user::create("Tahinli", "hash", Role::User, &conn)
583 .await
584 .unwrap();
585 let community = community::create(community::Kind::Group, "Tahinli", &conn)
586 .await
587 .unwrap();
588 let first = create(user.id, community, "First", &[], None, &conn)
589 .await
590 .unwrap();
591 let second = create(user.id, community, "Second", &[], None, &conn)
592 .await
593 .unwrap();
594
595 let created = forward(
596 user.id,
597 community,
598 &[first, second],
599 ForwardMode::Snippet,
600 &conn,
601 )
602 .await
603 .unwrap();
604
605 assert_eq!(1, created.len());
606 assert_eq!(2, created[0].snippet.as_ref().unwrap().messages.len());
607 }
608}