Skip to main content

matrix_sdk_ui/timeline/controller/
mod.rs

1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{
16    collections::BTreeSet,
17    fmt,
18    ops::Deref,
19    sync::{Arc, OnceLock},
20};
21
22use as_variant::as_variant;
23use eyeball::SharedObservable;
24use eyeball_im::{VectorDiff, VectorSubscriberStream};
25use eyeball_im_util::vector::{FilterMap, VectorObserverExt};
26use futures_core::Stream;
27use futures_util::future::try_join_all;
28use imbl::{HashSet, Vector};
29use matrix_sdk::{
30    deserialized_responses::{ThreadSummary, TimelineEvent},
31    event_cache::{
32        DecryptionRetryRequest, EventCache, EventFocusedCache, PaginationStatus, PinnedEventsCache,
33        RoomEventCache, Subscriber as EventCacheSubscriber, ThreadEventCache,
34        ThreadEventCacheUpdate,
35    },
36    send_queue::{LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendHandle},
37    task_monitor::BackgroundTaskHandle,
38};
39use ruma::{
40    EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedTransactionId, OwnedUserId, RoomId,
41    TransactionId, UserId,
42    api::client::receipt::create_receipt::v3::ReceiptType as SendReceiptType,
43    events::{
44        AnyMessageLikeEventContent, AnySyncMessageLikeEvent, AnySyncTimelineEvent,
45        MessageLikeEventType,
46        poll::unstable_start::UnstablePollStartEventContent,
47        reaction::ReactionEventContent,
48        receipt::{Receipt, ReceiptEventContent, ReceiptThread, ReceiptType},
49        relation::{Annotation, RelationType},
50        room::message::{MessageType, Relation},
51    },
52    room_version_rules::RoomVersionRules,
53};
54use tokio::sync::{RwLock, RwLockWriteGuard};
55use tracing::{
56    Instrument as _, Span, debug, error, field::debug, info, info_span, instrument, trace, warn,
57};
58
59pub(super) use self::{
60    metadata::{RelativePosition, TimelineMetadata},
61    observable_items::{
62        AllRemoteEvents, ObservableItems, ObservableItemsEntry, ObservableItemsTransaction,
63    },
64    state::TimelineState,
65    state_transaction::TimelineStateTransaction,
66};
67use super::{
68    DateDividerMode, EmbeddedEvent, Error, EventSendState, EventTimelineItem, InReplyToDetails,
69    MediaUploadProgress, Profile, TimelineDetails, TimelineEventItemId, TimelineFocus,
70    TimelineItem, TimelineItemContent, TimelineItemKind, TimelineReadReceiptTracking,
71    VirtualTimelineItem,
72    algorithms::{rfind_event_by_id, rfind_event_item},
73    event_item::RemoteEventOrigin,
74    item::TimelineUniqueId,
75    subscriber::TimelineSubscriber,
76    traits::RoomDataProvider,
77};
78use crate::{
79    timeline::{
80        MsgLikeContent, MsgLikeKind, Room, SendTarget, TimelineEventFilterFn,
81        TimelineEventFocusThreadMode,
82        algorithms::rfind_event_by_item_id,
83        controller::decryption_retry_task::compute_redecryption_candidates,
84        date_dividers::DateDividerAdjuster,
85        event_item::TimelineItemHandle,
86        tasks::{event_focused_task, pinned_events_task, thread_updates_task},
87    },
88    unable_to_decrypt_hook::UtdHookManager,
89};
90
91pub(in crate::timeline) mod aggregations;
92mod decryption_retry_task;
93mod metadata;
94mod observable_items;
95mod read_receipts;
96mod state;
97mod state_transaction;
98
99pub(super) use aggregations::*;
100pub(super) use decryption_retry_task::{CryptoDropHandles, spawn_crypto_tasks};
101use matrix_sdk_base::{CallIntentConsensus, RoomInfo};
102
103/// The outcome of [`TimelineController::should_send_receipt`].
104pub(super) enum SendReceiptDecision {
105    /// No read receipt should be sent.
106    DoNotSend,
107
108    /// A read receipt should be sent, targeting this event.
109    ///
110    /// This may differ from the event the caller asked about, since a read
111    /// receipt should not point at one of the user's own events.
112    SendTo(OwnedEventId),
113}
114
115/// Data associated to the current timeline focus.
116///
117/// This is the private counterpart of [`TimelineFocus`], and it is an augmented
118/// version of it, including extra state that makes it useful over the lifetime
119/// of a timeline.
120#[derive(Debug)]
121pub(in crate::timeline) enum TimelineFocusKind {
122    /// The timeline receives live events from the sync.
123    Live {
124        /// Whether to hide in-thread events from the timeline.
125        hide_threaded_events: bool,
126
127        /// The cache holding all the events for this focus.
128        event_cache: RoomEventCache,
129    },
130
131    /// The timeline is focused on a single event, and it can expand in one
132    /// direction or another.
133    Event {
134        /// The focused event ID.
135        focused_event_id: OwnedEventId,
136
137        /// If the focused event is part or the root of a thread, what's the
138        /// thread root?
139        ///
140        /// This is determined once when initializing the event-focused cache,
141        /// and then it won't change for the duration of this timeline.
142        thread_root: OnceLock<OwnedEventId>,
143
144        /// The thread mode to use for this event-focused timeline, which is
145        /// part of the key for the memoized event-focused cache.
146        thread_mode: TimelineEventFocusThreadMode,
147
148        /// The cache holding all the events for this focus.
149        event_cache: EventFocusedCache,
150    },
151
152    /// A live timeline for a thread.
153    Thread {
154        /// The root event for the current thread.
155        thread_id: OwnedEventId,
156
157        /// The cache holding all the events for this focus.
158        event_cache: ThreadEventCache,
159    },
160
161    PinnedEvents {
162        /// The cache holding all the events for this focus.
163        event_cache: PinnedEventsCache,
164    },
165}
166
167impl TimelineFocusKind {
168    /// Get the room ID of this timeline.
169    pub(super) fn room_id(&self) -> &RoomId {
170        match self {
171            TimelineFocusKind::Live { event_cache, .. } => event_cache.room_id(),
172            TimelineFocusKind::Thread { event_cache, .. } => event_cache.room_id(),
173            TimelineFocusKind::Event { event_cache, .. } => event_cache.room_id(),
174            TimelineFocusKind::PinnedEvents { event_cache } => event_cache.room_id(),
175        }
176    }
177    /// Returns the [`ReceiptThread`] that should be used for the current
178    /// timeline focus.
179    ///
180    /// Live and event timelines will use the unthreaded read receipt type in
181    /// general, unless they hide in-thread events, in which case they will use
182    /// the main thread.
183    pub(super) fn receipt_thread(&self) -> ReceiptThread {
184        if let Some(thread_root) = self.thread_root() {
185            ReceiptThread::Thread(thread_root.to_owned())
186        } else if self.hide_threaded_events() {
187            ReceiptThread::Main
188        } else {
189            ReceiptThread::Unthreaded
190        }
191    }
192
193    /// Whether to hide in-thread events from the timeline.
194    fn hide_threaded_events(&self) -> bool {
195        match self {
196            TimelineFocusKind::Live { hide_threaded_events, .. } => *hide_threaded_events,
197            TimelineFocusKind::Event { thread_mode, .. } => {
198                matches!(
199                    thread_mode,
200                    TimelineEventFocusThreadMode::Automatic { hide_threaded_events: true }
201                )
202            }
203            TimelineFocusKind::Thread { .. } | TimelineFocusKind::PinnedEvents { .. } => false,
204        }
205    }
206
207    /// Whether the focus is on a thread (from a live thread or a thread
208    /// permalink).
209    fn is_thread(&self) -> bool {
210        self.thread_root().is_some()
211    }
212
213    /// If the focus is a thread or event-focused, returns its thread root event
214    /// ID if any.
215    fn thread_root(&self) -> Option<&EventId> {
216        match self {
217            TimelineFocusKind::Event { thread_root, .. } => thread_root.get().map(|v| &**v),
218            TimelineFocusKind::Live { .. } | TimelineFocusKind::PinnedEvents { .. } => None,
219            TimelineFocusKind::Thread { thread_id, .. } => Some(thread_id),
220        }
221    }
222}
223
224#[derive(Clone, Debug)]
225pub(super) struct TimelineController<P: RoomDataProvider = Room> {
226    /// Inner mutable state.
227    state: Arc<RwLock<TimelineState<P>>>,
228
229    /// Focus data.
230    focus: Arc<TimelineFocusKind>,
231
232    /// A [`RoomDataProvider`] implementation, providing data.
233    ///
234    /// The type is a `RoomDataProvider` to allow testing. In the real world,
235    /// this would normally be a [`Room`].
236    pub(crate) room_data_provider: P,
237
238    /// Settings applied to this timeline.
239    pub(super) settings: TimelineSettings,
240
241    /// The ID of the closest visible event at or before the user's
242    /// `m.fully_read` marker.
243    pub(super) fully_read_event_id: SharedObservable<Option<OwnedEventId>>,
244}
245
246#[derive(Clone)]
247pub(super) struct TimelineSettings {
248    /// Should the read receipts and read markers be handled and on which event
249    /// types?
250    pub(super) track_read_receipts: TimelineReadReceiptTracking,
251
252    /// Event filter that controls what's rendered as a timeline item (and thus
253    /// what can carry read receipts).
254    pub(super) event_filter: Arc<TimelineEventFilterFn>,
255
256    /// Are unparsable events added as timeline items of their own kind?
257    pub(super) add_failed_to_parse: bool,
258
259    /// Should the timeline items be grouped by day or month?
260    pub(super) date_divider_mode: DateDividerMode,
261}
262
263#[cfg(not(tarpaulin_include))]
264impl fmt::Debug for TimelineSettings {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        f.debug_struct("TimelineSettings")
267            .field("track_read_receipts", &self.track_read_receipts)
268            .field("add_failed_to_parse", &self.add_failed_to_parse)
269            .finish_non_exhaustive()
270    }
271}
272
273impl Default for TimelineSettings {
274    fn default() -> Self {
275        Self {
276            track_read_receipts: TimelineReadReceiptTracking::Disabled,
277            event_filter: Arc::new(default_event_filter),
278            add_failed_to_parse: true,
279            date_divider_mode: DateDividerMode::Daily,
280        }
281    }
282}
283
284/// The default event filter for
285/// [`crate::timeline::TimelineBuilder::event_filter`].
286///
287/// It filters out events that are not rendered by the timeline, including but
288/// not limited to: reactions, edits, redactions on existing messages.
289///
290/// If you have a custom filter, it may be best to chain yours with this one if
291/// you do not want to run into situations where a read receipt is not visible
292/// because it's living on an event that doesn't have a matching timeline item.
293pub fn default_event_filter(event: &AnySyncTimelineEvent, rules: &RoomVersionRules) -> bool {
294    match event {
295        AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomRedaction(ev)) => {
296            if ev.redacts(&rules.redaction).is_some() {
297                // This is a redaction of an existing message, we'll only update
298                // the previous message and not render a new entry.
299                false
300            } else {
301                // This is a redacted entry, that we'll show only if the
302                // redacted entity wasn't a reaction.
303                ev.event_type() != MessageLikeEventType::Reaction
304            }
305        }
306
307        AnySyncTimelineEvent::MessageLike(msg) => {
308            match msg.original_content() {
309                None => {
310                    // This is a redacted entry, that we'll show only if the
311                    // redacted entity wasn't a reaction.
312                    msg.event_type() != MessageLikeEventType::Reaction
313                }
314
315                Some(original_content) => {
316                    match original_content {
317                        AnyMessageLikeEventContent::RoomMessage(content) => {
318                            if content
319                                .relates_to
320                                .as_ref()
321                                .is_some_and(|rel| matches!(rel, Relation::Replacement(_)))
322                            {
323                                // Edits aren't visible by default.
324                                return false;
325                            }
326
327                            match content.msgtype {
328                                MessageType::Audio(_)
329                                | MessageType::Emote(_)
330                                | MessageType::File(_)
331                                | MessageType::Image(_)
332                                | MessageType::Location(_)
333                                | MessageType::Notice(_)
334                                | MessageType::ServerNotice(_)
335                                | MessageType::Text(_)
336                                | MessageType::Video(_)
337                                | MessageType::VerificationRequest(_) => true,
338                                #[cfg(feature = "unstable-msc4274")]
339                                MessageType::Gallery(_) => true,
340                                _ => false,
341                            }
342                        }
343
344                        AnyMessageLikeEventContent::Sticker(_)
345                        | AnyMessageLikeEventContent::UnstablePollStart(
346                            UnstablePollStartEventContent::New(_),
347                        )
348                        | AnyMessageLikeEventContent::CallInvite(_)
349                        | AnyMessageLikeEventContent::RtcNotification(_)
350                        | AnyMessageLikeEventContent::RoomEncrypted(_) => true,
351
352                        // Beacon location-update events are aggregated onto
353                        // their parent `beacon_info` state event's timeline
354                        // item. They are never rendered as standalone items.
355                        AnyMessageLikeEventContent::Beacon(_) => false,
356                        // Ignore decline events, the matching RtcNotification
357                        // event will be updated to reflect the decline.
358                        AnyMessageLikeEventContent::RtcDecline(_) => false,
359
360                        _ => false,
361                    }
362                }
363            }
364        }
365
366        AnySyncTimelineEvent::State(_) => {
367            // All the state events may get displayed by default.
368            true
369        }
370    }
371}
372
373/// Result of calling [`TimelineController::init_focus`].
374pub(super) struct InitFocusResult {
375    /// Did the initialization result in having some events in the timeline?
376    pub has_events: bool,
377    /// If the timeline is a non-live timeline, an extra task that subscribes to
378    /// changes to the focus source.
379    pub focus_task: Option<BackgroundTaskHandle>,
380}
381
382/// Holds the various info about the current call
383#[derive(Clone, Debug, PartialEq)]
384pub struct ActiveCallInfo {
385    /// The list of users in the call
386    pub active_members: HashSet<OwnedUserId>,
387    /// The consensus intent of the call, audio/video
388    pub call_intent: CallIntentConsensus,
389    /// True if the user (with any device) is currently in the call, meaning
390    /// they have joined and haven't left yet.
391    pub is_joined: bool,
392    /// The timestamp of when the call started, in milliseconds since the unix
393    /// epoch. Currently, this is the origin_server_ts of the rtc.notification
394    /// event.
395    pub call_started_ts_millis: Option<MilliSecondsSinceUnixEpoch>,
396}
397
398impl ActiveCallInfo {
399    pub(crate) fn from_info(room_info: RoomInfo, owned_user_id: OwnedUserId) -> Option<Self> {
400        if room_info.has_active_room_call() {
401            Some(ActiveCallInfo {
402                active_members: HashSet::from(room_info.active_room_call_participants()),
403                call_intent: room_info.active_room_call_consensus_intent(),
404                is_joined: room_info.active_room_call_participants().contains(&owned_user_id),
405                call_started_ts_millis: None,
406            })
407        } else {
408            None
409        }
410    }
411
412    pub(crate) fn with_start_time(self, timestamp: Option<MilliSecondsSinceUnixEpoch>) -> Self {
413        Self { call_started_ts_millis: timestamp, ..self }
414    }
415}
416
417impl<P: RoomDataProvider> TimelineController<P> {
418    pub(super) async fn new(
419        room_data_provider: P,
420        focus: &TimelineFocus,
421        event_cache: &EventCache,
422        internal_id_prefix: Option<String>,
423        unable_to_decrypt_hook: Option<Arc<UtdHookManager>>,
424        is_room_encrypted: bool,
425        settings: TimelineSettings,
426    ) -> Result<Self, Error> {
427        let room_id = room_data_provider.room_id();
428
429        let focus = match focus {
430            TimelineFocus::Live { hide_threaded_events } => TimelineFocusKind::Live {
431                hide_threaded_events: *hide_threaded_events,
432                event_cache: event_cache.room(room_id).await?.0,
433            },
434
435            TimelineFocus::Event { target, thread_mode, num_context_events, .. } => {
436                TimelineFocusKind::Event {
437                    event_cache: event_cache
438                        .event_focused(room_id, target, (*thread_mode).into(), *num_context_events)
439                        .await?
440                        .0,
441                    focused_event_id: target.clone(),
442                    // This will be initialised in `Self::init_focus`.
443                    thread_root: OnceLock::new(),
444                    thread_mode: *thread_mode,
445                }
446            }
447
448            TimelineFocus::Thread { thread_id, .. } => TimelineFocusKind::Thread {
449                event_cache: event_cache.thread(room_id, thread_id).await?.0,
450                thread_id: thread_id.clone(),
451            },
452
453            TimelineFocus::PinnedEvents => TimelineFocusKind::PinnedEvents {
454                event_cache: event_cache.pinned_events(room_id).await?.0,
455            },
456        };
457
458        let focus = Arc::new(focus);
459        let state = TimelineState::new(
460            event_cache.clone(),
461            focus.clone(),
462            room_data_provider.own_user_id().to_owned(),
463            room_data_provider.room_version_rules(),
464            internal_id_prefix,
465            unable_to_decrypt_hook,
466            is_room_encrypted,
467            None,
468        );
469        let fully_read_event_id = state.meta.fully_read_event_id.clone();
470        let state = Arc::new(RwLock::new(state));
471
472        Ok(Self { state, focus, room_data_provider, settings, fully_read_event_id })
473    }
474
475    /// Listens to encryption state changes for the room in
476    /// [`matrix_sdk_base::RoomInfo`] and applies the new value to the existing
477    /// timeline items. This will then cause a refresh of those timeline items.
478    pub async fn handle_encryption_state_changes(&self) {
479        let mut room_info = self.room_data_provider.room_info();
480
481        // Small function helper to help mark as encrypted.
482        let mark_encrypted = || async {
483            let mut state = self.state.write().await;
484            state.meta.is_room_encrypted = true;
485            state.mark_all_events_as_encrypted();
486        };
487
488        if room_info.get().encryption_state().is_encrypted() {
489            // If the room was already encrypted, it won't toggle to
490            // unencrypted, so we can shut down this task early.
491            mark_encrypted().await;
492            return;
493        }
494
495        while let Some(info) = room_info.next().await {
496            if info.encryption_state().is_encrypted() {
497                mark_encrypted().await;
498                // Once the room is encrypted, it cannot switch back to
499                // unencrypted, so our work here is done.
500                break;
501            }
502        }
503    }
504
505    /// Run a lazy backwards pagination (in live mode).
506    ///
507    /// It adjusts the `count` value of the `Skip` higher-order stream so that
508    /// more items are pushed front in the timeline.
509    ///
510    /// If no more items are available (i.e. if the `count` is zero), this
511    /// method returns `Some(needs)` where `needs` is the number of events that
512    /// must be unlazily backwards paginated.
513    pub(super) async fn live_lazy_paginate_backwards(&self, num_events: u16) -> Option<usize> {
514        let state = self.state.read().await;
515
516        let (count, needs) = state
517            .meta
518            .subscriber_skip_count
519            .compute_next_when_paginating_backwards(num_events.into());
520
521        // This always happens on a live timeline.
522        let is_live_timeline = true;
523        state.meta.subscriber_skip_count.update(count, is_live_timeline);
524
525        needs
526    }
527
528    /// Is this timeline receiving events from sync (aka has a live focus)?
529    pub(super) fn is_live(&self) -> bool {
530        matches!(&*self.focus, TimelineFocusKind::Live { .. })
531    }
532
533    /// Is this timeline focused on a thread?
534    pub(super) fn is_threaded(&self) -> bool {
535        self.focus.is_thread()
536    }
537
538    /// The root of the current thread, for a live thread timeline or a
539    /// permalink to a thread message.
540    pub(super) fn thread_root(&self) -> Option<OwnedEventId> {
541        self.focus.thread_root().map(ToOwned::to_owned)
542    }
543
544    /// Get a copy of the current items in the list.
545    ///
546    /// Cheap because `im::Vector` is cheap to clone.
547    pub(super) async fn items(&self) -> Vector<Arc<TimelineItem>> {
548        self.state.read().await.items.clone_items()
549    }
550
551    #[cfg(test)]
552    pub(super) async fn subscribe_raw(
553        &self,
554    ) -> (Vector<Arc<TimelineItem>>, VectorSubscriberStream<Arc<TimelineItem>>) {
555        self.state.read().await.items.subscribe().into_values_and_stream()
556    }
557
558    pub(super) async fn subscribe(&self) -> (Vector<Arc<TimelineItem>>, TimelineSubscriber) {
559        let state = self.state.read().await;
560
561        TimelineSubscriber::new(&state.items, &state.meta.subscriber_skip_count)
562    }
563
564    pub(super) async fn subscribe_filter_map<U, F>(
565        &self,
566        f: F,
567    ) -> (Vector<U>, FilterMap<VectorSubscriberStream<Arc<TimelineItem>>, F>)
568    where
569        U: Clone,
570        F: Fn(Arc<TimelineItem>) -> Option<U>,
571    {
572        self.state.read().await.items.subscribe().filter_map(f)
573    }
574
575    /// Toggle a reaction locally.
576    ///
577    /// Returns true if the reaction was added, false if it was removed.
578    #[instrument(skip_all)]
579    pub(super) async fn toggle_reaction_local(
580        &self,
581        item_id: &TimelineEventItemId,
582        key: &str,
583        extra_content: Option<serde_json::Map<String, serde_json::Value>>,
584    ) -> Result<bool, Error> {
585        let mut state = self.state.write().await;
586
587        let Some((item_pos, item)) = rfind_event_by_item_id(&state.items, item_id) else {
588            warn!("Timeline item not found, can't add reaction");
589            return Err(Error::FailedToToggleReaction);
590        };
591
592        let user_id = self.room_data_provider.own_user_id();
593        let target = item.identifier();
594
595        // The item says whether we reacted; the registry has the handle and
596        // event id.
597        let has_reaction =
598            item.reactions().get(key).is_some_and(|by_user| by_user.contains_key(user_id));
599        let previous = has_reaction
600            .then(|| state.meta.aggregations.find_reaction(&target, key, user_id).cloned())
601            .flatten();
602
603        if has_reaction && previous.is_none() {
604            warn!("reaction is on the item but unknown to the aggregations");
605            return Ok(false);
606        }
607
608        let Some(previous) = previous else {
609            // Adding the new reaction.
610            match item.handle() {
611                TimelineItemHandle::Local(send_handle) => {
612                    if send_handle
613                        .react(key.to_owned())
614                        .await
615                        .map_err(|err| Error::SendQueueError(err.into()))?
616                        .is_some()
617                    {
618                        trace!("adding a reaction to a local echo");
619                        return Ok(true);
620                    }
621
622                    warn!("couldn't toggle reaction for local echo");
623                    return Ok(false);
624                }
625
626                TimelineItemHandle::Remote(event_id) => {
627                    // Add a reaction through the room data provider. No need to
628                    // reflect the effect locally, since the local echo handling
629                    // will take care of it.
630                    trace!("adding a reaction to a remote echo");
631                    let annotation = Annotation::new(event_id.to_owned(), key.to_owned());
632                    self.room_data_provider
633                        .send(ReactionEventContent::from(annotation).into(), extra_content)
634                        .await?;
635                    return Ok(true);
636                }
637            }
638        };
639
640        trace!("removing a previous reaction");
641
642        if previous.is_local() {
643            // Aborting the local echo is enough: its discard removes the
644            // reaction.
645            if let Some(handle) = &previous.send_handle {
646                if !handle.abort().await.map_err(|err| Error::SendQueueError(err.into()))? {
647                    // Impossible state: the reaction has moved from local to
648                    // echo under our feet, but the timeline was supposed to be
649                    // locked!
650                    warn!("unexpectedly unable to abort sending of local reaction");
651                }
652            } else {
653                warn!("no send handle (this should only happen in testing contexts)");
654            }
655            return Ok(false);
656        }
657
658        let TimelineEventItemId::EventId(event_id) = previous.own_id else {
659            warn!("sent reaction without an event id");
660            return Ok(false);
661        };
662
663        // Assume the redaction will work; we'll re-add the reaction if it
664        // didn't.
665        let Some(annotated_event_id) =
666            item.as_remote().map(|event_item| event_item.event_id.clone())
667        else {
668            warn!("remote reaction to remote event, but the associated item isn't remote");
669            return Ok(false);
670        };
671
672        let mut reactions = item.reactions().clone();
673        let reaction_info = reactions.remove_reaction(user_id, key);
674
675        if reaction_info.is_some() {
676            let new_item = item.with_reactions(reactions);
677            state.items.replace(item_pos, new_item);
678        } else {
679            warn!(
680                "reaction is missing on the item, not removing it locally, \
681                 but sending redaction."
682            );
683        }
684
685        // Release the lock before running the request.
686        drop(state);
687
688        trace!("sending redact for a previous reaction");
689        if let Err(err) = self.room_data_provider.redact(&event_id, None, None).await {
690            if let Some(reaction_info) = reaction_info {
691                debug!("sending redact failed, adding the reaction back to the list");
692
693                let mut state = self.state.write().await;
694                if let Some((item_pos, item)) = rfind_event_by_id(&state.items, &annotated_event_id)
695                {
696                    // Re-add the reaction to the mapping.
697                    let mut reactions = item.reactions().clone();
698                    reactions
699                        .entry(key.to_owned())
700                        .or_default()
701                        .insert(user_id.to_owned(), reaction_info);
702                    let new_item = item.with_reactions(reactions);
703                    state.items.replace(item_pos, new_item);
704                } else {
705                    warn!(
706                        "couldn't find item to re-add reaction anymore; \
707                         maybe it's been redacted?"
708                    );
709                }
710            }
711
712            return Err(err);
713        }
714
715        Ok(false)
716    }
717
718    /// The handle for a pending send on an item, see [`SendTarget`].
719    ///
720    /// `None` if there's nothing of that kind left to act on, which a caller
721    /// racing the remote echo can legitimately run into.
722    pub(super) async fn pending_send_handle(
723        &self,
724        item_id: &TimelineEventItemId,
725        target: SendTarget,
726    ) -> Result<Option<SendHandle>, Error> {
727        let state = self.state.read().await;
728
729        let Some((_, item)) = rfind_event_by_item_id(&state.items, item_id) else {
730            return Err(Error::EventNotInTimeline(item_id.clone()));
731        };
732
733        let own_user_id = self.room_data_provider.own_user_id();
734        let target_id = item.identifier();
735        let aggregations = &state.meta.aggregations;
736
737        let handle = match &target {
738            SendTarget::Event => item.local_echo_send_handle(),
739            SendTarget::Edit => aggregations
740                .pending_send_handle(&target_id, |kind| matches!(kind, AggregationKind::Edit(_))),
741            SendTarget::Redaction => aggregations
742                .pending_send_handle(&target_id, |kind| matches!(kind, AggregationKind::Redaction { .. })),
743            SendTarget::Reaction { key } => {
744                aggregations.pending_send_handle(&target_id, |kind| {
745                    matches!(kind, AggregationKind::Reaction { key: k, sender, .. } if k == key && sender == own_user_id)
746                })
747            }
748        };
749
750        Ok(handle)
751    }
752
753    /// Handle updates on events as [`VectorDiff`]s.
754    pub(super) async fn handle_remote_events_with_diffs(
755        &self,
756        diffs: Vec<VectorDiff<TimelineEvent>>,
757        origin: RemoteEventOrigin,
758    ) {
759        if diffs.is_empty() {
760            return;
761        }
762
763        let mut state = self.state.write().await;
764        state
765            .handle_remote_events_with_diffs(
766                diffs,
767                origin,
768                &self.room_data_provider,
769                &self.settings,
770            )
771            .await
772    }
773
774    /// Only handle aggregations received as [`VectorDiff`]s.
775    pub(super) async fn handle_remote_aggregations(
776        &self,
777        diffs: Vec<VectorDiff<TimelineEvent>>,
778        origin: RemoteEventOrigin,
779    ) {
780        if diffs.is_empty() {
781            return;
782        }
783
784        let mut state = self.state.write().await;
785        state
786            .handle_remote_aggregations(diffs, origin, &self.room_data_provider, &self.settings)
787            .await
788    }
789
790    /// Handle an update of the thread summary of a single event that is a
791    /// thread root.
792    pub(super) async fn handle_thread_summary(
793        &self,
794        thread_root: OwnedEventId,
795        thread_summary: ThreadSummary,
796    ) {
797        let mut state = self.state.write().await;
798        state.handle_thread_summary(thread_root, thread_summary, &self.room_data_provider).await
799    }
800
801    pub(super) async fn clear(&self) {
802        self.state.write().await.clear();
803    }
804
805    /// Replaces the content of the current timeline with initial events.
806    ///
807    /// Also sets up read receipts and the read marker for a live timeline of a
808    /// room.
809    ///
810    /// This is all done with a single lock guard, since we don't want the state
811    /// to be modified between the clear and re-insertion of new events.
812    pub(super) async fn replace_with_initial_remote_events<Events>(
813        &self,
814        events: Events,
815        origin: RemoteEventOrigin,
816    ) where
817        Events: IntoIterator,
818        <Events as IntoIterator>::Item: Into<TimelineEvent>,
819    {
820        let mut state = self.state.write().await;
821
822        let track_read_markers = &self.settings.track_read_receipts;
823        if track_read_markers.is_enabled() {
824            state.populate_initial_user_receipt(&self.room_data_provider, ReceiptType::Read).await;
825            state
826                .populate_initial_user_receipt(&self.room_data_provider, ReceiptType::ReadPrivate)
827                .await;
828        }
829
830        // Replace the events if either the current event list or the new one
831        // aren't empty. Previously we just had to check the new one wasn't
832        // empty because we did a clear operation before so the current one
833        // would always be empty, but now we may want to replace a populated
834        // timeline with an empty one.
835        let mut events = events.into_iter().peekable();
836        if !state.items.is_empty() || events.peek().is_some() {
837            state
838                .replace_with_remote_events(
839                    events,
840                    origin,
841                    &self.room_data_provider,
842                    &self.settings,
843                )
844                .await;
845        }
846
847        if track_read_markers.is_enabled() {
848            if let Some(fully_read_event_id) =
849                self.room_data_provider.load_fully_read_marker().await
850            {
851                state.handle_fully_read_marker(fully_read_event_id);
852            } else if let Some(latest_receipt_event_id) = state
853                .latest_user_read_receipt_timeline_event_id(self.room_data_provider.own_user_id())
854            {
855                // Fall back to read receipt if no fully read marker exists.
856                debug!("no `m.fully_read` marker found, falling back to read receipt");
857                state.handle_fully_read_marker(latest_receipt_event_id);
858            }
859        }
860    }
861
862    pub(super) async fn handle_fully_read_marker(&self, fully_read_event_id: OwnedEventId) {
863        self.state.write().await.handle_fully_read_marker(fully_read_event_id);
864    }
865
866    pub(super) async fn handle_active_call_update(
867        &self,
868        maybe_active_call: Option<ActiveCallInfo>,
869    ) {
870        let mut state = self.state.write().await;
871        let mut txn = state.transaction();
872
873        // Store the current active call info in metadata for new
874        // RtcNotification items
875        txn.meta.active_call = maybe_active_call.clone();
876
877        if let Some(existing_event_id) = &txn.meta.active_rtc_notification_event_id {
878            // Clean up the notification event
879            let last_notification = rfind_event_by_id(&txn.items, existing_event_id);
880            if let Some((last_idx, last_notification)) = last_notification {
881                let updated_content = match last_notification.content() {
882                    TimelineItemContent::RtcNotification {
883                        call_intent,
884                        declined_by,
885                        active_call_info: _active_call_info,
886                    } => Some(TimelineItemContent::RtcNotification {
887                        call_intent: call_intent.to_owned(),
888                        declined_by: declined_by.clone(),
889                        active_call_info: maybe_active_call
890                            .clone()
891                            .map(|info| info.with_start_time(last_notification.timestamp.into())),
892                    }),
893                    _ => None,
894                };
895                if let Some(new_content) = updated_content {
896                    let new_event_item = last_notification.inner.with_content(new_content);
897                    let new_timeline_item =
898                        TimelineItem::new(new_event_item, last_notification.internal_id.clone());
899                    txn.items.replace(last_idx, new_timeline_item);
900                }
901
902                if maybe_active_call.is_none() {
903                    // There is no active rtc_notification anymore
904                    txn.meta.active_rtc_notification_event_id = None;
905                }
906            }
907        }
908
909        txn.commit();
910    }
911
912    pub(super) async fn handle_read_receipt_event(&self, event: ReceiptEventContent) {
913        // Don't even take the lock if there are no events to process.
914        if event.is_empty() {
915            return;
916        }
917
918        let mut state = self.state.write().await;
919        state.handle_read_receipt(event, &self.room_data_provider).await;
920    }
921
922    /// Creates the local echo for an event we're sending.
923    #[instrument(skip_all)]
924    pub(super) async fn handle_local_event(
925        &self,
926        txn_id: OwnedTransactionId,
927        content: AnyMessageLikeEventContent,
928        send_handle: Option<SendHandle>,
929    ) {
930        let sender = self.room_data_provider.own_user_id().to_owned();
931        let profile = self.room_data_provider.profile_from_user_id(&sender).await;
932
933        let date_divider_mode = self.settings.date_divider_mode.clone();
934
935        let mut state = self.state.write().await;
936        state
937            .handle_local_event(sender, profile, date_divider_mode, txn_id, send_handle, content)
938            .await;
939    }
940
941    /// Update the send state of a local event represented by a transaction ID.
942    ///
943    /// If the corresponding local timeline item is missing, a warning is
944    /// raised.
945    #[instrument(skip(self))]
946    pub(super) async fn update_event_send_state(
947        &self,
948        txn_id: &TransactionId,
949        send_state: EventSendState,
950    ) {
951        let mut state = self.state.write().await;
952        let mut txn = state.transaction();
953
954        let new_event_id: Option<&EventId> =
955            as_variant!(&send_state, EventSendState::Sent { event_id } => event_id);
956
957        // The local echoes are always at the end of the timeline, we must first
958        // make sure the remote echo hasn't showed up yet.
959        if rfind_event_item(&txn.items, |it| {
960            new_event_id.is_some() && it.event_id() == new_event_id && it.as_remote().is_some()
961        })
962        .is_some()
963        {
964            // Remote echo already received. This is very unlikely.
965            trace!("Remote echo received before send-event response");
966
967            let local_echo = rfind_event_item(&txn.items, |it| it.transaction_id() == Some(txn_id));
968
969            // If there's both the remote echo and a local echo, that means the
970            // remote echo was received before the response _and_ contained no
971            // transaction ID (and thus duplicated the local echo).
972            if let Some((idx, _)) = local_echo {
973                warn!("Message echo got duplicated, removing the local one");
974                txn.items.remove(idx);
975
976                // Adjust the date dividers, if needs be.
977                let mut adjuster =
978                    DateDividerAdjuster::new(self.settings.date_divider_mode.clone());
979                adjuster.run(&mut txn.items, &mut txn.meta);
980            }
981
982            txn.commit();
983            return;
984        }
985
986        // Look for the local event by the transaction ID or event ID.
987        let result = rfind_event_item(&txn.items, |it| {
988            it.transaction_id() == Some(txn_id)
989                || new_event_id.is_some()
990                    && it.event_id() == new_event_id
991                    && it.as_local().is_some()
992        });
993
994        let Some((idx, item)) = result else {
995            // Not a standalone item: maybe one of our aggregations.
996            if txn.meta.aggregations.update_send_state(
997                txn_id.to_owned(),
998                send_state,
999                &mut txn.items,
1000                &txn.meta.room_version_rules,
1001            ) {
1002                trace!("Updated the send state of an aggregation");
1003                txn.commit();
1004                return;
1005            }
1006
1007            warn!("Timeline item not found, can't update send state");
1008            return;
1009        };
1010
1011        let Some(local_item) = item.as_local() else {
1012            warn!("We looked for a local item, but it transitioned to remote.");
1013            return;
1014        };
1015
1016        // The event was already marked as sent, that's a broken state, let's
1017        // emit an error but also override to the given sent state.
1018        if let EventSendState::Sent { event_id: existing_event_id } = &local_item.send_state {
1019            error!(?existing_event_id, ?new_event_id, "Local echo already marked as sent");
1020        }
1021
1022        // If the event has just been marked as sent, update the aggregations
1023        // mapping to take that into account.
1024        if let Some(new_event_id) = new_event_id {
1025            txn.meta.aggregations.mark_target_as_sent(txn_id.to_owned(), new_event_id.to_owned());
1026        }
1027
1028        let new_item = item.with_inner_kind(local_item.with_send_state(send_state));
1029        txn.items.replace(idx, new_item);
1030
1031        txn.commit();
1032    }
1033
1034    pub(super) async fn discard_local_echo(&self, txn_id: &TransactionId) -> bool {
1035        let mut state = self.state.write().await;
1036
1037        if let Some((idx, _)) =
1038            rfind_event_item(&state.items, |it| it.transaction_id() == Some(txn_id))
1039        {
1040            let mut txn = state.transaction();
1041
1042            txn.items.remove(idx);
1043
1044            // A read marker or a date divider may have been inserted before the
1045            // local echo. Ensure both are up to date.
1046            let mut adjuster = DateDividerAdjuster::new(self.settings.date_divider_mode.clone());
1047            adjuster.run(&mut txn.items, &mut txn.meta);
1048
1049            txn.meta.update_read_marker(&mut txn.items);
1050
1051            txn.commit();
1052
1053            debug!("discarded local echo");
1054            return true;
1055        }
1056
1057        // Avoid multiple mutable and immutable borrows of the lock guard by
1058        // explicitly dereferencing it once.
1059        let mut txn = state.transaction();
1060
1061        // Look if this was a local aggregation.
1062        let found_aggregation = match txn.meta.aggregations.try_remove_aggregation(
1063            &TimelineEventItemId::TransactionId(txn_id.to_owned()),
1064            &mut txn.items,
1065        ) {
1066            Ok(val) => val,
1067            Err(err) => {
1068                warn!("error when discarding local echo for an aggregation: {err}");
1069                // The aggregation has been found, it's just that we couldn't
1070                // discard it.
1071                true
1072            }
1073        };
1074
1075        if found_aggregation {
1076            txn.commit();
1077        }
1078
1079        found_aggregation
1080    }
1081
1082    pub(super) async fn replace_local_echo(
1083        &self,
1084        txn_id: &TransactionId,
1085        content: AnyMessageLikeEventContent,
1086    ) -> bool {
1087        let AnyMessageLikeEventContent::RoomMessage(content) = content else {
1088            // Ideally, we'd support replacing local echoes for a reaction,
1089            // etc., but handling RoomMessage should be sufficient in most
1090            // cases. Worst case, the local echo will be sent Soonâ„¢ and we'll
1091            // get another chance at editing the event then.
1092            warn!("Replacing a local echo for a non-RoomMessage-like event NYI");
1093            return false;
1094        };
1095
1096        let mut state = self.state.write().await;
1097        let mut txn = state.transaction();
1098
1099        let Some((idx, prev_item)) =
1100            rfind_event_item(&txn.items, |it| it.transaction_id() == Some(txn_id))
1101        else {
1102            // Not a standalone item: maybe one of our pending edits.
1103            if let Some(Relation::Replacement(replacement)) = content.relates_to
1104                && txn.meta.aggregations.replace_local_edit(
1105                    txn_id,
1106                    replacement,
1107                    &mut txn.items,
1108                    &txn.meta.room_version_rules,
1109                )
1110            {
1111                debug!("Replaced local echo of an edit");
1112                txn.commit();
1113                return true;
1114            }
1115
1116            debug!("Can't find local echo to replace");
1117            return false;
1118        };
1119
1120        // Reuse the previous local echo's state, but reset the send state to
1121        // not sent (per API contract).
1122        let ti_kind = {
1123            let Some(prev_local_item) = prev_item.as_local() else {
1124                warn!("We looked for a local item, but it transitioned as remote??");
1125                return false;
1126            };
1127            // If the local echo had an upload progress, retain it.
1128            let progress = as_variant!(&prev_local_item.send_state,
1129                EventSendState::NotSentYet { progress } => progress.clone())
1130            .flatten();
1131            prev_local_item.with_send_state(EventSendState::NotSentYet { progress })
1132        };
1133
1134        // Replace the local-related state (kind) and the content state.
1135        let new_item = TimelineItem::new(
1136            prev_item.with_kind(ti_kind).with_content(TimelineItemContent::message(
1137                content.msgtype,
1138                content.mentions,
1139                prev_item.content().thread_root(),
1140                prev_item.content().in_reply_to(),
1141                prev_item.content().thread_summary(),
1142            )),
1143            prev_item.internal_id.to_owned(),
1144        );
1145
1146        txn.items.replace(idx, new_item);
1147
1148        // This doesn't change the original sending time, so there's no need to
1149        // adjust date dividers.
1150
1151        txn.commit();
1152
1153        debug!("Replaced local echo");
1154        true
1155    }
1156
1157    pub(super) async fn compute_redecryption_candidates(
1158        &self,
1159    ) -> (BTreeSet<String>, BTreeSet<String>) {
1160        let state = self.state.read().await;
1161        compute_redecryption_candidates(&state.items)
1162    }
1163
1164    pub(super) async fn set_sender_profiles_pending(&self) {
1165        self.set_non_ready_sender_profiles(TimelineDetails::Pending).await;
1166    }
1167
1168    pub(super) async fn set_sender_profiles_error(&self, error: Arc<matrix_sdk::Error>) {
1169        self.set_non_ready_sender_profiles(TimelineDetails::Error(error)).await;
1170    }
1171
1172    async fn set_non_ready_sender_profiles(&self, profile_state: TimelineDetails<Profile>) {
1173        self.state.write().await.items.for_each(|mut entry| {
1174            let Some(event_item) = entry.as_event() else { return };
1175            if !matches!(event_item.sender_profile(), TimelineDetails::Ready(_)) {
1176                let new_item = entry.with_kind(TimelineItemKind::Event(
1177                    event_item.with_sender_profile(profile_state.clone()),
1178                ));
1179                ObservableItemsEntry::replace(&mut entry, new_item);
1180            }
1181        });
1182    }
1183
1184    pub(super) async fn update_missing_sender_profiles(&self) {
1185        trace!("Updating missing sender profiles");
1186
1187        let mut state = self.state.write().await;
1188        let mut entries = state.items.entries();
1189        while let Some(mut entry) = entries.next() {
1190            let Some(event_item) = entry.as_event() else { continue };
1191            let event_id = event_item.event_id().map(debug);
1192            let transaction_id = event_item.transaction_id().map(debug);
1193
1194            if event_item.sender_profile().is_ready() {
1195                trace!(event_id, transaction_id, "Profile already set");
1196                continue;
1197            }
1198
1199            match self.room_data_provider.profile_from_user_id(event_item.sender()).await {
1200                Some(profile) => {
1201                    trace!(event_id, transaction_id, "Adding profile");
1202                    let updated_item =
1203                        event_item.with_sender_profile(TimelineDetails::Ready(profile));
1204                    let new_item = entry.with_kind(updated_item);
1205                    ObservableItemsEntry::replace(&mut entry, new_item);
1206                }
1207                None => {
1208                    if !event_item.sender_profile().is_unavailable() {
1209                        trace!(event_id, transaction_id, "Marking profile unavailable");
1210                        let updated_item =
1211                            event_item.with_sender_profile(TimelineDetails::Unavailable);
1212                        let new_item = entry.with_kind(updated_item);
1213                        ObservableItemsEntry::replace(&mut entry, new_item);
1214                    } else {
1215                        debug!(event_id, transaction_id, "Profile already marked unavailable");
1216                    }
1217                }
1218            }
1219        }
1220
1221        trace!("Done updating missing sender profiles");
1222    }
1223
1224    /// Update the profiles of the given senders, even if they are ready.
1225    pub(super) async fn force_update_sender_profiles(&self, sender_ids: &BTreeSet<&UserId>) {
1226        trace!("Forcing update of sender profiles: {sender_ids:?}");
1227
1228        let mut state = self.state.write().await;
1229        let mut entries = state.items.entries();
1230        while let Some(mut entry) = entries.next() {
1231            let Some(event_item) = entry.as_event() else { continue };
1232            if !sender_ids.contains(event_item.sender()) {
1233                continue;
1234            }
1235
1236            let event_id = event_item.event_id().map(debug);
1237            let transaction_id = event_item.transaction_id().map(debug);
1238
1239            match self.room_data_provider.profile_from_user_id(event_item.sender()).await {
1240                Some(profile) => {
1241                    if matches!(event_item.sender_profile(), TimelineDetails::Ready(old_profile) if *old_profile == profile)
1242                    {
1243                        debug!(event_id, transaction_id, "Profile already up-to-date");
1244                    } else {
1245                        trace!(event_id, transaction_id, "Updating profile");
1246                        let updated_item =
1247                            event_item.with_sender_profile(TimelineDetails::Ready(profile));
1248                        let new_item = entry.with_kind(updated_item);
1249                        ObservableItemsEntry::replace(&mut entry, new_item);
1250                    }
1251                }
1252                None => {
1253                    if !event_item.sender_profile().is_unavailable() {
1254                        trace!(event_id, transaction_id, "Marking profile unavailable");
1255                        let updated_item =
1256                            event_item.with_sender_profile(TimelineDetails::Unavailable);
1257                        let new_item = entry.with_kind(updated_item);
1258                        ObservableItemsEntry::replace(&mut entry, new_item);
1259                    } else {
1260                        debug!(event_id, transaction_id, "Profile already marked unavailable");
1261                    }
1262                }
1263            }
1264        }
1265
1266        trace!("Done forcing update of sender profiles");
1267    }
1268
1269    #[cfg(test)]
1270    pub(super) async fn handle_read_receipts(&self, receipt_event_content: ReceiptEventContent) {
1271        let own_user_id = self.room_data_provider.own_user_id();
1272        self.state.write().await.handle_read_receipts(receipt_event_content, own_user_id);
1273    }
1274
1275    /// Get the latest read receipt for the given user.
1276    ///
1277    /// Useful to get the latest read receipt, whether it's private or public.
1278    pub(super) async fn latest_user_read_receipt(
1279        &self,
1280        user_id: &UserId,
1281    ) -> Option<(OwnedEventId, Receipt)> {
1282        let receipt_thread = self.focus.receipt_thread();
1283
1284        self.state
1285            .read()
1286            .await
1287            .latest_user_read_receipt(
1288                user_id,
1289                receipt_thread,
1290                &self.room_data_provider,
1291                read_receipts::ImplicitReadReceipts::Include,
1292            )
1293            .await
1294    }
1295
1296    /// Get the ID of the timeline event with the latest read receipt for the
1297    /// given user.
1298    pub(super) async fn latest_user_read_receipt_timeline_event_id(
1299        &self,
1300        user_id: &UserId,
1301    ) -> Option<OwnedEventId> {
1302        self.state.read().await.latest_user_read_receipt_timeline_event_id(user_id)
1303    }
1304
1305    /// Subscribe to changes in the read receipts of our own user.
1306    pub async fn subscribe_own_user_read_receipts_changed(
1307        &self,
1308    ) -> impl Stream<Item = ()> + use<P> {
1309        self.state.read().await.meta.read_receipts.subscribe_own_user_read_receipts_changed()
1310    }
1311
1312    /// Handle a room send update that's a new local echo.
1313    pub(crate) async fn handle_local_echo(&self, echo: LocalEcho) {
1314        match echo.content {
1315            LocalEchoContent::Event { serialized_event, send_handle, send_error } => {
1316                let content = match serialized_event.deserialize() {
1317                    Ok(d) => d,
1318                    Err(err) => {
1319                        warn!("error deserializing local echo: {err}");
1320                        return;
1321                    }
1322                };
1323
1324                self.handle_local_event(echo.transaction_id.clone(), content, Some(send_handle))
1325                    .await;
1326
1327                if let Some(send_error) = send_error {
1328                    self.update_event_send_state(
1329                        &echo.transaction_id,
1330                        EventSendState::SendingFailed {
1331                            error: Arc::new(matrix_sdk::Error::SendQueueWedgeError(Box::new(
1332                                send_error,
1333                            ))),
1334                            is_recoverable: false,
1335                        },
1336                    )
1337                    .await;
1338                }
1339            }
1340
1341            LocalEchoContent::React { key, send_handle, applies_to } => {
1342                self.handle_local_reaction(key, send_handle, applies_to).await;
1343            }
1344
1345            LocalEchoContent::Redaction { redacts, reason, send_handle, send_error } => {
1346                self.handle_local_redaction(
1347                    echo.transaction_id.clone(),
1348                    redacts,
1349                    reason,
1350                    Some(send_handle),
1351                )
1352                .await;
1353
1354                if let Some(send_error) = send_error {
1355                    self.update_event_send_state(
1356                        &echo.transaction_id,
1357                        EventSendState::SendingFailed {
1358                            error: Arc::new(matrix_sdk::Error::SendQueueWedgeError(Box::new(
1359                                send_error,
1360                            ))),
1361                            is_recoverable: false,
1362                        },
1363                    )
1364                    .await;
1365                }
1366            }
1367        }
1368    }
1369
1370    /// Adds a reaction (local echo) to a local echo.
1371    #[instrument(skip(self, send_handle))]
1372    async fn handle_local_reaction(
1373        &self,
1374        reaction_key: String,
1375        send_handle: SendHandle,
1376        applies_to: OwnedTransactionId,
1377    ) {
1378        let mut state = self.state.write().await;
1379        let mut tr = state.transaction();
1380
1381        let target = TimelineEventItemId::TransactionId(applies_to);
1382
1383        let reaction_txn_id = send_handle.transaction_id().to_owned();
1384        let aggregation = Aggregation::new_local(
1385            TimelineEventItemId::TransactionId(reaction_txn_id),
1386            AggregationKind::Reaction {
1387                key: reaction_key.clone(),
1388                sender: self.room_data_provider.own_user_id().to_owned(),
1389                timestamp: MilliSecondsSinceUnixEpoch::now(),
1390            },
1391            Some(send_handle),
1392        );
1393
1394        tr.meta.aggregations.add(target.clone(), aggregation.clone());
1395        find_item_and_apply_aggregation(
1396            &tr.meta.aggregations,
1397            &mut tr.items,
1398            &target,
1399            aggregation,
1400            &tr.meta.room_version_rules,
1401        );
1402
1403        tr.commit();
1404    }
1405
1406    /// Applies a local echo of a redaction.
1407    pub(super) async fn handle_local_redaction(
1408        &self,
1409        txn_id: OwnedTransactionId,
1410        redacts: OwnedEventId,
1411        reason: Option<String>,
1412        send_handle: Option<SendHandle>,
1413    ) {
1414        let mut state = self.state.write().await;
1415        let mut tr = state.transaction();
1416
1417        let target = TimelineEventItemId::EventId(redacts);
1418
1419        let aggregation = Aggregation::new_local(
1420            TimelineEventItemId::TransactionId(txn_id),
1421            AggregationKind::Redaction { reason },
1422            send_handle,
1423        );
1424
1425        tr.meta.aggregations.add(target.clone(), aggregation.clone());
1426        find_item_and_apply_aggregation(
1427            &tr.meta.aggregations,
1428            &mut tr.items,
1429            &target,
1430            aggregation,
1431            &tr.meta.room_version_rules,
1432        );
1433
1434        tr.commit();
1435    }
1436
1437    /// Handle a single room send queue update.
1438    pub(crate) async fn handle_room_send_queue_update(&self, update: RoomSendQueueUpdate) {
1439        match update {
1440            RoomSendQueueUpdate::NewLocalEvent(echo) => {
1441                self.handle_local_echo(echo).await;
1442            }
1443
1444            RoomSendQueueUpdate::CancelledLocalEvent { transaction_id } => {
1445                if !self.discard_local_echo(&transaction_id).await {
1446                    warn!("couldn't find the local echo to discard");
1447                }
1448            }
1449
1450            RoomSendQueueUpdate::ReplacedLocalEvent { transaction_id, new_content } => {
1451                let content = match new_content.deserialize() {
1452                    Ok(d) => d,
1453                    Err(err) => {
1454                        warn!("error deserializing local echo (upon edit): {err}");
1455                        return;
1456                    }
1457                };
1458
1459                if !self.replace_local_echo(&transaction_id, content).await {
1460                    warn!("couldn't find the local echo to replace");
1461                }
1462            }
1463
1464            RoomSendQueueUpdate::SendError { transaction_id, error, is_recoverable } => {
1465                self.update_event_send_state(
1466                    &transaction_id,
1467                    EventSendState::SendingFailed { error, is_recoverable },
1468                )
1469                .await;
1470            }
1471
1472            RoomSendQueueUpdate::RetryEvent { transaction_id } => {
1473                self.update_event_send_state(
1474                    &transaction_id,
1475                    EventSendState::NotSentYet { progress: None },
1476                )
1477                .await;
1478            }
1479
1480            RoomSendQueueUpdate::SentEvent { transaction_id, event_id } => {
1481                self.update_event_send_state(&transaction_id, EventSendState::Sent { event_id })
1482                    .await;
1483            }
1484
1485            RoomSendQueueUpdate::MediaUpload { related_to, index, progress, .. } => {
1486                self.update_event_send_state(
1487                    &related_to,
1488                    EventSendState::NotSentYet {
1489                        progress: Some(MediaUploadProgress { index, progress }),
1490                    },
1491                )
1492                .await;
1493            }
1494        }
1495    }
1496
1497    /// Insert a timeline start item at the beginning of the room, if it's
1498    /// missing.
1499    pub async fn insert_timeline_start_if_missing(&self) {
1500        let mut state = self.state.write().await;
1501        let mut txn = state.transaction();
1502        txn.items.push_timeline_start_if_missing(
1503            txn.meta.new_timeline_item(VirtualTimelineItem::TimelineStart),
1504        );
1505        txn.commit();
1506    }
1507
1508    /// Create a [`EmbeddedEvent`] from an arbitrary event, be it in the
1509    /// timeline or not.
1510    ///
1511    /// Can be `None` if the event cannot be represented as a standalone item,
1512    /// because it's an aggregation.
1513    pub(super) async fn make_replied_to(
1514        &self,
1515        event: TimelineEvent,
1516    ) -> Result<Option<EmbeddedEvent>, Error> {
1517        let state = self.state.read().await;
1518        EmbeddedEvent::try_from_timeline_event(event, &self.room_data_provider, &state.meta).await
1519    }
1520}
1521
1522impl TimelineController {
1523    pub(super) fn room(&self) -> &Room {
1524        &self.room_data_provider
1525    }
1526
1527    /// Initializes the configured timeline focus with appropriate data.
1528    ///
1529    /// Should be called only once after creation of the [`TimelineController`],
1530    /// with all its fields set.
1531    ///
1532    /// `initial_live_events` are the events of the room's event cache, as
1533    /// returned when subscribing to it. They're only used for a live focus.
1534    pub(super) async fn init_focus(
1535        &self,
1536        initial_live_events: Vec<TimelineEvent>,
1537    ) -> Result<InitFocusResult, Error> {
1538        match self.focus.deref() {
1539            TimelineFocusKind::Live { event_cache, .. } => {
1540                // Add the cached events to the timeline.
1541                let events = initial_live_events;
1542
1543                let has_events = !events.is_empty();
1544
1545                self.replace_with_initial_remote_events(events, RemoteEventOrigin::Cache).await;
1546
1547                match event_cache.pagination().status().get() {
1548                    PaginationStatus::Idle { hit_timeline_start } => {
1549                        if hit_timeline_start {
1550                            // Eagerly insert the timeline start item, since
1551                            // pagination claims we've already hit the timeline
1552                            // start.
1553                            self.insert_timeline_start_if_missing().await;
1554                        }
1555                    }
1556                    PaginationStatus::Paginating => {}
1557                }
1558
1559                Ok(InitFocusResult { has_events, focus_task: None })
1560            }
1561
1562            TimelineFocusKind::Event {
1563                focused_event_id: event_id,
1564                thread_mode,
1565                thread_root: focus_thread_root,
1566                event_cache,
1567                ..
1568            } => {
1569                let (events, receiver) = event_cache.subscribe().await?;
1570
1571                let has_events = !events.is_empty();
1572
1573                // Ask the cache for the thread root, if it managed to extract
1574                // one or decided that the target event was the thread root.
1575                if let Some(thread_root) = event_cache.thread_root().await? {
1576                    focus_thread_root.get_or_init(|| thread_root);
1577                }
1578
1579                self.replace_with_initial_remote_events(events, RemoteEventOrigin::Pagination)
1580                    .await;
1581
1582                let task = self
1583                    .room_data_provider
1584                    .client()
1585                    .task_monitor()
1586                    .spawn_infinite_task(
1587                        "timeline::event_focused_cache_updates",
1588                        event_focused_task(
1589                            event_id.clone(),
1590                            (*thread_mode).into(),
1591                            event_cache.clone(),
1592                            self.clone(),
1593                            receiver,
1594                        ),
1595                    )
1596                    .abort_on_drop();
1597
1598                Ok(InitFocusResult { has_events, focus_task: Some(task) })
1599            }
1600
1601            TimelineFocusKind::Thread { event_cache, .. } => {
1602                let (has_events, subscriber) = self.init_with_thread_root(event_cache).await?;
1603
1604                let room = &self.room_data_provider;
1605                let span = info_span!(
1606                    parent: Span::none(),
1607                    "thread_live_update_handler",
1608                    room_id = ?room.room_id(),
1609                );
1610                span.follows_from(Span::current());
1611
1612                let task = room
1613                    .client()
1614                    .task_monitor()
1615                    .spawn_infinite_task(
1616                        "timeline::thread_event_cache_updates",
1617                        thread_updates_task(subscriber, event_cache.clone(), self.clone())
1618                            .instrument(span),
1619                    )
1620                    .abort_on_drop();
1621
1622                Ok(InitFocusResult { has_events, focus_task: Some(task) })
1623            }
1624
1625            TimelineFocusKind::PinnedEvents { event_cache } => {
1626                let (initial_events, pinned_events_recv) = event_cache.subscribe().await?;
1627
1628                let has_events = !initial_events.is_empty();
1629
1630                self.replace_with_initial_remote_events(
1631                    initial_events,
1632                    RemoteEventOrigin::Pagination,
1633                )
1634                .await;
1635
1636                let task = self
1637                    .room_data_provider
1638                    .client()
1639                    .task_monitor()
1640                    .spawn_infinite_task(
1641                        "timeline::pinned_events_cache_updates",
1642                        pinned_events_task(event_cache.clone(), self.clone(), pinned_events_recv),
1643                    )
1644                    .abort_on_drop();
1645
1646                Ok(InitFocusResult { has_events, focus_task: Some(task) })
1647            }
1648        }
1649    }
1650
1651    /// (Re-)initialise a timeline using [`TimelineFocus::Thread`] with cached
1652    /// threaded events and secondary relations.
1653    ///
1654    /// Returns whether there were any events added to the timeline, and a
1655    /// receiver to return updates after the initial events have been inserted
1656    /// in the timeline.
1657    pub(super) async fn init_with_thread_root(
1658        &self,
1659        event_cache: &ThreadEventCache,
1660    ) -> Result<(bool, EventCacheSubscriber<ThreadEventCacheUpdate>), Error> {
1661        let (events, subscriber) = event_cache.subscribe().await?;
1662        let has_events = !events.is_empty();
1663
1664        // For each event, we also need to find the related events, as they
1665        // don't include the thread relationship, they won't be included in the
1666        // initial list of events.
1667        //
1668        // The lookups are independent store queries, so run them together
1669        // rather than awaiting them one after the other. `try_join_all` keeps
1670        // the input order, so the related events are collected in the same
1671        // order as before.
1672        let lookups = events
1673            .iter()
1674            .filter_map(|event| event.event_id())
1675            .map(|event_id| event_cache.find_event_with_relations(event_id, None));
1676
1677        let mut related_events = Vector::new();
1678        for (_original, related) in try_join_all(lookups).await?.into_iter().flatten() {
1679            related_events.extend(related);
1680        }
1681
1682        self.replace_with_initial_remote_events(events, RemoteEventOrigin::Cache).await;
1683
1684        // Now that we've inserted the thread events, add the aggregations too.
1685        if !related_events.is_empty() {
1686            self.handle_remote_aggregations(
1687                vec![VectorDiff::Append { values: related_events }],
1688                RemoteEventOrigin::Cache,
1689            )
1690            .await;
1691        }
1692
1693        Ok((has_events, subscriber))
1694    }
1695
1696    /// Given an event identifier, will fetch the details for the event it's
1697    /// replying to, if applicable.
1698    #[instrument(skip(self))]
1699    pub(super) async fn fetch_in_reply_to_details(&self, event_id: &EventId) -> Result<(), Error> {
1700        let state_guard = self.state.write().await;
1701        let (index, item) = rfind_event_by_id(&state_guard.items, event_id)
1702            .ok_or(Error::EventNotInTimeline(TimelineEventItemId::EventId(event_id.to_owned())))?;
1703        let remote_item = item
1704            .as_remote()
1705            .ok_or(Error::EventNotInTimeline(TimelineEventItemId::EventId(event_id.to_owned())))?
1706            .clone();
1707
1708        let TimelineItemContent::MsgLike(msglike) = item.content().clone() else {
1709            debug!("Event is not a message");
1710            return Ok(());
1711        };
1712        let Some(in_reply_to) = msglike.in_reply_to.clone() else {
1713            debug!("Event is not a reply");
1714            return Ok(());
1715        };
1716        if let TimelineDetails::Pending = &in_reply_to.event {
1717            debug!("Replied-to event is already being fetched");
1718            return Ok(());
1719        }
1720        if let TimelineDetails::Ready(_) = &in_reply_to.event {
1721            debug!("Replied-to event has already been fetched");
1722            return Ok(());
1723        }
1724
1725        let internal_id = item.internal_id.to_owned();
1726        let item = item.clone();
1727        let event = fetch_replied_to_event(
1728            state_guard,
1729            &self.state,
1730            index,
1731            &item,
1732            internal_id,
1733            &msglike,
1734            &in_reply_to.event_id,
1735            self.room(),
1736        )
1737        .await?;
1738
1739        // We need to be sure to have the latest position of the event as it
1740        // might have changed while waiting for the request.
1741        let mut state = self.state.write().await;
1742        let (index, item) = rfind_event_by_id(&state.items, &remote_item.event_id)
1743            .ok_or(Error::EventNotInTimeline(TimelineEventItemId::EventId(event_id.to_owned())))?;
1744
1745        // Check the state of the event again, it might have been redacted while
1746        // the request was in-flight.
1747        let TimelineItemContent::MsgLike(MsgLikeContent {
1748            kind: MsgLikeKind::Message(message),
1749            thread_root,
1750            in_reply_to,
1751            thread_summary,
1752        }) = item.content().clone()
1753        else {
1754            info!("Event is no longer a message (redacted?)");
1755            return Ok(());
1756        };
1757        let Some(in_reply_to) = in_reply_to else {
1758            warn!("Event no longer has a reply (bug?)");
1759            return Ok(());
1760        };
1761
1762        // Now that we've received the content of the replied-to event, replace
1763        // the replied-to content in the item with it.
1764        trace!("Updating in-reply-to details");
1765        let internal_id = item.internal_id.to_owned();
1766        let mut item = item.clone();
1767        item.set_content(TimelineItemContent::MsgLike(MsgLikeContent {
1768            kind: MsgLikeKind::Message(message),
1769            thread_root,
1770            in_reply_to: Some(InReplyToDetails { event_id: in_reply_to.event_id, event }),
1771            thread_summary,
1772        }));
1773        state.items.replace(index, TimelineItem::new(item, internal_id));
1774
1775        Ok(())
1776    }
1777
1778    /// Returns the thread that should be used for a read receipt based on the
1779    /// current focus of the timeline and the receipt type.
1780    ///
1781    /// A `SendReceiptType::FullyRead` will always use
1782    /// `ReceiptThread::Unthreaded`
1783    pub(super) fn infer_thread_for_read_receipt(
1784        &self,
1785        receipt_type: &SendReceiptType,
1786    ) -> ReceiptThread {
1787        if matches!(receipt_type, SendReceiptType::FullyRead) {
1788            ReceiptThread::Unthreaded
1789        } else {
1790            self.focus.receipt_thread()
1791        }
1792    }
1793
1794    /// Decide whether a read receipt should be sent, and which event it should
1795    /// target.
1796    ///
1797    /// The returned event may differ from `event_id`: a read receipt should not
1798    /// point at one of the user's own events (see the Matrix spec's
1799    /// [Receipts module]), so if `event_id` is one of theirs, the latest unread
1800    /// event before it that is targeted instead.
1801    ///
1802    /// - When there's no such earlier event and `is_marking_room_as_read` is
1803    ///   `false`, [`SendReceiptDecision::DoNotSend`] is returned.
1804    /// - When `is_marking_room_as_read` is `true`, the receipt falls back to
1805    ///   `event_id` itself if it is explicitly unread, so that the homeserver
1806    ///   still recomputes the push/badge count.
1807    ///
1808    /// [Receipts module]: https://spec.matrix.org/latest/client-server-api/#receipts
1809    pub(super) async fn should_send_receipt(
1810        &self,
1811        receipt_type: &SendReceiptType,
1812        receipt_thread: &ReceiptThread,
1813        event_id: &EventId,
1814        is_marking_room_as_read: bool,
1815    ) -> SendReceiptDecision {
1816        let own_user_id = self.room().own_user_id();
1817        let state = self.state.read().await;
1818        let room = self.room();
1819        let all_remote_events = state.items.all_remote_events();
1820
1821        // Resolve the event the receipt should target, redirecting away from
1822        // the user's own events for read receipts.
1823        let target_event_id = match receipt_type {
1824            SendReceiptType::Read | SendReceiptType::ReadPrivate => {
1825                let is_own_event = all_remote_events
1826                    .get_by_event_id(event_id)
1827                    .and_then(|event_meta| event_meta.sender.as_deref())
1828                    == Some(own_user_id);
1829
1830                if is_own_event {
1831                    let filter_out_thread_events = match self.focus() {
1832                        TimelineFocusKind::Thread { .. } | TimelineFocusKind::Event { .. } => false,
1833                        TimelineFocusKind::Live { hide_threaded_events, .. } => {
1834                            *hide_threaded_events
1835                        }
1836                        TimelineFocusKind::PinnedEvents { .. } => true,
1837                    };
1838
1839                    let previous_event = all_remote_events
1840                        .iter()
1841                        .rev()
1842                        // Only consider the events that precede the requested one.
1843                        .skip_while(|event_meta| event_meta.event_id != *event_id)
1844                        .skip(1)
1845                        // Never point a read receipt at one of the user's own events.
1846                        .filter(|event_meta| event_meta.sender.as_deref() != Some(own_user_id))
1847                        .find_map(|event_meta| {
1848                            if !filter_out_thread_events {
1849                                Some(event_meta.event_id.clone())
1850                            } else if event_meta.thread_root_id.is_none() {
1851                                if let Some(TimelineEventItemId::EventId(aggregated_event_id)) =
1852                                    state.meta.aggregations.is_aggregation_of(
1853                                        &TimelineEventItemId::EventId(event_meta.event_id.clone()),
1854                                    )
1855                                    && let Some(target_meta) =
1856                                        all_remote_events.get_by_event_id(aggregated_event_id)
1857                                    && target_meta.thread_root_id.is_some()
1858                                {
1859                                    None
1860                                } else {
1861                                    Some(event_meta.event_id.clone())
1862                                }
1863                            } else {
1864                                None
1865                            }
1866                        });
1867
1868                    match previous_event {
1869                        Some(event_id) => event_id,
1870                        // Nothing from another user to point at. When marking
1871                        // the room as read, fall back to the user's own event
1872                        // so the homeserver still recomputes its push/badge
1873                        // count; otherwise there's nothing to send.
1874                        None if is_marking_room_as_read => event_id.to_owned(),
1875                        None => return SendReceiptDecision::DoNotSend,
1876                    }
1877                } else {
1878                    event_id.to_owned()
1879                }
1880            }
1881
1882            _ => event_id.to_owned(),
1883        };
1884
1885        // Find the real receipt the homeserver already knows about.
1886        let previous_event_id = match receipt_type {
1887            SendReceiptType::Read => state
1888                .meta
1889                .user_receipt(
1890                    own_user_id,
1891                    ReceiptType::Read,
1892                    receipt_thread.clone(),
1893                    room,
1894                    all_remote_events,
1895                    read_receipts::ImplicitReadReceipts::Exclude,
1896                )
1897                .await
1898                .map(|(event_id, _)| event_id),
1899
1900            // Implicit read receipts are saved as public read receipts, so get
1901            // the latest. It also doesn't make sense to have a private read
1902            // receipt behind a public one.
1903            SendReceiptType::ReadPrivate => state
1904                .latest_user_read_receipt(
1905                    own_user_id,
1906                    receipt_thread.clone(),
1907                    room,
1908                    read_receipts::ImplicitReadReceipts::Exclude,
1909                )
1910                .await
1911                .map(|(event_id, _)| event_id),
1912
1913            SendReceiptType::FullyRead => self.room_data_provider.load_fully_read_marker().await,
1914
1915            _ => None,
1916        };
1917
1918        // Don't send anything if the resolved event isn't more recent than
1919        // that.
1920        if let Some(previous_event_id) = previous_event_id {
1921            trace!(%previous_event_id, "found a previous receipt");
1922            if let Some(relative_pos) = TimelineMetadata::compare_events_positions(
1923                &previous_event_id,
1924                &target_event_id,
1925                all_remote_events,
1926            ) && relative_pos != RelativePosition::After
1927            {
1928                return SendReceiptDecision::DoNotSend;
1929            }
1930        }
1931
1932        // No previous receipt was found (or it's an unknown one): let the
1933        // server handle it.
1934        SendReceiptDecision::SendTo(target_event_id)
1935    }
1936
1937    /// Returns the latest event identifier, even if it's not visible, or if
1938    /// it's folded into another timeline item.
1939    pub(crate) async fn latest_event_id(&self) -> Option<OwnedEventId> {
1940        let state = self.state.read().await;
1941        let filter_out_thread_events = match self.focus() {
1942            TimelineFocusKind::Thread { .. } => false,
1943            TimelineFocusKind::Live { hide_threaded_events, .. } => *hide_threaded_events,
1944            TimelineFocusKind::Event { .. } => {
1945                // For event-focused timelines, filtering is handled in the
1946                // event cache layer.
1947                false
1948            }
1949            TimelineFocusKind::PinnedEvents { .. } => true,
1950        };
1951
1952        state
1953            .items
1954            .all_remote_events()
1955            .iter()
1956            .rev()
1957            .filter_map(|event_meta| {
1958                if !filter_out_thread_events {
1959                    // For an unthreaded timeline, the last event is always the
1960                    // latest event.
1961                    Some(event_meta.event_id.clone())
1962                } else if event_meta.thread_root_id.is_none() {
1963                    // For the main-thread timeline, only non-threaded events
1964                    // are valid candidates for the latest event.
1965                    //
1966                    // But! An event could be an aggregation that relate to an
1967                    // in-thread event. In this case, it's not a valid latest
1968                    // event.
1969                    if let Some(TimelineEventItemId::EventId(target_event_id)) =
1970                        state.meta.aggregations.is_aggregation_of(&TimelineEventItemId::EventId(
1971                            event_meta.event_id.clone(),
1972                        ))
1973                        && let Some(target_meta) =
1974                            state.items.all_remote_events().get_by_event_id(target_event_id)
1975                        && target_meta.thread_root_id.is_some()
1976                    {
1977                        // This event is an aggregation of an in-thread event,
1978                        // so skip it.
1979                        None
1980                    } else {
1981                        // Not in a thread, and not the aggregation of an
1982                        // in-thread event, so it's a valid candidate for the
1983                        // latest event.
1984                        Some(event_meta.event_id.clone())
1985                    }
1986                } else {
1987                    // An in-thread event, when we're filtering out threaded
1988                    // events, is never a valid candidate for the latest event.
1989                    None
1990                }
1991            })
1992            .next()
1993    }
1994
1995    #[instrument(skip(self), fields(room_id = ?self.room().room_id()))]
1996    pub(super) async fn retry_event_decryption(&self, session_ids: Option<BTreeSet<String>>) {
1997        let (utds, decrypted) = self.compute_redecryption_candidates().await;
1998
1999        let request = DecryptionRetryRequest {
2000            room_id: self.room().room_id().to_owned(),
2001            utd_session_ids: utds,
2002            refresh_info_session_ids: decrypted,
2003        };
2004
2005        self.state.read().await.meta.event_cache.request_decryption(request);
2006    }
2007
2008    /// Combine the global (event cache) pagination status with the local state
2009    /// of the timeline.
2010    ///
2011    /// This only changes the global pagination status of this room, in one
2012    /// case: if the timeline has a skip count greater than 0, it will ensure
2013    /// that the pagination status says that we haven't reached the timeline
2014    /// start yet.
2015    pub(super) async fn map_pagination_status(&self, status: PaginationStatus) -> PaginationStatus {
2016        match status {
2017            PaginationStatus::Idle { hit_timeline_start } => {
2018                if hit_timeline_start {
2019                    let state = self.state.read().await;
2020                    // If the skip count is greater than 0, it means that a
2021                    // subsequent pagination could return more items, so pretend
2022                    // we didn't get the information that the timeline start was
2023                    // hit.
2024                    if state.meta.subscriber_skip_count.get() > 0 {
2025                        return PaginationStatus::Idle { hit_timeline_start: false };
2026                    }
2027                }
2028            }
2029            PaginationStatus::Paginating => {}
2030        }
2031
2032        // You're perfect, just the way you are.
2033        status
2034    }
2035}
2036
2037impl<P: RoomDataProvider> TimelineController<P> {
2038    /// Returns the timeline focus of the [`TimelineController`].
2039    pub(super) fn focus(&self) -> &TimelineFocusKind {
2040        &self.focus
2041    }
2042
2043    /// Find an event by ID in this timeline, along with its related events.
2044    ///
2045    /// The related events can be filtered by relation type.
2046    pub(in crate::timeline) async fn find_event_with_relations(
2047        &self,
2048        event_id: &EventId,
2049        filter: Option<Vec<RelationType>>,
2050    ) -> Result<(TimelineEvent, Vec<TimelineEvent>), Error> {
2051        self.room_data_provider
2052            .load_or_fetch_event_with_relations(event_id, filter)
2053            .await
2054            .map_err(Into::into)
2055    }
2056}
2057
2058#[allow(clippy::too_many_arguments)]
2059async fn fetch_replied_to_event<P: RoomDataProvider>(
2060    mut state_guard: RwLockWriteGuard<'_, TimelineState<P>>,
2061    state_lock: &RwLock<TimelineState<P>>,
2062    index: usize,
2063    item: &EventTimelineItem,
2064    internal_id: TimelineUniqueId,
2065    msglike: &MsgLikeContent,
2066    in_reply_to: &EventId,
2067    room: &Room,
2068) -> Result<TimelineDetails<Box<EmbeddedEvent>>, Error> {
2069    if let Some((_, item)) = rfind_event_by_id(&state_guard.items, in_reply_to) {
2070        let details = TimelineDetails::Ready(Box::new(EmbeddedEvent::from_timeline_item(&item)));
2071        trace!("Found replied-to event locally");
2072        return Ok(details);
2073    }
2074
2075    // Replace the item with a new timeline item that has the fetching status of
2076    // the replied-to event to pending.
2077    trace!("Setting in-reply-to details to pending");
2078    let in_reply_to_details =
2079        InReplyToDetails { event_id: in_reply_to.to_owned(), event: TimelineDetails::Pending };
2080
2081    let event_item = item
2082        .with_content(TimelineItemContent::MsgLike(msglike.with_in_reply_to(in_reply_to_details)));
2083
2084    let new_timeline_item = TimelineItem::new(event_item, internal_id);
2085    state_guard.items.replace(index, new_timeline_item);
2086
2087    // Don't hold the state lock while the network request is made.
2088    drop(state_guard);
2089
2090    trace!("Fetching replied-to event");
2091    let res = match room.load_or_fetch_event(in_reply_to, None).await {
2092        Ok(timeline_event) => {
2093            let state = state_lock.read().await;
2094
2095            let replied_to_item =
2096                EmbeddedEvent::try_from_timeline_event(timeline_event, room, &state.meta).await?;
2097
2098            if let Some(item) = replied_to_item {
2099                TimelineDetails::Ready(Box::new(item))
2100            } else {
2101                // The replied-to item is an aggregation, not a standalone item.
2102                return Err(Error::UnsupportedEvent);
2103            }
2104        }
2105
2106        Err(e) => TimelineDetails::Error(Arc::new(e)),
2107    };
2108
2109    Ok(res)
2110}