forge
Explore
Log in

Don't you dare go Hollow

Builders see deleted messages and edit history

Browse files at this commit

09df64d0ccb7bd845a036dd950075672880d7e89Ahmet Kaan GümüşParent: a446307
  • feat
    • builders see deleted messages and edit history
    • delete is soft (deleted_at), edits keep previous bodies (message_edit, ListEdits builder-only), others get deleted messages hidden and reply quotes redacted
    • retention and account deletion stay hard
Show full message
✨ feat: builders see deleted messages and edit history; delete is soft (deleted_at), edits keep previous bodies (message_edit, ListEdits builder-only), others get deleted messages hidden and reply quotes redacted; retention and account deletion stay hard
crates/client/lang/en/chat.txtmodified+1 -0
@@ -49,6 +49,7 @@ stats = Connection stats
49 stats_hide = Hide connection stats49 stats_hide = Hide connection stats
50 new = New50 new = New
51 edited = (edited)51 edited = (edited)
52+deleted = (deleted)
52 calls = {count} calls53 calls = {count} calls
53 call_started_mine = You started a call54 call_started_mine = You started a call
54 call_started = {name} started a call55 call_started = {name} started a call
crates/client/lang/tr/chat.txtmodified+1 -0
@@ -49,6 +49,7 @@ stats = Bağlantı istatistikleri
49 stats_hide = Bağlantı istatistiklerini gizle49 stats_hide = Bağlantı istatistiklerini gizle
50 new = Yeni50 new = Yeni
51 edited = (düzenlendi)51 edited = (düzenlendi)
52+deleted = (silindi)
52 calls = {count} arama53 calls = {count} arama
53 call_started_mine = Bir arama başlattın54 call_started_mine = Bir arama başlattın
54 call_started = {name} bir arama başlattı55 call_started = {name} bir arama başlattı
crates/client/src/gui.rsmodified+2 -1
@@ -1014,8 +1014,9 @@ impl Yumush {
1014 }1014 }
1015 _ => {}1015 _ => {}
1016 }1016 }
1017+ let builder = self.is_builder();
1017 self.chat1018 self.chat
1018- .apply_event(event, self.user.as_ref().map(|user| user.id));1019+ .apply_event(event, self.user.as_ref().map(|user| user.id), builder);
1019 self.request_authors(cx);1020 self.request_authors(cx);
1020 self.request_social_avatars(cx);1021 self.request_social_avatars(cx);
1021 self.request_media(cx);1022 self.request_media(cx);
crates/client/src/gui/chat.rsmodified+57 -17
@@ -35,14 +35,14 @@ use crate::share::session::ShareSample;
35 use common::{35 use common::{
36 call::{36 call::{
37 CreateCommunity, DeclineCall, DeleteMessage, GetUser, LeaveCommunity, ListBans,37 CreateCommunity, DeclineCall, DeleteMessage, GetUser, LeaveCommunity, ListBans,
38- ListCommunities, ListMembers, ListMessages, ListPins, ListUnreads, ListVoiceParticipants,38+ ListCommunities, ListEdits, ListMembers, ListMessages, ListPins, ListUnreads,
39- PushStats, SearchCommunity, WatchCommunity,39+ ListVoiceParticipants, PushStats, SearchCommunity, WatchCommunity,
40 },40 },
41 constant::MESSAGE_PAGE_LIMIT,41 constant::MESSAGE_PAGE_LIMIT,
42 event::Event,42 event::Event,
43 model::{43 model::{
44 Account, AdminActionKind, AdminLogEntry, AttachmentInfo, Ban, BanScope, CallLog, Community,44 Account, AdminActionKind, AdminLogEntry, AttachmentInfo, Ban, BanScope, CallLog, Community,
45- CommunityKind, CommunitySummary, CommunityUsage, DayStat, Friends, Id, Invitation,45+ CommunityKind, CommunitySummary, CommunityUsage, DayStat, Edit, Friends, Id, Invitation,
46 InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Reply, Report,46 InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Reply, Report,
47 ReportStatus, ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions,47 ReportStatus, ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions,
48 },48 },
@@ -142,6 +142,7 @@ pub struct Chat {
142 unseen: u32,142 unseen: u32,
143 pub(super) muted: HashSet<Id>,143 pub(super) muted: HashSet<Id>,
144 pub(super) pinned: HashSet<Id>,144 pub(super) pinned: HashSet<Id>,
145+ pub(super) edits: HashMap<Id, Vec<Edit>>,
145 pub(super) message_input: Entity<TextareaState>,146 pub(super) message_input: Entity<TextareaState>,
146 pub(super) search_input: Entity<InputState>,147 pub(super) search_input: Entity<InputState>,
147 pub(super) friends_open: bool,148 pub(super) friends_open: bool,
@@ -433,6 +434,7 @@ impl Chat {
433 unseen: 0,434 unseen: 0,
434 muted: HashSet::new(),435 muted: HashSet::new(),
435 pinned: HashSet::new(),436 pinned: HashSet::new(),
437+ edits: HashMap::new(),
436 message_input,438 message_input,
437 search_input,439 search_input,
438 friends_open: false,440 friends_open: false,
@@ -642,7 +644,7 @@ impl Chat {
642 (remaining > 0).then(|| remaining.div_ceil(1000))644 (remaining > 0).then(|| remaining.div_ceil(1000))
643 }645 }
644 646
645- pub fn apply_event(&mut self, event: Event, me: Option<Id>) {647+ pub fn apply_event(&mut self, event: Event, me: Option<Id>, builder: bool) {
646 match event {648 match event {
647 Event::MessageCreated(message) => {649 Event::MessageCreated(message) => {
648 if let Some(users) = self.typing.get_mut(&message.community_id) {650 if let Some(users) = self.typing.get_mut(&message.community_id) {
@@ -680,7 +682,7 @@ impl Chat {
680 Event::MessagesDeleted { community_id, ids } => {682 Event::MessagesDeleted { community_id, ids } => {
681 if self.is_selected(community_id) {683 if self.is_selected(community_id) {
682 for id in ids {684 for id in ids {
683- self.forget_message(id);685+ self.remove_message(id, builder);
684 }686 }
685 }687 }
686 }688 }
@@ -884,17 +886,26 @@ impl Chat {
884 })886 })
885 }887 }
886 888
887- fn forget_message(&mut self, message_id: Id) {889+ fn remove_message(&mut self, message_id: Id, builder: bool) {
888- self.messages.retain(|existing| existing.id != message_id);890+ if builder {
889- for message in &mut self.messages {891+ if let Some(message) = self
890- if message892+ .messages
891- .reply893+ .iter_mut()
892- .as_ref()894+ .find(|existing| existing.id == message_id)
893- .and_then(Reply::quote)
894- .is_some_and(|quote| quote.message_id == message_id)
895 {895 {
896- message.reply = Some(Reply::Deleted);896+ message.deleted = true;
897+ message.pinned = false;
897 }898 }
899+ } else {
900+ self.messages.retain(|existing| existing.id != message_id);
901+ }
902+ for message in &mut self.messages {
903+ message.reply = match message.reply.take() {
904+ Some(Reply::Quote(quote)) if quote.message_id == message_id => {
905+ Some(Reply::Deleted(builder.then_some(quote)))
906+ }
907+ other => other,
908+ };
898 }909 }
899 910
900 match &mut self.composer {911 match &mut self.composer {
@@ -2472,6 +2483,24 @@ impl Yumush {
2472 });2483 });
2473 }2484 }
2474 2485
2486+ pub(super) fn load_edits(&self, message_id: Id, cx: &mut Context<Self>) {
2487+ let network = self.network.clone();
2488+ cx.spawn(async move |this, cx| {
2489+ let edits = match network.call(ListEdits { message_id }).await {
2490+ Ok(edits) => edits,
2491+ Err(error) => {
2492+ tracing::warn!("list edits failed: {error}");
2493+ return;
2494+ }
2495+ };
2496+ let _ = this.update(cx, |yumush, cx| {
2497+ yumush.chat.edits.insert(message_id, edits);
2498+ cx.notify();
2499+ });
2500+ })
2501+ .detach();
2502+ }
2503+
2475 pub(super) fn leave_community(2504 pub(super) fn leave_community(
2476 &self,2505 &self,
2477 community_id: Id,2506 community_id: Id,
@@ -3556,6 +3585,7 @@ fn render_message(
3556 palette,3585 palette,
3557 );3586 );
3558 }3587 }
3588+ let builder = me.is_some_and(|me| permission::is_builder(me.role));
3559 let author = chat.author(message.user_id);3589 let author = chat.author(message.user_id);
3560 let username = author.map_or(w().chat.unknown, |user| user.username.as_str());3590 let username = author.map_or(w().chat.unknown, |user| user.username.as_str());
3561 let name = div().flex().items_center().gap(px(space::SM)).child(3591 let name = div().flex().items_center().gap(px(space::SM)).child(
@@ -3598,6 +3628,7 @@ fn render_message(
3598 .min_w_0()3628 .min_w_0()
3599 .hover(|style| style.bg(palette.hover))3629 .hover(|style| style.bg(palette.hover))
3600 .when(chat.engaged(message.id), |this| this.bg(palette.hover))3630 .when(chat.engaged(message.id), |this| this.bg(palette.hover))
3631+ .when(message.deleted, |this| this.text_color(palette.tokens.faint()))
3601 .when(first && spaced && !selecting, |this| this.mt(px(space::LG)))3632 .when(first && spaced && !selecting, |this| this.mt(px(space::LG)))
3602 .when(highlighted, |this| this.bg(palette.tokens.press()))3633 .when(highlighted, |this| this.bg(palette.tokens.press()))
3603 .when(mentioned, |this| {3634 .when(mentioned, |this| {
@@ -3681,12 +3712,21 @@ fn render_message(
3681 .selectable(true),3712 .selectable(true),
3682 ),3713 ),
3683 )3714 )
3684- .when(message.edited, |this| {3715+ .when(message.edited || message.deleted, |this| {
3685 this.child(3716 this.child(
3686 div()3717 div()
3718+ .flex()
3719+ .gap(px(space::SM))
3687 .text_size(text(text::CAPTION))3720 .text_size(text(text::CAPTION))
3688 .text_color(palette.muted)3721 .text_color(palette.muted)
3689- .child(w().chat.edited),3722+ .children(message.edited.then(|| {
3723+ message_actions::edited_mark(
3724+ message, builder, entity, palette,
3725+ )
3726+ }))
3727+ .children(
3728+ message.deleted.then(|| w().chat.deleted),
3729+ ),
3690 )3730 )
3691 }),3731 }),
3692 )3732 )
@@ -3715,7 +3755,7 @@ fn render_message(
3715 ),3755 ),
3716 )3756 )
3717 .children(message.pinned.then(|| message_actions::pin_mark(palette)))3757 .children(message.pinned.then(|| message_actions::pin_mark(palette)))
3718- .children((!selecting).then(|| {3758+ .children((!selecting && !message.deleted).then(|| {
3719 div()3759 div()
3720 .absolute()3760 .absolute()
3721 .right_0()3761 .right_0()
crates/client/src/gui/message_actions.rsmodified+69 -6
@@ -7,8 +7,8 @@ use common::{
7 model::{Message, Reply, User},7 model::{Message, Reply, User},
8 };8 };
9 use gpui_kit::{9 use gpui_kit::{
10- Anchor, Context, Div, Entity, Focusable as _, FontWeight, InteractiveElement, IntoElement,10+ Anchor, AnyElement, Context, Div, Entity, Focusable as _, FontWeight, InteractiveElement,
11- ParentElement, Stateful, StatefulInteractiveElement as _, Styled, Window,11+ IntoElement, ParentElement, Stateful, StatefulInteractiveElement as _, Styled, Window,
12 assets::IconName,12 assets::IconName,
13 component::{13 component::{
14 input::InputState,14 input::InputState,
@@ -20,7 +20,7 @@ use gpui_kit::{
20 };20 };
21 21
22 use super::{22 use super::{
23- CLOCK, Palette, Yumush, avatar,23+ CLOCK, Palette, Trigger, Yumush, avatar,
24 chat::{Chat, ReportTarget},24 chat::{Chat, ReportTarget},
25 clickable,25 clickable,
26 composer::trigger_icon,26 composer::trigger_icon,
@@ -168,10 +168,14 @@ pub fn quote_line(
168 .border_color(palette.border)168 .border_color(palette.border)
169 .text_size(text(text::CAPTION))169 .text_size(text(text::CAPTION))
170 .text_color(palette.muted);170 .text_color(palette.muted);
171- let quote = match message.reply.as_ref()? {171+ let (quote, deleted) = match message.reply.as_ref()? {
172- Reply::Quote(quote) => quote,172+ Reply::Quote(quote) => (quote, false),
173- Reply::Deleted => return Some(frame.italic().child(w().message_actions.deleted)),173+ Reply::Deleted(Some(quote)) => (quote, true),
174+ Reply::Deleted(None) => {
175+ return Some(frame.italic().child(w().message_actions.deleted));
176+ }
174 };177 };
178+ let frame = frame.when(deleted, |this| this.italic());
175 let author = chat.author(quote.user_id);179 let author = chat.author(quote.user_id);
176 let target = quote.message_id;180 let target = quote.message_id;
177 let entity = entity.clone();181 let entity = entity.clone();
@@ -205,6 +209,65 @@ pub fn quote_line(
205 )209 )
206 }210 }
207 211
212+pub fn edited_mark(
213+ message: &Message,
214+ builder: bool,
215+ entity: &Entity<Yumush>,
216+ palette: Palette,
217+) -> AnyElement {
218+ let message_id = message.id;
219+ if !builder {
220+ return w().chat.edited.into_any_element();
221+ }
222+ let loading = entity.clone();
223+ let content = entity.clone();
224+
225+ Popover::new(format!("edits_{message_id}"))
226+ .anchor(Anchor::BottomLeft)
227+ .on_open_change(move |open, _, cx| {
228+ if *open {
229+ loading.update(cx, |yumush, cx| yumush.load_edits(message_id, cx));
230+ }
231+ })
232+ .appearance(false)
233+ .trigger(Trigger::new(
234+ div()
235+ .id(format!("edited_{message_id}"))
236+ .cursor_pointer()
237+ .child(w().chat.edited),
238+ ))
239+ .content(move |_, _, cx| {
240+ let mut edits = content
241+ .read(cx)
242+ .chat
243+ .edits
244+ .get(&message_id)
245+ .cloned()
246+ .unwrap_or_default();
247+ edits.sort_by_key(|edit| std::cmp::Reverse(edit.edited_at));
248+ panel(palette)
249+ .flex()
250+ .flex_col()
251+ .gap(px(space::XS))
252+ .p(px(space::SM))
253+ .max_w(px(size::PAGE))
254+ .children(edits.into_iter().map(|edit| {
255+ div()
256+ .flex()
257+ .gap(px(space::SM))
258+ .text_size(text(text::CAPTION))
259+ .child(
260+ div()
261+ .flex_shrink_0()
262+ .text_color(palette.muted)
263+ .child(millis_time(edit.edited_at, CLOCK)),
264+ )
265+ .child(div().min_w_0().child(edit.body))
266+ }))
267+ })
268+ .into_any_element()
269+}
270+
208 pub fn pin_mark(palette: Palette) -> impl IntoElement {271 pub fn pin_mark(palette: Palette) -> impl IntoElement {
209 div()272 div()
210 .flex_shrink_0()273 .flex_shrink_0()
crates/common/src/call.rsmodified+9 -3
@@ -6,9 +6,9 @@ use crate::{
6 model::Hue,6 model::Hue,
7 model::{7 model::{
8 Account, AdminActionKind, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope,8 Account, AdminActionKind, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope,
9- Community, CommunitySummary, CommunityUsage, DayStat, Friends, Id, Invitation, InviteCode,9+ Community, CommunitySummary, CommunityUsage, DayStat, Edit, Friends, Id, Invitation,
10- LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus,10+ InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report,
11- Role, ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,11+ ReportStatus, Role, ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
12 },12 },
13 share::{Codec, Kind, Quality, Share, Source},13 share::{Codec, Kind, Quality, Share, Source},
14 stats::Stats,14 stats::Stats,
@@ -222,6 +222,11 @@ pub struct DeleteMessage {
222 pub message_id: Id,222 pub message_id: Id,
223 }223 }
224 224
225+#[derive(Debug, Clone, Encode, Decode)]
226+pub struct ListEdits {
227+ pub message_id: Id,
228+}
229+
225 #[derive(Debug, Clone, Encode, Decode)]230 #[derive(Debug, Clone, Encode, Decode)]
226 pub struct CreatePoll {231 pub struct CreatePoll {
227 pub community_id: Id,232 pub community_id: Id,
@@ -686,6 +691,7 @@ calls! {
686 ForwardMessages: User -> Vec<Message>, |c| validate_forward(c.message_ids.len());691 ForwardMessages: User -> Vec<Message>, |c| validate_forward(c.message_ids.len());
687 UpdateMessage: User -> Message, |c| validate_new_message(&c.body, 0, MAXIMUM_MESSAGE_LENGTH);692 UpdateMessage: User -> Message, |c| validate_new_message(&c.body, 0, MAXIMUM_MESSAGE_LENGTH);
688 DeleteMessage: User -> ();693 DeleteMessage: User -> ();
694+ ListEdits: User -> Vec<Edit>;
689 CreatePoll: User -> Message, |c| validate_poll(&c.question, &c.options);695 CreatePoll: User -> Message, |c| validate_poll(&c.question, &c.options);
690 Vote: User -> ();696 Vote: User -> ();
691 ClosePoll: User -> ();697 ClosePoll: User -> ();
crates/common/src/model.rsmodified+15 -2
@@ -532,16 +532,28 @@ pub struct Quote {
532 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]532 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
533 pub enum Reply {533 pub enum Reply {
534 Quote(Quote),534 Quote(Quote),
535- Deleted,535+ Deleted(Option<Quote>),
536 }536 }
537 537
538 impl Reply {538 impl Reply {
539 pub fn quote(&self) -> Option<&Quote> {539 pub fn quote(&self) -> Option<&Quote> {
540 match self {540 match self {
541 Reply::Quote(quote) => Some(quote),541 Reply::Quote(quote) => Some(quote),
542- Reply::Deleted => None,542+ Reply::Deleted(_) => None,
543 }543 }
544 }544 }
545+
546+ pub fn redact(&mut self) {
547+ if let Reply::Deleted(quote) = self {
548+ *quote = None;
549+ }
550+ }
551+}
552+
553+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
554+pub struct Edit {
555+ pub body: String,
556+ pub edited_at: u64,
545 }557 }
546 558
547 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]559 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
@@ -600,6 +612,7 @@ pub struct Message {
600 pub poll: Option<Poll>,612 pub poll: Option<Poll>,
601 pub edited: bool,613 pub edited: bool,
602 pub pinned: bool,614 pub pinned: bool,
615+ pub deleted: bool,
603 pub call: Option<CallLog>,616 pub call: Option<CallLog>,
604 }617 }
605 618
crates/server/src/call/message.rsmodified+35 -5
@@ -1,11 +1,12 @@
1 use common::{1 use common::{
2 call::{2 call::{
3- ClosePoll, CreateMessage, CreatePoll, DeleteMessage, ForwardMessages, ListMessages,3+ ClosePoll, CreateMessage, CreatePoll, DeleteMessage, ForwardMessages, ListEdits,
4- ListPins, ListUnreads, MarkRead, MyVotes, Pin, React, Typing, UpdateMessage, Vote,4+ ListMessages, ListPins, ListUnreads, MarkRead, MyVotes, Pin, React, Typing, UpdateMessage,
5+ Vote,
5 },6 },
6 error::Error,7 error::Error,
7 event::Event,8 event::Event,
8- model::{AdminAction, Id, LogAction, Message, ServerSettings, Unread, User},9+ model::{AdminAction, Edit, Id, LogAction, Message, ServerSettings, Unread, User},
9 permission,10 permission,
10 validate::{validate_new_message, validate_vote},11 validate::{validate_new_message, validate_vote},
11 };12 };
@@ -30,6 +31,18 @@ fn limit_messages(me: &User, settings: &ServerSettings, cx: &Cx<'_>) -> Result<(
30 .allow(&me.id.to_string(), settings.messages_per_minute)?)31 .allow(&me.id.to_string(), settings.messages_per_minute)?)
31 }32 }
32 33
34+fn redact_replies(messages: &mut [Message], me: &User) {
35+ if permission::is_builder(me.role) {
36+ return;
37+ }
38+
39+ for message in messages {
40+ if let Some(reply) = &mut message.reply {
41+ reply.redact();
42+ }
43+ }
44+}
45+
33 impl Handle for CreateMessage {46 impl Handle for CreateMessage {
34 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> {47 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> {
35 let me = me.user()?;48 let me = me.user()?;
@@ -253,7 +266,10 @@ impl Handle for ListPins {
253 let me = me.user()?;266 let me = me.user()?;
254 allowed(&me, self.community_id, cx.db, permission::can_read).await?;267 allowed(&me, self.community_id, cx.db, permission::can_read).await?;
255 268
256- db::message::pinned(self.community_id, cx.db).await269+ let mut pins = db::message::pinned(self.community_id, cx.db).await?;
270+ redact_replies(&mut pins, &me);
271+
272+ Ok(pins)
257 }273 }
258 }274 }
259 275
@@ -262,7 +278,21 @@ impl Handle for ListMessages {
262 let me = me.user()?;278 let me = me.user()?;
263 allowed(&me, self.community_id, cx.db, permission::can_read).await?;279 allowed(&me, self.community_id, cx.db, permission::can_read).await?;
264 280
265- db::message::read_page(self.community_id, self.before, cx.db).await281+ let builder = permission::is_builder(me.role);
282+ let mut messages =
283+ db::message::read_page(self.community_id, self.before, builder, cx.db).await?;
284+ redact_replies(&mut messages, &me);
285+
286+ Ok(messages)
287+ }
288+}
289+
290+impl Handle for ListEdits {
291+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Edit>, ServerError> {
292+ let me = me.user()?;
293+ ensure(permission::is_builder(me.role))?;
294+
295+ db::message::edits(self.message_id, cx.db).await
266 }296 }
267 }297 }
268 298
crates/server/src/call/mod.rsmodified+1 -0
@@ -144,6 +144,7 @@ pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> {
144 Request::React(call) => serve(call, cx).await,144 Request::React(call) => serve(call, cx).await,
145 Request::Pin(call) => serve(call, cx).await,145 Request::Pin(call) => serve(call, cx).await,
146 Request::ListPins(call) => serve(call, cx).await,146 Request::ListPins(call) => serve(call, cx).await,
147+ Request::ListEdits(call) => serve(call, cx).await,
147 Request::ListMessages(call) => serve(call, cx).await,148 Request::ListMessages(call) => serve(call, cx).await,
148 Request::ListUnreads(call) => serve(call, cx).await,149 Request::ListUnreads(call) => serve(call, cx).await,
149 Request::MarkRead(call) => serve(call, cx).await,150 Request::MarkRead(call) => serve(call, cx).await,
crates/server/src/db/community.rsmodified+1 -1
@@ -73,7 +73,7 @@ pub async fn create(kind: Kind, name: &str, db: &Connection) -> Result<Id, Serve
73 pub async fn communities_of(user_id: Id, db: &Connection) -> Result<Vec<Community>, ServerError> {73 pub async fn communities_of(user_id: Id, db: &Connection) -> Result<Vec<Community>, ServerError> {
74 let ids: Vec<Id> = all(74 let ids: Vec<Id> = all(
75 db,75 db,
76- "SELECT m.community_id FROM member m JOIN community c ON c.id = m.community_id WHERE m.user_id = ?1 AND (c.kind != 'direct' OR EXISTS (SELECT 1 FROM message WHERE message.community_id = c.id)) ORDER BY m.community_id",76+ "SELECT m.community_id FROM member m JOIN community c ON c.id = m.community_id WHERE m.user_id = ?1 AND (c.kind != 'direct' OR EXISTS (SELECT 1 FROM message WHERE message.community_id = c.id AND message.deleted_at IS NULL)) ORDER BY m.community_id",
77 (user_id,),77 (user_id,),
78 |r| r.get(),78 |r| r.get(),
79 )79 )
crates/server/src/db/member.rsmodified+2 -2
@@ -83,7 +83,7 @@ pub async fn unreads(
83 ) -> Result<Vec<Unread>, ServerError> {83 ) -> Result<Vec<Unread>, ServerError> {
84 let mut unreads = all(84 let mut unreads = all(
85 db,85 db,
86- "SELECT m.community_id, (SELECT COUNT(*) FROM message WHERE message.community_id = m.community_id AND message.user_id != ?1 AND (m.last_read IS NULL OR message.id > m.last_read)), m.last_read FROM member m WHERE m.user_id = ?1",86+ "SELECT m.community_id, (SELECT COUNT(*) FROM message WHERE message.community_id = m.community_id AND message.user_id != ?1 AND message.deleted_at IS NULL AND (m.last_read IS NULL OR message.id > m.last_read)), m.last_read FROM member m WHERE m.user_id = ?1",
87 (user_id,),87 (user_id,),
88 |r| {88 |r| {
89 Ok(Unread {89 Ok(Unread {
@@ -99,7 +99,7 @@ pub async fn unreads(
99 let needle = format!("@{}", username.to_lowercase());99 let needle = format!("@{}", username.to_lowercase());
100 let bodies: Vec<(Id, String)> = all(100 let bodies: Vec<(Id, String)> = all(
101 db,101 db,
102- "SELECT message.community_id, message.body FROM message JOIN member ON member.community_id = message.community_id AND member.user_id = ?1 WHERE message.user_id != ?1 AND (member.last_read IS NULL OR message.id > member.last_read) AND instr(lower(message.body), ?2) > 0",102+ "SELECT message.community_id, message.body FROM message JOIN member ON member.community_id = message.community_id AND member.user_id = ?1 WHERE message.user_id != ?1 AND message.deleted_at IS NULL AND (member.last_read IS NULL OR message.id > member.last_read) AND instr(lower(message.body), ?2) > 0",
103 (user_id, needle.as_str()),103 (user_id, needle.as_str()),
104 |r| Ok((r.get()?, r.get()?)),104 |r| Ok((r.get()?, r.get()?)),
105 )105 )
crates/server/src/db/message.rsmodified+116 -19
@@ -1,7 +1,7 @@
1 use common::{1 use common::{
2 constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT},2 constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT},
3 error::{Error, Field, Problem},3 error::{Error, Field, Problem},
4- model::{CallLog, Id, Message, MessageHit, Quote, Reaction, Reply, SnippetMessage},4+ model::{CallLog, Edit, Id, Message, MessageHit, Quote, Reaction, Reply, SnippetMessage},
5 time::now_ms,5 time::now_ms,
6 };6 };
7 7
@@ -11,7 +11,7 @@ use crate::error::{ServerError, ensure_with};
11 const SEARCH_LIMIT: u32 = 200;11 const SEARCH_LIMIT: u32 = 200;
12 const PAGE_LIMIT: u32 = MESSAGE_PAGE_LIMIT as u32;12 const PAGE_LIMIT: u32 = MESSAGE_PAGE_LIMIT as u32;
13 13
14-const 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 FROM message m LEFT JOIN message r ON r.id = m.reply_to";14+const 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 15
16 fn row(r: &mut Reader) -> Result<Message, ServerError> {16 fn row(r: &mut Reader) -> Result<Message, ServerError> {
17 let id = r.get()?;17 let id = r.get()?;
@@ -28,15 +28,24 @@ fn row(r: &mut Reader) -> Result<Message, ServerError> {
28 let call: Option<String> = r.get()?;28 let call: Option<String> = r.get()?;
29 let call_seconds: u64 = r.get()?;29 let call_seconds: u64 = r.get()?;
30 let pinned = r.get()?;30 let pinned = r.get()?;
31+ let deleted = r.get()?;
32+ let reply_deleted: bool = r.get()?;
31 33
32 let reply = match (reply_id, reply_user_id, reply_body) {34 let reply = match (reply_id, reply_user_id, reply_body) {
33- (Some(message_id), Some(user_id), Some(body)) => Some(Reply::Quote(Quote {35+ (Some(message_id), Some(user_id), Some(body)) => {
34- message_id,36+ let quote = Quote {
35- user_id,37+ message_id,
36- body: body.chars().take(MAXIMUM_QUOTE_LENGTH).collect(),38+ user_id,
37- attachments: reply_attachments,39+ body: body.chars().take(MAXIMUM_QUOTE_LENGTH).collect(),
38- })),40+ attachments: reply_attachments,
39- _ => reply_to.map(|_| Reply::Deleted),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)),
40 };49 };
41 50
42 Ok(Message {51 Ok(Message {
@@ -52,6 +61,7 @@ fn row(r: &mut Reader) -> Result<Message, ServerError> {
52 poll: None,61 poll: None,
53 edited,62 edited,
54 pinned,63 pinned,
64+ deleted,
55 call: call.and_then(|text| CallLog::parse(&text, call_seconds)),65 call: call.and_then(|text| CallLog::parse(&text, call_seconds)),
56 })66 })
57 }67 }
@@ -140,6 +150,13 @@ pub async fn create(
140 }150 }
141 151
142 pub async fn read(id: Id, db: &Connection) -> Result<Message, ServerError> {152 pub 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+
159+pub async fn read_any(id: Id, db: &Connection) -> Result<Message, ServerError> {
143 let mut message = one(db, &format!("{SELECT} WHERE m.id = ?1"), (id,), row).await?;160 let mut message = one(db, &format!("{SELECT} WHERE m.id = ?1"), (id,), row).await?;
144 message.reactions = reactions(id, db).await?;161 message.reactions = reactions(id, db).await?;
145 message.poll = poll::of(id, db).await?;162 message.poll = poll::of(id, db).await?;
@@ -152,7 +169,7 @@ pub async fn read(id: Id, db: &Connection) -> Result<Message, ServerError> {
152 async fn read_all(ids: Vec<Id>, db: &Connection) -> Result<Vec<Message>, ServerError> {169 async fn read_all(ids: Vec<Id>, db: &Connection) -> Result<Vec<Message>, ServerError> {
153 let mut messages = Vec::new();170 let mut messages = Vec::new();
154 for id in ids {171 for id in ids {
155- messages.push(read(id, db).await?);172+ messages.push(read_any(id, db).await?);
156 }173 }
157 174
158 Ok(messages)175 Ok(messages)
@@ -161,12 +178,13 @@ async fn read_all(ids: Vec<Id>, db: &Connection) -> Result<Vec<Message>, ServerE
161 pub async fn read_page(178 pub async fn read_page(
162 community_id: Id,179 community_id: Id,
163 before: Option<Id>,180 before: Option<Id>,
181+ with_deleted: bool,
164 db: &Connection,182 db: &Connection,
165 ) -> Result<Vec<Message>, ServerError> {183 ) -> Result<Vec<Message>, ServerError> {
166 let mut ids = all(184 let mut ids = all(
167 db,185 db,
168- "SELECT id FROM message WHERE community_id = ?1 AND (?2 IS NULL OR id < ?2) ORDER BY id DESC LIMIT ?3",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",
169- (community_id, before, PAGE_LIMIT),187+ (community_id, before, PAGE_LIMIT, with_deleted),
170 |r| r.get(),188 |r| r.get(),
171 )189 )
172 .await?;190 .await?;
@@ -178,7 +196,7 @@ pub async fn read_page(
178 pub async fn pinned(community_id: Id, db: &Connection) -> Result<Vec<Message>, ServerError> {196 pub async fn pinned(community_id: Id, db: &Connection) -> Result<Vec<Message>, ServerError> {
179 let ids = all(197 let ids = all(
180 db,198 db,
181- "SELECT id FROM message WHERE community_id = ?1 AND pinned = 1 ORDER BY id DESC",199+ "SELECT id FROM message WHERE community_id = ?1 AND pinned = 1 AND deleted_at IS NULL ORDER BY id DESC",
182 (community_id,),200 (community_id,),
183 |r| r.get(),201 |r| r.get(),
184 )202 )
@@ -251,10 +269,16 @@ pub async fn pin(message_id: Id, pinned: bool, db: &Connection) -> Result<Messag
251 }269 }
252 270
253 pub async fn update(message_id: Id, body: &str, db: &Connection) -> Result<Message, ServerError> {271 pub 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?;
254 ensure_with(278 ensure_with(
255 run(279 run(
256 db,280 db,
257- "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1",281+ "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1 AND deleted_at IS NULL",
258 (message_id, body),282 (message_id, body),
259 )283 )
260 .await?284 .await?
@@ -267,11 +291,32 @@ pub async fn update(message_id: Id, body: &str, db: &Connection) -> Result<Messa
267 291
268 pub async fn delete(message_id: Id, db: &Connection) -> Result<(), ServerError> {292 pub async fn delete(message_id: Id, db: &Connection) -> Result<(), ServerError> {
269 ensure_with(293 ensure_with(
270- run(db, "DELETE FROM message WHERE id = ?1", (message_id,)).await? == 1,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,
271 Error::NotFound,301 Error::NotFound,
272 )302 )
273 }303 }
274 304
305+pub 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+
275 pub async fn delete_where_user(user_id: Id, db: &Connection) -> Result<Vec<(Id, Id)>, ServerError> {320 pub async fn delete_where_user(user_id: Id, db: &Connection) -> Result<Vec<(Id, Id)>, ServerError> {
276 all(321 all(
277 db,322 db,
@@ -306,7 +351,7 @@ pub async fn search(
306 ) -> Result<Vec<MessageHit>, ServerError> {351 ) -> Result<Vec<MessageHit>, ServerError> {
307 let ids: Vec<Id> = all(352 let ids: Vec<Id> = all(
308 db,353 db,
309- "SELECT id FROM message WHERE (?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",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",
310 (355 (
311 text,356 text,
312 user_id,357 user_id,
@@ -436,7 +481,9 @@ pub async fn forward(
436 mod tests {481 mod tests {
437 use common::model::Role;482 use common::model::Role;
438 483
439- use super::{ForwardMode, create, forward, read_page};484+ use common::model::Reply;
485+
486+ use super::{ForwardMode, create, delete, edits, forward, read, read_page, update};
440 use crate::{487 use crate::{
441 db::{community, user},488 db::{community, user},
442 test,489 test,
@@ -466,8 +513,8 @@ mod tests {
466 .await513 .await
467 .unwrap();514 .unwrap();
468 515
469- let newest = read_page(community, None, &conn).await.unwrap();516+ let newest = read_page(community, None, false, &conn).await.unwrap();
470- let older = read_page(community, Some(message_3.id), &conn)517+ let older = read_page(community, Some(message_3.id), false, &conn)
471 .await518 .await
472 .unwrap();519 .unwrap();
473 520
@@ -478,6 +525,56 @@ mod tests {
478 assert_eq!(vec![message_1, message_2], older);525 assert_eq!(vec![message_1, message_2], older);
479 }526 }
480 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+
481 #[tokio::test]578 #[tokio::test]
482 async fn forward_two_as_snippet() {579 async fn forward_two_as_snippet() {
483 let db = test::db().await;580 let db = test::db().await;
crates/server/src/db/schema.sqlmodified+10 -1
@@ -87,13 +87,22 @@ CREATE TABLE message (
87 edited INTEGER NOT NULL DEFAULT 0,87 edited INTEGER NOT NULL DEFAULT 0,
88 pinned INTEGER NOT NULL DEFAULT 0,88 pinned INTEGER NOT NULL DEFAULT 0,
89 call TEXT,89 call TEXT,
90- call_seconds INTEGER NOT NULL DEFAULT 090+ call_seconds INTEGER NOT NULL DEFAULT 0,
91+ deleted_at INTEGER
91 ) STRICT;92 ) STRICT;
92 CREATE INDEX message_community ON message (community_id, id);93 CREATE INDEX message_community ON message (community_id, id);
93 CREATE INDEX message_user ON message (user_id);94 CREATE INDEX message_user ON message (user_id);
94 CREATE INDEX message_created ON message (created_at);95 CREATE INDEX message_created ON message (created_at);
95 CREATE INDEX message_reply ON message (reply_to);96 CREATE INDEX message_reply ON message (reply_to);
96 97
98+CREATE TABLE message_edit (
99+ id INTEGER PRIMARY KEY AUTOINCREMENT,
100+ message_id INTEGER NOT NULL REFERENCES message (id) ON DELETE CASCADE,
101+ body TEXT NOT NULL,
102+ edited_at INTEGER NOT NULL
103+) STRICT;
104+CREATE INDEX message_edit_message ON message_edit (message_id);
105+
97 CREATE TABLE attachment (106 CREATE TABLE attachment (
98 id INTEGER PRIMARY KEY AUTOINCREMENT,107 id INTEGER PRIMARY KEY AUTOINCREMENT,
99 uploader_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE,108 uploader_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE,
crates/server/src/files.rsmodified+1 -1
@@ -481,7 +481,7 @@ mod tests {
481 db::message::create(user.id, community, "", &[attachment.id], None, &conn)481 db::message::create(user.id, community, "", &[attachment.id], None, &conn)
482 .await482 .await
483 .unwrap();483 .unwrap();
484- let messages = db::message::read_page(community, None, &conn)484+ let messages = db::message::read_page(community, None, false, &conn)
485 .await485 .await
486 .unwrap();486 .unwrap();
487 assert_eq!(vec![attachment.clone()], messages[0].attachments);487 assert_eq!(vec![attachment.clone()], messages[0].attachments);
crates/server/src/request.rsmodified+7 -2
@@ -296,7 +296,12 @@ pub(crate) async fn ensure_editable(community_id: Id, db: &Connection) -> Result
296 }296 }
297 297
298 pub(crate) fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast {298 pub(crate) fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast {
299- Broadcast::new(To::Community(message.community_id), event(message.clone()))299+ let mut message = message.clone();
300+ if let Some(reply) = &mut message.reply {
301+ reply.redact();
302+ }
303+
304+ Broadcast::new(To::Community(message.community_id), event(message))
300 }305 }
301 306
302 pub(crate) fn voice_joined(community_id: Id, user_id: Id, muted: bool) -> Vec<Broadcast> {307 pub(crate) fn voice_joined(community_id: Id, user_id: Id, muted: bool) -> Vec<Broadcast> {
@@ -590,7 +595,7 @@ mod tests {
590 .unwrap();595 .unwrap();
591 596
592 let conn = db.lock().await.unwrap();597 let conn = db.lock().await.unwrap();
593- let remaining = db::message::read_page(community.id, None, &conn)598+ let remaining = db::message::read_page(community.id, None, false, &conn)
594 .await599 .await
595 .unwrap();600 .unwrap();
596 601