Skip to main content

matrix_sdk_ui/timeline/
builder.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::sync::Arc;
16
17use matrix_sdk::Room;
18use matrix_sdk_base::{SendOutsideWasm, SyncOutsideWasm};
19use ruma::{events::AnySyncTimelineEvent, room_version_rules::RoomVersionRules};
20use tracing::{Instrument, Span, info_span};
21
22use super::{
23    DateDividerMode, Error, Timeline, TimelineDropHandle, TimelineFocus,
24    controller::{TimelineController, TimelineSettings},
25};
26#[cfg(feature = "unstable-msc4426")]
27use crate::timeline::tasks::global_profile_updates_task;
28use crate::{
29    timeline::{
30        TimelineReadReceiptTracking,
31        controller::{ActiveCallInfo, InitFocusResult, spawn_crypto_tasks},
32        tasks::{
33            room_event_cache_updates_task, room_send_queue_update_task, rtc_membership_update_task,
34        },
35        traits::RoomDataProvider,
36    },
37    unable_to_decrypt_hook::UtdHookManager,
38};
39
40/// Builder that allows creating and configuring various parts of a
41/// [`Timeline`].
42#[must_use]
43#[derive(Debug)]
44pub struct TimelineBuilder {
45    room: Room,
46    settings: TimelineSettings,
47    focus: TimelineFocus,
48
49    /// An optional hook to call whenever we run into an unable-to-decrypt or a
50    /// late-decryption event.
51    unable_to_decrypt_hook: Option<Arc<UtdHookManager>>,
52
53    /// An optional prefix for internal IDs.
54    internal_id_prefix: Option<String>,
55}
56
57impl TimelineBuilder {
58    pub fn new(room: &Room) -> Self {
59        Self {
60            room: room.clone(),
61            settings: TimelineSettings::default(),
62            unable_to_decrypt_hook: None,
63            focus: TimelineFocus::Live { hide_threaded_events: false },
64            internal_id_prefix: None,
65        }
66    }
67
68    /// Sets up the initial focus for this timeline.
69    ///
70    /// By default, the focus for a timeline is to be "live" (i.e. it will
71    /// listen to sync and append this room's events in real-time, and it'll be
72    /// able to back-paginate older events), and show all events (including
73    /// events in threads). Look at [`TimelineFocus`] for other options.
74    pub fn with_focus(mut self, focus: TimelineFocus) -> Self {
75        self.focus = focus;
76        self
77    }
78
79    /// Sets up a hook to catch unable-to-decrypt (UTD) events for the timeline
80    /// we're building.
81    ///
82    /// If it was previously set before, will overwrite the previous one.
83    pub fn with_unable_to_decrypt_hook(mut self, hook: Arc<UtdHookManager>) -> Self {
84        self.unable_to_decrypt_hook = Some(hook);
85        self
86    }
87
88    /// Sets the internal id prefix for this timeline.
89    ///
90    /// The prefix will be prepended to any internal ID using when generating
91    /// timeline IDs for this timeline.
92    pub fn with_internal_id_prefix(mut self, prefix: String) -> Self {
93        self.internal_id_prefix = Some(prefix);
94        self
95    }
96
97    /// Choose when to insert the date separators, either in between each day
98    /// or each month.
99    pub fn with_date_divider_mode(mut self, mode: DateDividerMode) -> Self {
100        self.settings.date_divider_mode = mode;
101        self
102    }
103
104    /// Choose whether to enable tracking of the fully-read marker and the read
105    /// receipts and on which event types.
106    pub fn track_read_marker_and_receipts(mut self, tracking: TimelineReadReceiptTracking) -> Self {
107        self.settings.track_read_receipts = tracking;
108        self
109    }
110
111    /// Use the given filter to choose whether to add events to the timeline.
112    ///
113    /// # Arguments
114    ///
115    /// * `filter` - A function that takes a deserialized event, and should
116    ///   return `true` if the event should be added to the `Timeline`.
117    ///
118    /// If this is not overridden, the timeline uses the default filter that
119    /// only allows events that are materialized into a `Timeline` item. For
120    /// instance, reactions and edits don't get their own timeline item (as
121    /// they affect another existing one), so they're "filtered out" to
122    /// reflect that.
123    ///
124    /// You can use the default event filter with
125    /// [`crate::timeline::default_event_filter`] so as to chain it with
126    /// your own event filter, if you want to avoid situations where a read
127    /// receipt would be attached to an event that doesn't get its own
128    /// timeline item.
129    ///
130    /// Note that currently:
131    ///
132    /// - Not all event types have a representation as a `TimelineItem` so these
133    ///   are not added no matter what the filter returns.
134    /// - It is not possible to filter out `m.room.encrypted` events (otherwise
135    ///   they couldn't be decrypted when the appropriate room key arrives).
136    pub fn event_filter<F>(mut self, filter: F) -> Self
137    where
138        F: Fn(&AnySyncTimelineEvent, &RoomVersionRules) -> bool
139            + SendOutsideWasm
140            + SyncOutsideWasm
141            + 'static,
142    {
143        self.settings.event_filter = Arc::new(filter);
144        self
145    }
146
147    /// Whether to add events that failed to deserialize to the timeline.
148    ///
149    /// Defaults to `true`.
150    pub fn add_failed_to_parse(mut self, add: bool) -> Self {
151        self.settings.add_failed_to_parse = add;
152        self
153    }
154
155    /// Create a [`Timeline`] with the options set on this builder.
156    #[tracing::instrument(
157        skip(self),
158        fields(
159            room_id = ?self.room.room_id(),
160            track_read_receipts = ?self.settings.track_read_receipts,
161        )
162    )]
163    pub async fn build(self) -> Result<Timeline, Error> {
164        let Self { room, settings, unable_to_decrypt_hook, focus, internal_id_prefix } = self;
165
166        // Subscribe the event cache to sync responses, in case we hadn't done it yet.
167        let client = room.client();
168        let event_cache = client.event_cache();
169        event_cache.subscribe()?;
170
171        let room_id = room.room_id();
172        let (room_event_cache, event_cache_drop) = event_cache.room(room_id).await?;
173        let (_, event_subscriber) = room_event_cache.subscribe().await?;
174
175        let is_room_encrypted = room
176            .latest_encryption_state()
177            .await
178            .map(|state| state.is_encrypted())
179            .ok()
180            .unwrap_or_default();
181
182        let initial_info = room.clone_info();
183        let owned_user_id = room.own_user_id().to_owned();
184
185        let controller = TimelineController::new(
186            room.clone(),
187            &focus,
188            event_cache,
189            internal_id_prefix.clone(),
190            unable_to_decrypt_hook,
191            is_room_encrypted,
192            settings,
193        )
194        .await?;
195
196        let InitFocusResult { focus_task, has_events } = controller.init_focus().await?;
197
198        let room_update_join_handle = room
199            .client()
200            .task_monitor()
201            .spawn_infinite_task("timeline::room_event_cache_updates", {
202                let span = info_span!(
203                    parent: Span::none(),
204                    "live_update_handler",
205                    room_id = ?room.room_id(),
206                    focus = focus.debug_string(),
207                    prefix = internal_id_prefix
208                );
209                span.follows_from(Span::current());
210
211                room_event_cache_updates_task(
212                    room_event_cache.clone(),
213                    controller.clone(),
214                    event_subscriber,
215                    focus.clone(),
216                )
217                .instrument(span)
218            })
219            .abort_on_drop();
220
221        let local_echo_listener_handle = {
222            let timeline_controller = controller.clone();
223            let (local_echoes, send_queue_stream) = room.send_queue().subscribe().await?;
224
225            room.client()
226                .task_monitor()
227                .spawn_infinite_task("timeline::local_echo_listener", {
228                    // Handles existing local echoes first.
229                    for echo in local_echoes {
230                        timeline_controller.handle_local_echo(echo).await;
231                    }
232
233                    let span = info_span!(
234                        parent: Span::none(),
235                        "local_echo_handler",
236                        room_id = ?room.room_id(),
237                        focus = focus.debug_string(),
238                        prefix = internal_id_prefix
239                    );
240                    span.follows_from(Span::current());
241
242                    room_send_queue_update_task(send_queue_stream, timeline_controller)
243                        .instrument(span)
244                })
245                .abort_on_drop()
246        };
247
248        #[cfg(feature = "unstable-msc4426")]
249        let global_profile_updates_handle = room
250            .client()
251            .task_monitor()
252            .spawn_infinite_task(
253                "timeline::global_profile_updates",
254                global_profile_updates_task(
255                    room.client().subscribe_to_global_profile_updates(),
256                    controller.clone(),
257                ),
258            )
259            .abort_on_drop();
260
261        let initial_active_call_info = ActiveCallInfo::from_info(initial_info, owned_user_id);
262        if initial_active_call_info.is_some() {
263            controller.handle_active_call_update(initial_active_call_info).await;
264        }
265        let rtc_membership_listener_handle = {
266            let room_info_subscriber = room.subscribe_info();
267            room.client()
268                .task_monitor()
269                .spawn_infinite_task("timeline::rtc_membership_listener", {
270                    let span = info_span!(
271                        parent: Span::none(),
272                        "rtc_membership_handler",
273                        room_id = ?room.room_id(),
274                    );
275                    span.follows_from(Span::current());
276
277                    rtc_membership_update_task(room_info_subscriber, controller.clone())
278                        .instrument(span)
279                })
280                .abort_on_drop()
281        };
282
283        let crypto_drop_handles = spawn_crypto_tasks(controller.clone()).await;
284
285        let timeline = Timeline {
286            controller,
287            drop_handle: Arc::new(TimelineDropHandle {
288                _crypto_drop_handles: crypto_drop_handles,
289                _room_update_join_handle: room_update_join_handle,
290                #[cfg(feature = "unstable-msc4426")]
291                _global_profile_updates_handle: global_profile_updates_handle,
292                _local_echo_listener_handle: local_echo_listener_handle,
293                _rtc_membership_listener_handle: rtc_membership_listener_handle,
294                _focus_drop_handle: focus_task,
295                _event_cache_drop_handle: event_cache_drop,
296            }),
297        };
298
299        if has_events {
300            // The events we're injecting might be encrypted events, but we might
301            // have received the room key to decrypt them while nobody was listening to the
302            // `m.room_key` event, let's retry now.
303            timeline.retry_decryption_for_all_events().await;
304        }
305
306        Ok(timeline)
307    }
308}