forked from matrix-org/matrix-rust-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
1543 lines (1345 loc) · 58.5 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{collections::BTreeSet, fmt, sync::Arc};
use as_variant::as_variant;
use decryption_retry_task::DecryptionRetryTask;
use eyeball_im::VectorDiff;
use eyeball_im_util::vector::VectorObserverExt;
use futures_core::Stream;
use imbl::Vector;
#[cfg(test)]
use matrix_sdk::{crypto::OlmMachine, SendOutsideWasm};
use matrix_sdk::{
deserialized_responses::TimelineEvent,
event_cache::{
paginator::{PaginationResult, Paginator},
RoomEventCache,
},
send_queue::{
LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendHandle, SendReactionHandle,
},
Result, Room,
};
use ruma::{
api::client::receipt::create_receipt::v3::ReceiptType as SendReceiptType,
events::{
poll::unstable_start::UnstablePollStartEventContent,
reaction::ReactionEventContent,
receipt::{Receipt, ReceiptThread, ReceiptType},
relation::Annotation,
room::message::{MessageType, Relation},
AnyMessageLikeEventContent, AnySyncEphemeralRoomEvent, AnySyncMessageLikeEvent,
AnySyncTimelineEvent, MessageLikeEventType,
},
serde::Raw,
EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedTransactionId, RoomVersionId,
TransactionId, UserId,
};
#[cfg(test)]
use ruma::{events::receipt::ReceiptEventContent, OwnedRoomId, RoomId};
use tokio::sync::{RwLock, RwLockWriteGuard};
use tracing::{debug, error, field::debug, info, instrument, trace, warn};
pub(super) use self::{
metadata::{RelativePosition, TimelineMetadata},
observable_items::{
AllRemoteEvents, ObservableItems, ObservableItemsEntry, ObservableItemsTransaction,
ObservableItemsTransactionEntry,
},
state::{FullEventMeta, PendingEdit, PendingEditKind, TimelineState},
state_transaction::TimelineStateTransaction,
};
use super::{
algorithms::{rfind_event_by_id, rfind_event_item},
event_handler::TimelineEventKind,
event_item::{ReactionStatus, RemoteEventOrigin},
item::TimelineUniqueId,
subscriber::TimelineSubscriber,
traits::{Decryptor, RoomDataProvider},
DateDividerMode, Error, EventSendState, EventTimelineItem, InReplyToDetails, Message,
PaginationError, Profile, RepliedToEvent, TimelineDetails, TimelineEventItemId, TimelineFocus,
TimelineItem, TimelineItemContent, TimelineItemKind,
};
use crate::{
timeline::{
algorithms::rfind_event_by_item_id,
date_dividers::DateDividerAdjuster,
event_item::EventTimelineItemKind,
pinned_events_loader::{PinnedEventsLoader, PinnedEventsLoaderError},
TimelineEventFilterFn,
},
unable_to_decrypt_hook::UtdHookManager,
};
mod aggregations;
mod decryption_retry_task;
mod metadata;
mod observable_items;
mod read_receipts;
mod state;
mod state_transaction;
pub(super) use aggregations::*;
/// Data associated to the current timeline focus.
#[derive(Debug)]
enum TimelineFocusData<P: RoomDataProvider> {
/// The timeline receives live events from the sync.
Live,
/// The timeline is focused on a single event, and it can expand in one
/// direction or another.
Event {
/// The event id we've started to focus on.
event_id: OwnedEventId,
/// The paginator instance.
paginator: Paginator<P>,
/// Number of context events to request for the first request.
num_context_events: u16,
},
PinnedEvents {
loader: PinnedEventsLoader,
},
}
#[derive(Clone, Debug)]
pub(super) struct TimelineController<P: RoomDataProvider = Room, D: Decryptor = Room> {
/// Inner mutable state.
state: Arc<RwLock<TimelineState>>,
/// Inner mutable focus state.
focus: Arc<RwLock<TimelineFocusData<P>>>,
/// A [`RoomDataProvider`] implementation, providing data.
///
/// Useful for testing only; in the real world, it's just a [`Room`].
pub(crate) room_data_provider: P,
/// Settings applied to this timeline.
pub(super) settings: TimelineSettings,
/// Long-running task used to retry decryption of timeline items without
/// blocking main processing.
decryption_retry_task: DecryptionRetryTask<D>,
}
#[derive(Clone)]
pub(super) struct TimelineSettings {
/// Should the read receipts and read markers be handled?
pub(super) track_read_receipts: bool,
/// Event filter that controls what's rendered as a timeline item (and thus
/// what can carry read receipts).
pub(super) event_filter: Arc<TimelineEventFilterFn>,
/// Are unparsable events added as timeline items of their own kind?
pub(super) add_failed_to_parse: bool,
/// Should the timeline items be grouped by day or month?
pub(super) date_divider_mode: DateDividerMode,
}
#[cfg(not(tarpaulin_include))]
impl fmt::Debug for TimelineSettings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TimelineSettings")
.field("track_read_receipts", &self.track_read_receipts)
.field("add_failed_to_parse", &self.add_failed_to_parse)
.finish_non_exhaustive()
}
}
impl Default for TimelineSettings {
fn default() -> Self {
Self {
track_read_receipts: false,
event_filter: Arc::new(default_event_filter),
add_failed_to_parse: true,
date_divider_mode: DateDividerMode::Daily,
}
}
}
#[derive(Debug, Clone, Copy)]
pub(super) enum TimelineFocusKind {
Live,
Event,
PinnedEvents,
}
/// The default event filter for
/// [`crate::timeline::TimelineBuilder::event_filter`].
///
/// It filters out events that are not rendered by the timeline, including but
/// not limited to: reactions, edits, redactions on existing messages.
///
/// If you have a custom filter, it may be best to chain yours with this one if
/// you do not want to run into situations where a read receipt is not visible
/// because it's living on an event that doesn't have a matching timeline item.
pub fn default_event_filter(event: &AnySyncTimelineEvent, room_version: &RoomVersionId) -> bool {
match event {
AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomRedaction(ev)) => {
if ev.redacts(room_version).is_some() {
// This is a redaction of an existing message, we'll only update the previous
// message and not render a new entry.
false
} else {
// This is a redacted entry, that we'll show only if the redacted entity wasn't
// a reaction.
ev.event_type() != MessageLikeEventType::Reaction
}
}
AnySyncTimelineEvent::MessageLike(msg) => {
match msg.original_content() {
None => {
// This is a redacted entry, that we'll show only if the redacted entity wasn't
// a reaction.
msg.event_type() != MessageLikeEventType::Reaction
}
Some(original_content) => {
match original_content {
AnyMessageLikeEventContent::RoomMessage(content) => {
if content
.relates_to
.as_ref()
.is_some_and(|rel| matches!(rel, Relation::Replacement(_)))
{
// Edits aren't visible by default.
return false;
}
matches!(
content.msgtype,
MessageType::Audio(_)
| MessageType::Emote(_)
| MessageType::File(_)
| MessageType::Image(_)
| MessageType::Location(_)
| MessageType::Notice(_)
| MessageType::ServerNotice(_)
| MessageType::Text(_)
| MessageType::Video(_)
| MessageType::VerificationRequest(_)
)
}
AnyMessageLikeEventContent::Sticker(_)
| AnyMessageLikeEventContent::UnstablePollStart(
UnstablePollStartEventContent::New(_),
)
| AnyMessageLikeEventContent::CallInvite(_)
| AnyMessageLikeEventContent::CallNotify(_)
| AnyMessageLikeEventContent::RoomEncrypted(_) => true,
_ => false,
}
}
}
}
AnySyncTimelineEvent::State(_) => {
// All the state events may get displayed by default.
true
}
}
}
impl<P: RoomDataProvider, D: Decryptor> TimelineController<P, D> {
pub(super) fn new(
room_data_provider: P,
focus: TimelineFocus,
internal_id_prefix: Option<String>,
unable_to_decrypt_hook: Option<Arc<UtdHookManager>>,
is_room_encrypted: bool,
) -> Self {
let (focus_data, focus_kind) = match focus {
TimelineFocus::Live => (TimelineFocusData::Live, TimelineFocusKind::Live),
TimelineFocus::Event { target, num_context_events } => {
let paginator = Paginator::new(room_data_provider.clone());
(
TimelineFocusData::Event { paginator, event_id: target, num_context_events },
TimelineFocusKind::Event,
)
}
TimelineFocus::PinnedEvents { max_events_to_load, max_concurrent_requests } => (
TimelineFocusData::PinnedEvents {
loader: PinnedEventsLoader::new(
Arc::new(room_data_provider.clone()),
max_events_to_load as usize,
max_concurrent_requests as usize,
),
},
TimelineFocusKind::PinnedEvents,
),
};
let state = Arc::new(RwLock::new(TimelineState::new(
focus_kind,
room_data_provider.own_user_id().to_owned(),
room_data_provider.room_version(),
internal_id_prefix,
unable_to_decrypt_hook,
is_room_encrypted,
)));
let settings = TimelineSettings::default();
let decryption_retry_task =
DecryptionRetryTask::new(state.clone(), room_data_provider.clone());
Self {
state,
focus: Arc::new(RwLock::new(focus_data)),
room_data_provider,
settings,
decryption_retry_task,
}
}
/// Initializes the configured focus with appropriate data.
///
/// Should be called only once after creation of the [`TimelineInner`], with
/// all its fields set.
///
/// Returns whether there were any events added to the timeline.
pub(super) async fn init_focus(
&self,
room_event_cache: &RoomEventCache,
) -> Result<bool, Error> {
let focus_guard = self.focus.read().await;
match &*focus_guard {
TimelineFocusData::Live => {
// Retrieve the cached events, and add them to the timeline.
let (events, _stream) = room_event_cache.subscribe().await;
let has_events = !events.is_empty();
self.replace_with_initial_remote_events(
events.into_iter(),
RemoteEventOrigin::Cache,
)
.await;
Ok(has_events)
}
TimelineFocusData::Event { event_id, paginator, num_context_events } => {
// Start a /context request, and append the results (in order) to the timeline.
let start_from_result = paginator
.start_from(event_id, (*num_context_events).into())
.await
.map_err(PaginationError::Paginator)?;
drop(focus_guard);
let has_events = !start_from_result.events.is_empty();
self.replace_with_initial_remote_events(
start_from_result.events.into_iter(),
RemoteEventOrigin::Pagination,
)
.await;
Ok(has_events)
}
TimelineFocusData::PinnedEvents { loader } => {
let loaded_events = loader.load_events().await.map_err(Error::PinnedEventsError)?;
drop(focus_guard);
let has_events = !loaded_events.is_empty();
self.replace_with_initial_remote_events(
loaded_events.into_iter(),
RemoteEventOrigin::Pagination,
)
.await;
Ok(has_events)
}
}
}
/// Listens to encryption state changes for the room in
/// [`matrix_sdk_base::RoomInfo`] and applies the new value to the
/// existing timeline items. This will then cause a refresh of those
/// timeline items.
pub async fn handle_encryption_state_changes(&self) {
let mut room_info = self.room_data_provider.room_info();
// Small function helper to help mark as encrypted.
let mark_encrypted = || async {
let mut state = self.state.write().await;
state.meta.is_room_encrypted = true;
state.mark_all_events_as_encrypted();
};
if room_info.get().encryption_state().is_encrypted() {
// If the room was already encrypted, it won't toggle to unencrypted, so we can
// shut down this task early.
mark_encrypted().await;
return;
}
while let Some(info) = room_info.next().await {
if info.encryption_state().is_encrypted() {
mark_encrypted().await;
// Once the room is encrypted, it cannot switch back to unencrypted, so our work
// here is done.
break;
}
}
}
pub(crate) async fn reload_pinned_events(
&self,
) -> Result<Vec<TimelineEvent>, PinnedEventsLoaderError> {
let focus_guard = self.focus.read().await;
if let TimelineFocusData::PinnedEvents { loader } = &*focus_guard {
loader.load_events().await
} else {
Err(PinnedEventsLoaderError::TimelineFocusNotPinnedEvents)
}
}
/// Run a lazy backwards pagination (in live mode).
///
/// It adjusts the `count` value of the `Skip` higher-order stream so that
/// more items are pushed front in the timeline.
///
/// If no more items are available (i.e. if the `count` is zero), this
/// method returns `Some(needs)` where `needs` is the number of events that
/// must be unlazily backwards paginated.
pub(super) async fn live_lazy_paginate_backwards(&self, num_events: u16) -> Option<usize> {
let state = self.state.read().await;
let (count, needs) = state
.meta
.subscriber_skip_count
.compute_next_when_paginating_backwards(num_events.into());
state.meta.subscriber_skip_count.update(count, &state.timeline_focus);
needs
}
/// Run a backwards pagination (in focused mode) and append the results to
/// the timeline.
///
/// Returns whether we hit the start of the timeline.
pub(super) async fn focused_paginate_backwards(
&self,
num_events: u16,
) -> Result<bool, PaginationError> {
let PaginationResult { events, hit_end_of_timeline } = match &*self.focus.read().await {
TimelineFocusData::Live | TimelineFocusData::PinnedEvents { .. } => {
return Err(PaginationError::NotEventFocusMode)
}
TimelineFocusData::Event { paginator, .. } => paginator
.paginate_backward(num_events.into())
.await
.map_err(PaginationError::Paginator)?,
};
// Events are in reverse topological order.
// We can push front each event individually.
self.handle_remote_events_with_diffs(
events.into_iter().map(|event| VectorDiff::PushFront { value: event }).collect(),
RemoteEventOrigin::Pagination,
)
.await;
Ok(hit_end_of_timeline)
}
/// Run a forwards pagination (in focused mode) and append the results to
/// the timeline.
///
/// Returns whether we hit the end of the timeline.
pub(super) async fn focused_paginate_forwards(
&self,
num_events: u16,
) -> Result<bool, PaginationError> {
let PaginationResult { events, hit_end_of_timeline } = match &*self.focus.read().await {
TimelineFocusData::Live | TimelineFocusData::PinnedEvents { .. } => {
return Err(PaginationError::NotEventFocusMode)
}
TimelineFocusData::Event { paginator, .. } => paginator
.paginate_forward(num_events.into())
.await
.map_err(PaginationError::Paginator)?,
};
// Events are in topological order.
// We can append all events with no transformation.
self.handle_remote_events_with_diffs(
vec![VectorDiff::Append { values: events.into() }],
RemoteEventOrigin::Pagination,
)
.await;
Ok(hit_end_of_timeline)
}
/// Is this timeline receiving events from sync (aka has a live focus)?
pub(super) async fn is_live(&self) -> bool {
matches!(&*self.focus.read().await, TimelineFocusData::Live)
}
pub(super) fn with_settings(mut self, settings: TimelineSettings) -> Self {
self.settings = settings;
self
}
/// Get a copy of the current items in the list.
///
/// Cheap because `im::Vector` is cheap to clone.
pub(super) async fn items(&self) -> Vector<Arc<TimelineItem>> {
self.state.read().await.items.clone_items()
}
#[cfg(test)]
pub(super) async fn subscribe_raw(
&self,
) -> (
Vector<Arc<TimelineItem>>,
impl Stream<Item = VectorDiff<Arc<TimelineItem>>> + SendOutsideWasm,
) {
let state = self.state.read().await;
state.items.subscribe().into_values_and_stream()
}
pub(super) async fn subscribe(&self) -> (Vector<Arc<TimelineItem>>, TimelineSubscriber) {
let state = self.state.read().await;
TimelineSubscriber::new(&state.items, &state.meta.subscriber_skip_count)
}
pub(super) async fn subscribe_filter_map<U, F>(
&self,
f: F,
) -> (Vector<U>, impl Stream<Item = VectorDiff<U>>)
where
U: Clone,
F: Fn(Arc<TimelineItem>) -> Option<U>,
{
self.state.read().await.items.subscribe().filter_map(f)
}
/// Toggle a reaction locally.
///
/// Returns true if the reaction was added, false if it was removed.
#[instrument(skip_all)]
pub(super) async fn toggle_reaction_local(
&self,
item_id: &TimelineEventItemId,
key: &str,
) -> Result<bool, Error> {
let mut state = self.state.write().await;
let Some((item_pos, item)) = rfind_event_by_item_id(&state.items, item_id) else {
warn!("Timeline item not found, can't add reaction");
return Err(Error::FailedToToggleReaction);
};
let user_id = self.room_data_provider.own_user_id();
let prev_status = item
.content()
.reactions()
.get(key)
.and_then(|group| group.get(user_id))
.map(|reaction_info| reaction_info.status.clone());
let Some(prev_status) = prev_status else {
match &item.kind {
EventTimelineItemKind::Local(local) => {
if let Some(send_handle) = &local.send_handle {
if send_handle
.react(key.to_owned())
.await
.map_err(|err| Error::SendQueueError(err.into()))?
.is_some()
{
trace!("adding a reaction to a local echo");
return Ok(true);
}
warn!("couldn't toggle reaction for local echo");
return Ok(false);
}
warn!("missing send handle for local echo; is this a test?");
return Ok(false);
}
EventTimelineItemKind::Remote(remote) => {
// Add a reaction through the room data provider.
// No need to reflect the effect locally, since the local echo handling will
// take care of it.
trace!("adding a reaction to a remote echo");
let annotation = Annotation::new(remote.event_id.to_owned(), key.to_owned());
self.room_data_provider
.send(ReactionEventContent::from(annotation).into())
.await?;
return Ok(true);
}
}
};
trace!("removing a previous reaction");
match prev_status {
ReactionStatus::LocalToLocal(send_reaction_handle) => {
if let Some(handle) = send_reaction_handle {
if !handle.abort().await.map_err(|err| Error::SendQueueError(err.into()))? {
// Impossible state: the reaction has moved from local to echo under our
// feet, but the timeline was supposed to be locked!
warn!("unexpectedly unable to abort sending of local reaction");
}
} else {
warn!("no send reaction handle (this should only happen in testing contexts)");
}
}
ReactionStatus::LocalToRemote(send_handle) => {
// No need to reflect the change ourselves, since handling the discard of the
// local echo will take care of it.
trace!("aborting send of the previous reaction that was a local echo");
if let Some(handle) = send_handle {
if !handle.abort().await.map_err(|err| Error::SendQueueError(err.into()))? {
// Impossible state: the reaction has moved from local to echo under our
// feet, but the timeline was supposed to be locked!
warn!("unexpectedly unable to abort sending of local reaction");
}
} else {
warn!("no send handle (this should only happen in testing contexts)");
}
}
ReactionStatus::RemoteToRemote(event_id) => {
// Assume the redaction will work; we'll re-add the reaction if it didn't.
let Some(annotated_event_id) =
item.as_remote().map(|event_item| event_item.event_id.clone())
else {
warn!("remote reaction to remote event, but the associated item isn't remote");
return Ok(false);
};
let mut reactions = item.content().reactions().clone();
let reaction_info = reactions.remove_reaction(user_id, key);
if reaction_info.is_some() {
let new_item = item.with_reactions(reactions);
state.items.replace(item_pos, new_item);
} else {
warn!("reaction is missing on the item, not removing it locally, but sending redaction.");
}
// Release the lock before running the request.
drop(state);
trace!("sending redact for a previous reaction");
if let Err(err) = self.room_data_provider.redact(&event_id, None, None).await {
if let Some(reaction_info) = reaction_info {
debug!("sending redact failed, adding the reaction back to the list");
let mut state = self.state.write().await;
if let Some((item_pos, item)) =
rfind_event_by_id(&state.items, &annotated_event_id)
{
// Re-add the reaction to the mapping.
let mut reactions = item.content().reactions();
reactions
.entry(key.to_owned())
.or_default()
.insert(user_id.to_owned(), reaction_info);
let new_item = item.with_reactions(reactions);
state.items.replace(item_pos, new_item);
} else {
warn!("couldn't find item to re-add reaction anymore; maybe it's been redacted?");
}
}
return Err(err);
}
}
}
Ok(false)
}
/// Handle updates on events as [`VectorDiff`]s.
pub(super) async fn handle_remote_events_with_diffs(
&self,
diffs: Vec<VectorDiff<TimelineEvent>>,
origin: RemoteEventOrigin,
) {
if diffs.is_empty() {
return;
}
let mut state = self.state.write().await;
state
.handle_remote_events_with_diffs(
diffs,
origin,
&self.room_data_provider,
&self.settings,
)
.await
}
pub(super) async fn clear(&self) {
self.state.write().await.clear();
}
/// Replaces the content of the current timeline with initial events.
///
/// Also sets up read receipts and the read marker for a live timeline of a
/// room.
///
/// This is all done with a single lock guard, since we don't want the state
/// to be modified between the clear and re-insertion of new events.
pub(super) async fn replace_with_initial_remote_events<Events>(
&self,
events: Events,
origin: RemoteEventOrigin,
) where
Events: IntoIterator + ExactSizeIterator,
<Events as IntoIterator>::Item: Into<TimelineEvent>,
{
let mut state = self.state.write().await;
let track_read_markers = self.settings.track_read_receipts;
if track_read_markers {
state.populate_initial_user_receipt(&self.room_data_provider, ReceiptType::Read).await;
state
.populate_initial_user_receipt(&self.room_data_provider, ReceiptType::ReadPrivate)
.await;
}
// Replace the events if either the current event list or the new one aren't
// empty.
// Previously we just had to check the new one wasn't empty because
// we did a clear operation before so the current one would always be empty, but
// now we may want to replace a populated timeline with an empty one.
if !state.items.is_empty() || events.len() > 0 {
state
.replace_with_remote_events(
events,
origin,
&self.room_data_provider,
&self.settings,
)
.await;
}
if track_read_markers {
if let Some(fully_read_event_id) =
self.room_data_provider.load_fully_read_marker().await
{
state.handle_fully_read_marker(fully_read_event_id);
}
}
}
pub(super) async fn handle_fully_read_marker(&self, fully_read_event_id: OwnedEventId) {
self.state.write().await.handle_fully_read_marker(fully_read_event_id);
}
pub(super) async fn handle_ephemeral_events(
&self,
events: Vec<Raw<AnySyncEphemeralRoomEvent>>,
) {
let mut state = self.state.write().await;
state.handle_ephemeral_events(events, &self.room_data_provider).await;
}
/// Creates the local echo for an event we're sending.
#[instrument(skip_all)]
pub(super) async fn handle_local_event(
&self,
txn_id: OwnedTransactionId,
content: TimelineEventKind,
send_handle: Option<SendHandle>,
) {
let sender = self.room_data_provider.own_user_id().to_owned();
let profile = self.room_data_provider.profile_from_user_id(&sender).await;
// Only add new items if the timeline is live.
let should_add_new_items = self.is_live().await;
let date_divider_mode = self.settings.date_divider_mode.clone();
let mut state = self.state.write().await;
state
.handle_local_event(
sender,
profile,
should_add_new_items,
date_divider_mode,
txn_id,
send_handle,
content,
)
.await;
}
/// Update the send state of a local event represented by a transaction ID.
///
/// If the corresponding local timeline item is missing, a warning is
/// raised.
#[instrument(skip(self))]
pub(super) async fn update_event_send_state(
&self,
txn_id: &TransactionId,
send_state: EventSendState,
) {
let mut state = self.state.write().await;
let mut txn = state.transaction();
let new_event_id: Option<&EventId> =
as_variant!(&send_state, EventSendState::Sent { event_id } => event_id);
// The local echoes are always at the end of the timeline, we must first make
// sure the remote echo hasn't showed up yet.
if rfind_event_item(&txn.items, |it| {
new_event_id.is_some() && it.event_id() == new_event_id && it.as_remote().is_some()
})
.is_some()
{
// Remote echo already received. This is very unlikely.
trace!("Remote echo received before send-event response");
let local_echo = rfind_event_item(&txn.items, |it| it.transaction_id() == Some(txn_id));
// If there's both the remote echo and a local echo, that means the
// remote echo was received before the response *and* contained no
// transaction ID (and thus duplicated the local echo).
if let Some((idx, _)) = local_echo {
warn!("Message echo got duplicated, removing the local one");
txn.items.remove(idx);
// Adjust the date dividers, if needs be.
let mut adjuster =
DateDividerAdjuster::new(self.settings.date_divider_mode.clone());
adjuster.run(&mut txn.items, &mut txn.meta);
}
txn.commit();
return;
}
// Look for the local event by the transaction ID or event ID.
let result = rfind_event_item(&txn.items, |it| {
it.transaction_id() == Some(txn_id)
|| new_event_id.is_some()
&& it.event_id() == new_event_id
&& it.as_local().is_some()
});
let Some((idx, item)) = result else {
// Event wasn't found as a standalone item.
//
// If it was just sent, try to find if it matches a corresponding aggregation,
// and mark it as sent in that case.
if let Some(new_event_id) = new_event_id {
match txn
.meta
.aggregations
.mark_aggregation_as_sent(txn_id.to_owned(), new_event_id.to_owned())
{
MarkAggregationSentResult::MarkedSent { update } => {
trace!("marked aggregation as sent");
if let Some((target, aggregation)) = update {
if let Some((item_pos, item)) =
rfind_event_by_item_id(&txn.items, &target)
{
let mut content = item.content().clone();
match aggregation.apply(&mut content) {
ApplyAggregationResult::UpdatedItem => {
trace!("reapplied aggregation in the event");
let internal_id = item.internal_id.to_owned();
let new_item = item.with_content(content);
txn.items.replace(
item_pos,
TimelineItem::new(new_item, internal_id),
);
txn.commit();
}
ApplyAggregationResult::LeftItemIntact => {}
ApplyAggregationResult::Error(err) => {
warn!("when reapplying aggregation just marked as sent: {err}");
}
}
}
}
// Early return: we've found the event to mark as sent, it was an
// aggregation.
return;
}
MarkAggregationSentResult::NotFound => {}
}
}
warn!("Timeline item not found, can't update send state");
return;
};
let Some(local_item) = item.as_local() else {
warn!("We looked for a local item, but it transitioned to remote.");
return;
};
// The event was already marked as sent, that's a broken state, let's
// emit an error but also override to the given sent state.
if let EventSendState::Sent { event_id: existing_event_id } = &local_item.send_state {
error!(?existing_event_id, ?new_event_id, "Local echo already marked as sent");
}
// If the event has just been marked as sent, update the aggregations mapping to
// take that into account.
if let Some(new_event_id) = new_event_id {
txn.meta.aggregations.mark_target_as_sent(txn_id.to_owned(), new_event_id.to_owned());
}
let new_item = item.with_inner_kind(local_item.with_send_state(send_state));
txn.items.replace(idx, new_item);
txn.commit();
}
pub(super) async fn discard_local_echo(&self, txn_id: &TransactionId) -> bool {
let mut state = self.state.write().await;
if let Some((idx, _)) =
rfind_event_item(&state.items, |it| it.transaction_id() == Some(txn_id))
{
let mut txn = state.transaction();
txn.items.remove(idx);
// A read marker or a date divider may have been inserted before the local echo.
// Ensure both are up to date.
let mut adjuster = DateDividerAdjuster::new(self.settings.date_divider_mode.clone());
adjuster.run(&mut txn.items, &mut txn.meta);
txn.meta.update_read_marker(&mut txn.items);
txn.commit();
debug!("discarded local echo");
return true;
}
// Avoid multiple mutable and immutable borrows of the lock guard by explicitly
// dereferencing it once.
let state = &mut *state;
// Look if this was a local aggregation.
if let Some((target, aggregation)) = state
.meta
.aggregations
.try_remove_aggregation(&TimelineEventItemId::TransactionId(txn_id.to_owned()))
{
let Some((item_pos, item)) = rfind_event_by_item_id(&state.items, target) else {
warn!("missing target item for a local aggregation");
return false;
};
let mut content = item.content().clone();
match aggregation.unapply(&mut content) {
ApplyAggregationResult::UpdatedItem => {
trace!("removed local reaction to local echo");
let internal_id = item.internal_id.clone();
let new_item = item.with_content(content);
state.items.replace(item_pos, TimelineItem::new(new_item, internal_id));
}
ApplyAggregationResult::LeftItemIntact => {}
ApplyAggregationResult::Error(err) => {
warn!("when undoing local aggregation: {err}");
}
}
return true;
}
false
}
pub(super) async fn replace_local_echo(
&self,
txn_id: &TransactionId,
content: AnyMessageLikeEventContent,
) -> bool {
let AnyMessageLikeEventContent::RoomMessage(content) = content else {
// Ideally, we'd support replacing local echoes for a reaction, etc., but