Skip to main content

matrix_sdk_ui/timeline/
mod.rs

1// Copyright 2022 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
15//! A high-level view into a room's contents.
16//!
17//! See [`Timeline`] for details.
18
19use std::{fs, iter, path::PathBuf, sync::Arc};
20
21use algorithms::rfind_event_by_item_id;
22use event_item::TimelineItemHandle;
23use eyeball::Subscriber;
24use eyeball_im::VectorDiff;
25#[cfg(feature = "unstable-msc4274")]
26use futures::SendGallery;
27use futures_core::Stream;
28use imbl::Vector;
29use matrix_sdk::{
30    Result,
31    attachment::{AttachmentInfo, Thumbnail},
32    deserialized_responses::TimelineEvent,
33    event_cache::{EventCacheDropHandles, EventFocusThreadMode},
34    room::{
35        Receipts, Room,
36        edit::EditedContent,
37        reply::{EnforceThread, Reply},
38    },
39    send_queue::{RoomSendQueueError, SendHandle},
40    task_monitor::BackgroundTaskHandle,
41};
42use mime::Mime;
43use ruma::{
44    EventId, OwnedEventId, OwnedTransactionId, UserId,
45    api::client::receipt::create_receipt::v3::ReceiptType,
46    events::{
47        AnyMessageLikeEventContent, AnySyncTimelineEvent, Mentions,
48        location::{AssetType, LocationContent, ZoomLevel},
49        poll::unstable_start::{NewUnstablePollStartEventContent, UnstablePollStartEventContent},
50        receipt::{Receipt, ReceiptThread},
51        relation::{RelationType, Thread},
52        room::message::{
53            AddMentions, LocationMessageEventContent, MessageType, Relation,
54            RelationWithoutReplacement, ReplyWithinThread, RoomMessageEventContent,
55            RoomMessageEventContentWithoutRelation, TextMessageEventContent,
56        },
57    },
58    room_version_rules::RoomVersionRules,
59};
60use subscriber::TimelineWithDropHandle;
61use thiserror::Error;
62use tracing::{instrument, trace, warn};
63
64use self::{
65    algorithms::rfind_event_by_id, controller::TimelineController, futures::SendAttachment,
66};
67use crate::timeline::controller::{CryptoDropHandles, SendReceiptDecision};
68
69mod algorithms;
70mod builder;
71mod controller;
72mod date_dividers;
73mod error;
74pub mod event_filter;
75mod event_handler;
76mod event_item;
77pub mod futures;
78mod item;
79mod latest_event;
80mod pagination;
81mod subscriber;
82mod tasks;
83#[cfg(test)]
84mod tests;
85pub mod thread_list_service;
86mod traits;
87mod virtual_item;
88
89pub use self::{
90    builder::TimelineBuilder,
91    controller::default_event_filter,
92    error::*,
93    event_filter::{TimelineEventCondition, TimelineEventFilter},
94    event_item::{
95        AnyOtherStateEventContentChange, BeaconInfo, EditRevision, EmbeddedEvent, EncryptedMessage,
96        EventItemOrigin, EventSendState, EventTimelineItem, InReplyToDetails, LiveLocationState,
97        MediaUploadProgress, MemberProfileChange, MembershipChange, Message, MsgLikeContent,
98        MsgLikeKind, OtherMessageLike, OtherState, PollResult, PollState, Profile, ReactionInfo,
99        ReactionsByKeyBySender, RoomMembershipChange, RoomPinnedEventsChange, Sticker,
100        ThreadSummary, TimelineDetails, TimelineEventItemId, TimelineEventShieldState,
101        TimelineEventShieldStateCode, TimelineItemContent,
102    },
103    item::{TimelineItem, TimelineItemKind, TimelineUniqueId},
104    latest_event::{LatestEventValue, LatestEventValueLocalState},
105    thread_list_service::{ThreadListPaginationState, ThreadListService},
106    traits::RoomExt,
107    virtual_item::VirtualTimelineItem,
108};
109
110/// Which pending send on an item [`Timeline::retry_send`] and
111/// [`Timeline::abort_send`] act on.
112#[derive(Clone, Debug)]
113pub enum SendTarget {
114    /// The item itself, while it's a local echo.
115    ///
116    /// Note that aborting one that's already in flight queues a redaction for
117    /// it, without a reason; use [`SendHandle::abort_with_reason`] if one is
118    /// needed.
119    ///
120    /// [`SendHandle::abort_with_reason`]: matrix_sdk::send_queue::SendHandle::abort_with_reason
121    Event,
122    /// Our pending edit of the item.
123    Edit,
124    /// Our pending redaction of the item.
125    Redaction,
126    /// Our pending reaction to the item with this key.
127    Reaction { key: String },
128}
129
130/// A high-level view into a regular¹ room's contents.
131///
132/// ¹ This type is meant to be used in the context of rooms without a
133/// `room_type`, that is rooms that are primarily used to exchange text
134/// messages.
135#[derive(Debug)]
136pub struct Timeline {
137    /// Cloneable, inner fields of the `Timeline`, shared with some background
138    /// tasks.
139    controller: TimelineController,
140
141    /// References to long-running tasks held by the timeline.
142    drop_handle: Arc<TimelineDropHandle>,
143}
144
145/// What should the timeline focus on?
146#[derive(Clone, Debug, PartialEq)]
147pub enum TimelineFocus {
148    /// Focus on live events, i.e. receive events from sync and append them in
149    /// real-time.
150    Live {
151        /// Whether to hide in-thread replies from the live timeline.
152        ///
153        /// This should be set to true when the client can create
154        /// [`Self::Thread`]-focused timelines from the thread roots themselves.
155        hide_threaded_events: bool,
156    },
157
158    /// Focus on a specific event, e.g. after clicking a permalink.
159    Event {
160        target: OwnedEventId,
161        num_context_events: u16,
162        /// How to handle threaded events.
163        thread_mode: TimelineEventFocusThreadMode,
164    },
165
166    /// Focus on a specific thread
167    Thread { thread_id: OwnedEventId },
168
169    /// Only show pinned events.
170    PinnedEvents,
171}
172
173/// Options for controlling the behaviour of [`TimelineFocus::Event`] for
174/// threaded events.
175#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
176#[derive(Clone, Copy, Debug, PartialEq)]
177pub enum TimelineEventFocusThreadMode {
178    /// Force the timeline into threaded mode.
179    ///
180    /// When the focused event is part of a thread, the timeline will be focused
181    /// on that thread's root. Otherwise, the timeline will treat the target
182    /// event itself as the thread root. Threaded events will never be hidden.
183    ForceThread,
184
185    /// Automatically determine if the target event is part of a thread or not.
186    ///
187    /// If the event is part of a thread, the timeline will be filtered to
188    /// on-thread events.
189    Automatic {
190        /// When the target event is not part of a thread, whether to hide
191        /// in-thread replies from the live timeline.
192        ///
193        /// Has no effect when the target event is part of a thread.
194        ///
195        /// This should be set to true when the client can create
196        /// [`TimelineFocus::Thread`]-focused timelines from the thread roots
197        /// themselves and doesn't use the [`Self::ForceThread`] mode.
198        hide_threaded_events: bool,
199    },
200}
201
202impl From<TimelineEventFocusThreadMode> for EventFocusThreadMode {
203    fn from(val: TimelineEventFocusThreadMode) -> Self {
204        match val {
205            TimelineEventFocusThreadMode::ForceThread => EventFocusThreadMode::ForceThread,
206            TimelineEventFocusThreadMode::Automatic { .. } => EventFocusThreadMode::Automatic,
207        }
208    }
209}
210
211impl TimelineFocus {
212    pub(super) fn debug_string(&self) -> String {
213        match self {
214            TimelineFocus::Live { .. } => "live".to_owned(),
215            TimelineFocus::Event { target, .. } => format!("permalink:{target}"),
216            TimelineFocus::Thread { thread_id, .. } => {
217                format!("thread:{thread_id}")
218            }
219            TimelineFocus::PinnedEvents => "pinned-events".to_owned(),
220        }
221    }
222}
223
224/// Changes how dividers get inserted, either in between each day or in between
225/// each month
226#[derive(Debug, Clone)]
227pub enum DateDividerMode {
228    Daily,
229    Monthly,
230}
231
232/// Configuration for sending an attachment.
233///
234/// Like [`matrix_sdk::attachment::AttachmentConfig`], but instead of the
235/// `reply` field, there's only a `in_reply_to` event id; it's the timeline
236/// deciding to fill the rest of the reply parameters.
237#[derive(Debug, Default)]
238pub struct AttachmentConfig {
239    pub txn_id: Option<OwnedTransactionId>,
240    pub info: Option<AttachmentInfo>,
241    pub thumbnail: Option<Thumbnail>,
242    pub caption: Option<TextMessageEventContent>,
243    pub mentions: Option<Mentions>,
244    pub in_reply_to: Option<OwnedEventId>,
245    pub extra_content: Option<serde_json::Map<String, serde_json::Value>>,
246}
247
248impl Timeline {
249    /// Returns the room for this timeline.
250    pub fn room(&self) -> &Room {
251        self.controller.room()
252    }
253
254    /// Clear all timeline items.
255    pub async fn clear(&self) {
256        self.controller.clear().await;
257    }
258
259    /// Retry decryption of previously un-decryptable events given a list of
260    /// session IDs whose keys have been imported.
261    ///
262    /// # Examples
263    ///
264    /// ```no_run
265    /// # use std::{path::PathBuf, time::Duration};
266    /// # use matrix_sdk::{Client, config::SyncSettings, ruma::room_id};
267    /// # use matrix_sdk_ui::Timeline;
268    /// # async {
269    /// # let mut client: Client = todo!();
270    /// # let room_id = ruma::room_id!("!example:example.org");
271    /// # let timeline: Timeline = todo!();
272    /// let path = PathBuf::from("/home/example/e2e-keys.txt");
273    /// let result =
274    ///     client.encryption().import_room_keys(path, "secret-passphrase").await?;
275    ///
276    /// // Given a timeline for a specific room_id
277    /// if let Some(keys_for_users) = result.keys.get(room_id) {
278    ///     let session_ids = keys_for_users.values().flatten();
279    ///     timeline.retry_decryption(session_ids).await;
280    /// }
281    /// # anyhow::Ok(()) };
282    /// ```
283    pub async fn retry_decryption<S: Into<String>>(
284        &self,
285        session_ids: impl IntoIterator<Item = S>,
286    ) {
287        self.controller
288            .retry_event_decryption(Some(session_ids.into_iter().map(Into::into).collect()))
289            .await;
290    }
291
292    #[tracing::instrument(skip(self))]
293    async fn retry_decryption_for_all_events(&self) {
294        self.controller.retry_event_decryption(None).await;
295    }
296
297    /// Get the current timeline item for the given event ID, if any.
298    ///
299    /// Will return a remote event, _or_ a local echo that has been sent but not
300    /// yet replaced by a remote echo.
301    ///
302    /// It's preferable to store the timeline items in the model for your UI, if
303    /// possible, instead of just storing IDs and coming back to the timeline
304    /// object to look up items.
305    pub async fn item_by_event_id(&self, event_id: &EventId) -> Option<EventTimelineItem> {
306        let items = self.controller.items().await;
307        let (_, item) = rfind_event_by_id(&items, event_id)?;
308        Some(item.to_owned())
309    }
310
311    /// Get the edit history for the given event.
312    ///
313    /// Returns all revisions of the event, in chronological order. The first
314    /// entry is the original event content, followed by each edit in the order
315    /// they were applied.
316    ///
317    /// This looks up the event and all `m.replace` relations targeting it,
318    /// first in the event cache and falling back to the homeserver if needed.
319    /// This works regardless of the timeline's focus kind (live, thread,
320    /// permalink, or pinned events).
321    pub async fn edit_revisions(&self, event_id: &EventId) -> Result<Vec<EditRevision>, Error> {
322        let Ok((original_event, edit_events)) = self
323            .controller
324            .find_event_with_relations(event_id, Some(vec![RelationType::Replacement]))
325            .await
326        else {
327            return Ok(Vec::new());
328        };
329
330        let room = self.room();
331        let mut revisions = Vec::with_capacity(edit_events.len() + 1);
332
333        for event in iter::once(original_event).chain(edit_events) {
334            let timestamp = event.timestamp();
335            if let Some(content) = TimelineItemContent::from_event(room, event).await {
336                revisions.push(EditRevision { content, timestamp });
337            }
338        }
339
340        Ok(revisions)
341    }
342
343    /// Get the ID of the closest visible event at or before the user's
344    /// `m.fully_read` marker.
345    ///
346    /// The marker may point to an event that isn't rendered (e.g. a reaction
347    /// or an edit). If the marker's event isn't loaded, or no visible event
348    /// before it is, this is the marker's own event ID. The read marker item
349    /// itself may be placed further down, after the user's own events.
350    ///
351    /// If the room has no `m.fully_read` marker, the user's latest read receipt
352    /// is used instead. Returns `None` if there's neither, or if the timeline
353    /// doesn't track read markers.
354    pub fn fully_read_event_id(&self) -> Option<OwnedEventId> {
355        self.controller.fully_read_event_id.get()
356    }
357
358    /// Subscribe to changes of [`Self::fully_read_event_id`].
359    ///
360    /// Updates are published after the timeline items they depend on.
361    pub fn subscribe_fully_read_event_id(&self) -> Subscriber<Option<OwnedEventId>> {
362        self.controller.fully_read_event_id.subscribe()
363    }
364
365    /// Get the latest of the timeline's remote event ids.
366    pub async fn latest_event_id(&self) -> Option<OwnedEventId> {
367        self.controller.latest_event_id().await
368    }
369
370    /// Get the current timeline items, along with a stream of updates of
371    /// timeline items.
372    ///
373    /// The stream produces `Vec<VectorDiff<_>>`, which means multiple updates
374    /// at once. There are no delays, it consumes as many updates as possible
375    /// and batches them.
376    pub async fn subscribe(
377        &self,
378    ) -> (Vector<Arc<TimelineItem>>, impl Stream<Item = Vec<VectorDiff<Arc<TimelineItem>>>> + use<>)
379    {
380        let (items, stream) = self.controller.subscribe().await;
381        let stream = TimelineWithDropHandle::new(stream, self.drop_handle.clone());
382        (items, stream)
383    }
384
385    /// Send a message to the room, and add it to the timeline as a local echo.
386    ///
387    /// For simplicity, this method doesn't currently allow custom message
388    /// types.
389    ///
390    /// If the encryption feature is enabled, this method will transparently
391    /// encrypt the room message if the room is encrypted.
392    ///
393    /// If sending the message fails, the local echo item will change its
394    /// `send_state` to [`EventSendState::SendingFailed`].
395    ///
396    /// This will do the right thing in the presence of threads:
397    ///
398    /// - if this timeline is not focused on a thread, then it will send the
399    ///   event as is.
400    /// - if this is a threaded timeline, and the event to send is a room
401    ///   message without a relationship, it will automatically mark it as a
402    ///   thread reply with the correct reply fallback, and send it.
403    ///
404    /// # Arguments
405    ///
406    /// - `content` - The content of the message event.
407    #[instrument(skip(self, content), fields(room_id = ?self.room().room_id()))]
408    pub async fn send(&self, content: AnyMessageLikeEventContent) -> Result<SendHandle, Error> {
409        self.send_with_extra_content(content, None).await
410    }
411
412    /// Queues an event in this room's send queue, with additional top-level
413    /// fields merged into its content. The event's own fields take precedence
414    /// on conflicts.
415    ///
416    /// See [`Self::send`] for more details.
417    #[instrument(skip(self, content, extra_content), fields(room_id = ?self.room().room_id()))]
418    pub async fn send_with_extra_content(
419        &self,
420        mut content: AnyMessageLikeEventContent,
421        extra_content: Option<serde_json::Map<String, serde_json::Value>>,
422    ) -> Result<SendHandle, Error> {
423        // If this is a room event we're sending in a threaded timeline, we add
424        // the thread relation ourselves.
425        if content.relation().is_none()
426            && let Some(reply) = self.infer_reply(None).await
427        {
428            match &mut content {
429                AnyMessageLikeEventContent::RoomMessage(room_msg_content) => {
430                    content = self
431                        .room()
432                        .make_reply_event(
433                            // Note: this `.into()` gets rid of the relation,
434                            // but we've checked previously that the
435                            // `relates_to` field wasn't set.
436                            room_msg_content.clone().into(),
437                            reply,
438                        )
439                        .await?
440                        .into();
441                }
442
443                AnyMessageLikeEventContent::UnstablePollStart(
444                    UnstablePollStartEventContent::New(poll),
445                ) => {
446                    if let Some(thread_root) = self.controller.thread_root() {
447                        poll.relates_to = Some(RelationWithoutReplacement::Thread(Thread::plain(
448                            thread_root,
449                            reply.event_id,
450                        )));
451                    }
452                }
453
454                AnyMessageLikeEventContent::Sticker(sticker) => {
455                    if let Some(thread_root) = self.controller.thread_root() {
456                        sticker.relates_to =
457                            Some(Relation::Thread(Thread::plain(thread_root, reply.event_id)));
458                    }
459                }
460
461                _ => {}
462            }
463        }
464
465        let queue = self.room().send_queue();
466        let send = queue.send(content);
467        let send = match extra_content {
468            Some(extra_content) => send.with_extra_content(extra_content),
469            None => send,
470        };
471        Ok(send.await?)
472    }
473
474    /// Send a reply to the given event.
475    ///
476    /// Currently it only supports events with an event ID and JSON being
477    /// available (which can be removed by local redactions). This is subject to
478    /// change. Use [`EventTimelineItem::can_be_replied_to`] to decide whether
479    /// to render a reply button.
480    ///
481    /// The sender will be added to the mentions of the reply if and only if the
482    /// event has not been written by the sender.
483    ///
484    /// This will do the right thing in the presence of threads:
485    ///
486    /// - if this timeline is not focused on a thread, then it will forward the
487    ///   thread relationship of the replied-to event, if present.
488    /// - if this is a threaded timeline, it will mark the reply as an in-thread
489    ///   reply.
490    ///
491    /// # Arguments
492    ///
493    /// - `content` - The content of the reply.
494    /// - `in_reply_to` - The ID of the event to reply to.
495    #[instrument(skip(self, content))]
496    pub async fn send_reply(
497        &self,
498        content: RoomMessageEventContentWithoutRelation,
499        in_reply_to: OwnedEventId,
500    ) -> Result<SendHandle, Error> {
501        let reply = self
502            .infer_reply(Some(in_reply_to))
503            .await
504            .expect("the reply will always be set because we provided a replied-to event id");
505        let content = self.room().make_reply_event(content, reply).await?;
506        self.send(content.into()).await
507    }
508
509    /// Send a location event to the room, with `body` as the plain-text
510    /// fallback and `geo_uri` its RFC 5870 representation. With `in_reply_to`,
511    /// the location is sent as a reply, with [`Self::send_reply`] semantics.
512    #[instrument(skip(self, body, geo_uri, description))]
513    pub async fn send_location(
514        &self,
515        body: String,
516        geo_uri: String,
517        description: Option<String>,
518        zoom_level: Option<ZoomLevel>,
519        asset_type: Option<AssetType>,
520        in_reply_to: Option<OwnedEventId>,
521    ) -> Result<SendHandle, Error> {
522        let mut content = LocationMessageEventContent::new(body, geo_uri.clone());
523
524        if let Some(asset_type) = asset_type {
525            content = content.with_asset_type(asset_type);
526        }
527
528        let mut location = LocationContent::new(geo_uri);
529        location.description = description;
530        location.zoom_level = zoom_level;
531        content.location = Some(location);
532
533        let msgtype = MessageType::Location(content);
534
535        match in_reply_to {
536            Some(event_id) => {
537                self.send_reply(RoomMessageEventContentWithoutRelation::new(msgtype), event_id)
538                    .await
539            }
540            None => self.send(RoomMessageEventContent::new(msgtype).into()).await,
541        }
542    }
543
544    /// Given a message or media to send, and an optional `in_reply_to` event,
545    /// automatically fills the [`Reply`] information based on the current
546    /// timeline focus.
547    pub(crate) async fn infer_reply(&self, in_reply_to: Option<OwnedEventId>) -> Option<Reply> {
548        // If there's a replied-to event id, the reply is pretty
549        // straightforward, and we should only infer the `EnforceThread` based
550        // on the current focus.
551        if let Some(in_reply_to) = in_reply_to {
552            let enforce_thread = if self.controller.is_threaded() {
553                EnforceThread::Threaded(ReplyWithinThread::Yes)
554            } else {
555                EnforceThread::MaybeThreaded
556            };
557            return Some(Reply {
558                event_id: in_reply_to,
559                enforce_thread,
560                add_mentions: AddMentions::Yes,
561            });
562        }
563
564        let thread_root = self.controller.thread_root()?;
565
566        // The latest event id is used for the reply-to fallback, for clients
567        // which don't handle threads. It should be correctly set to the latest
568        // event in the thread, which the timeline instance might or might not
569        // know about; in this case, we do a best effort of filling it, and
570        // resort to using the thread root if we don't know about any event.
571        //
572        // Note: we could trigger a back-pagination if the timeline is empty,
573        // and wait for the results, if the timeline is too often empty.
574
575        let latest_event_id = self
576            .controller
577            .items()
578            .await
579            .iter()
580            .rev()
581            .find_map(|item| {
582                if let TimelineItemKind::Event(event) = item.kind() {
583                    event.event_id().map(ToOwned::to_owned)
584                } else {
585                    None
586                }
587            })
588            .unwrap_or(thread_root);
589
590        Some(Reply {
591            event_id: latest_event_id,
592            enforce_thread: EnforceThread::Threaded(ReplyWithinThread::No),
593            add_mentions: AddMentions::Yes,
594        })
595    }
596
597    /// Edit an event given its [`TimelineEventItemId`] and some new content.
598    ///
599    /// Only supports events for which [`EventTimelineItem::is_editable()`]
600    /// returns `true`.
601    #[instrument(skip(self, new_content))]
602    pub async fn edit(
603        &self,
604        item_id: &TimelineEventItemId,
605        new_content: EditedContent,
606    ) -> Result<(), Error> {
607        let items = self.items().await;
608        let Some((_pos, item)) = rfind_event_by_item_id(&items, item_id) else {
609            return Err(Error::EventNotInTimeline(item_id.clone()));
610        };
611
612        match item.handle() {
613            TimelineItemHandle::Remote(event_id) => {
614                let content = self
615                    .room()
616                    .make_edit_event(event_id, new_content)
617                    .await
618                    .map_err(EditError::RoomError)?;
619                self.send(content).await?;
620                Ok(())
621            }
622
623            TimelineItemHandle::Local(handle) => {
624                let new_content: AnyMessageLikeEventContent = match new_content {
625                    EditedContent::RoomMessage(message) => {
626                        if item.content.is_message() {
627                            // The replacement becomes the pending event itself,
628                            // so restore its relations, which the payload can't
629                            // carry by type.
630                            AnyMessageLikeEventContent::RoomMessage(
631                                message.with_relation(item.content.relation()),
632                            )
633                        } else {
634                            return Err(EditError::ContentMismatch {
635                                original: item.content.debug_string().to_owned(),
636                                new: "a message".to_owned(),
637                            }
638                            .into());
639                        }
640                    }
641
642                    EditedContent::PollStart { new_content, .. } => {
643                        if item.content.is_poll() {
644                            AnyMessageLikeEventContent::UnstablePollStart(
645                                UnstablePollStartEventContent::New(
646                                    NewUnstablePollStartEventContent::new(new_content),
647                                ),
648                            )
649                        } else {
650                            return Err(EditError::ContentMismatch {
651                                original: item.content.debug_string().to_owned(),
652                                new: "a poll".to_owned(),
653                            }
654                            .into());
655                        }
656                    }
657
658                    EditedContent::MediaCaption { caption, formatted_caption, mentions } => {
659                        if handle
660                            .edit_media_caption(caption, formatted_caption, mentions)
661                            .await
662                            .map_err(RoomSendQueueError::StorageError)?
663                        {
664                            return Ok(());
665                        }
666                        return Err(EditError::InvalidLocalEchoState.into());
667                    }
668                };
669
670                if !handle.edit(new_content).await.map_err(RoomSendQueueError::StorageError)? {
671                    return Err(EditError::InvalidLocalEchoState.into());
672                }
673
674                Ok(())
675            }
676        }
677    }
678
679    /// Toggle a reaction on an event.
680    ///
681    /// Adds or redacts a reaction based on the state of the reaction at the
682    /// time it is called.
683    ///
684    /// When redacting a previous reaction, the redaction reason is not set.
685    ///
686    /// Ensures that only one reaction is sent at a time to avoid race
687    /// conditions and spamming the homeserver with requests.
688    ///
689    /// Returns `true` if the reaction was added, `false` if it was removed.
690    pub async fn toggle_reaction(
691        &self,
692        item_id: &TimelineEventItemId,
693        reaction_key: &str,
694    ) -> Result<bool, Error> {
695        self.controller.toggle_reaction_local(item_id, reaction_key, None).await
696    }
697
698    /// Same as [`Timeline::toggle_reaction`], merging `extra_content`'s fields
699    /// into the reaction's content when one is added.
700    ///
701    /// The reaction's own fields take precedence on conflicts. Removing a
702    /// reaction is a redaction, which carries no content, so `extra_content` is
703    /// only used when adding one — and only for reactions to remote events,
704    /// since a local echo is the user's own not-yet-sent event.
705    pub async fn toggle_reaction_with_extra_content(
706        &self,
707        item_id: &TimelineEventItemId,
708        reaction_key: &str,
709        extra_content: Option<serde_json::Map<String, serde_json::Value>>,
710    ) -> Result<bool, Error> {
711        self.controller.toggle_reaction_local(item_id, reaction_key, extra_content).await
712    }
713
714    /// Sends an attachment to the room.
715    ///
716    /// It does not currently support local echoes.
717    ///
718    /// If the encryption feature is enabled, this method will transparently
719    /// encrypt the room message if the room is encrypted.
720    ///
721    /// The attachment and its optional thumbnail are stored in the media cache
722    /// and can be retrieved at any time, by calling
723    /// [`Media::get_media_content()`] with the `MediaSource` that can be found
724    /// in the corresponding `TimelineEventItem`, and using a
725    /// `MediaFormat::File`.
726    ///
727    /// # Arguments
728    ///
729    /// - `source` - The source of the attachment to send.
730    /// - `mime_type` - The attachment's mime type.
731    /// - `config` - An attachment configuration object containing details about
732    ///   the attachment like a thumbnail, its size, duration etc.
733    ///
734    /// [`Media::get_media_content()`]: matrix_sdk::Media::get_media_content
735    #[instrument(skip_all)]
736    pub fn send_attachment(
737        &self,
738        source: impl Into<AttachmentSource>,
739        mime_type: Mime,
740        config: AttachmentConfig,
741    ) -> SendAttachment<'_> {
742        SendAttachment::new(self, source.into(), mime_type, config)
743    }
744
745    /// Replaces the attachment of a message the current user sent, or adds one
746    /// to a message which had none, through the send queue.
747    ///
748    /// See [`RoomSendQueue::edit_with_attachment()`] for the details. The
749    /// `in_reply_to` of the `config` is ignored: an edit carries no other
750    /// relation.
751    ///
752    /// [`RoomSendQueue::edit_with_attachment()`]: matrix_sdk::send_queue::RoomSendQueue::edit_with_attachment
753    #[instrument(skip_all, fields(%event_id))]
754    pub async fn edit_with_attachment(
755        &self,
756        event_id: &EventId,
757        source: impl Into<AttachmentSource>,
758        mime_type: Mime,
759        config: AttachmentConfig,
760    ) -> Result<(), Error> {
761        let (data, filename) = source.into().try_into_bytes_and_filename()?;
762
763        let config = matrix_sdk::attachment::AttachmentConfig {
764            txn_id: config.txn_id,
765            info: config.info,
766            thumbnail: config.thumbnail,
767            caption: config.caption,
768            mentions: config.mentions,
769            extra_content: config.extra_content,
770            reply: None,
771        };
772
773        self.room()
774            .send_queue()
775            .edit_with_attachment(event_id, filename, mime_type, data, config)
776            .await?;
777
778        Ok(())
779    }
780
781    /// Sends a media gallery to the room.
782    ///
783    /// If the encryption feature is enabled, this method will transparently
784    /// encrypt the room message if the room is encrypted.
785    ///
786    /// The attachments and their optional thumbnails are stored in the media
787    /// cache and can be retrieved at any time, by calling
788    /// [`Media::get_media_content()`] with the `MediaSource` that can be found
789    /// in the corresponding `TimelineEventItem`, and using a
790    /// `MediaFormat::File`.
791    ///
792    /// # Arguments
793    ///
794    /// - `gallery` - A configuration object containing details about the
795    ///   gallery like files, thumbnails, etc.
796    ///
797    /// [`Media::get_media_content()`]: matrix_sdk::Media::get_media_content
798    #[cfg(feature = "unstable-msc4274")]
799    #[instrument(skip_all)]
800    pub fn send_gallery(&self, gallery: GalleryConfig) -> SendGallery<'_> {
801        SendGallery::new(self, gallery)
802    }
803
804    /// Redact an event given its [`TimelineEventItemId`] and an optional
805    /// reason.
806    pub async fn redact(
807        &self,
808        item_id: &TimelineEventItemId,
809        reason: Option<&str>,
810    ) -> Result<(), Error> {
811        let items = self.items().await;
812        let Some((_pos, event)) = rfind_event_by_item_id(&items, item_id) else {
813            return Err(RedactError::ItemNotFound(item_id.clone()).into());
814        };
815
816        match event.handle() {
817            TimelineItemHandle::Remote(event_id) => {
818                self.room()
819                    .send_queue()
820                    .redact(event_id.to_owned(), reason)
821                    .await
822                    .map_err(|_| Error::FailedSendingRedaction)?;
823                Ok(())
824            }
825            TimelineItemHandle::Local(handle) => {
826                // Forward the reason: if the local echo was being sent and the
827                // send wins the race, the server-side redaction that
828                // materializes the abort carries it.
829                if !handle
830                    .abort_with_reason(reason.map(ToOwned::to_owned))
831                    .await
832                    .map_err(RoomSendQueueError::StorageError)?
833                {
834                    return Err(RedactError::InvalidLocalEchoState.into());
835                }
836                Ok(())
837            }
838        }
839    }
840
841    /// Retry sending something on this item that failed, see [`SendTarget`].
842    ///
843    /// Only needed after an unrecoverable failure, which parks the request
844    /// until it's retried or aborted; a recoverable one goes out again when the
845    /// room's send queue is re-enabled.
846    ///
847    /// Returns `false` if there was nothing of that kind left to retry, e.g.
848    /// because it went out in the meantime.
849    pub async fn retry_send(
850        &self,
851        item_id: &TimelineEventItemId,
852        target: SendTarget,
853    ) -> Result<bool, Error> {
854        let Some(handle) = self.controller.pending_send_handle(item_id, target).await? else {
855            return Ok(false);
856        };
857        handle.unwedge().await?;
858        Ok(true)
859    }
860
861    /// Abort sending something on this item that hasn't gone out yet, see
862    /// [`SendTarget`].
863    ///
864    /// Returns `false` if there was nothing of that kind left to abort, e.g.
865    /// because it went out in the meantime.
866    pub async fn abort_send(
867        &self,
868        item_id: &TimelineEventItemId,
869        target: SendTarget,
870    ) -> Result<bool, Error> {
871        let Some(handle) = self.controller.pending_send_handle(item_id, target).await? else {
872            return Ok(false);
873        };
874        handle.abort().await.map_err(|err| Error::SendQueueError(err.into()))
875    }
876
877    /// Fetch unavailable details about the event with the given ID.
878    ///
879    /// This method only works for IDs of remote [`EventTimelineItem`]s, to
880    /// prevent losing details when a local echo is replaced by its remote echo.
881    ///
882    /// This method tries to make all the requests it can. If an error is
883    /// encountered for a given request, it is forwarded with the
884    /// [`TimelineDetails::Error`] variant.
885    ///
886    /// # Arguments
887    ///
888    /// - `event_id` - The event ID of the event to fetch details for.
889    ///
890    /// # Errors
891    ///
892    /// Returns an error if the identifier doesn't match any event with a remote
893    /// echo in the timeline, or if the event is removed from the timeline
894    /// before all requests are handled.
895    #[instrument(skip(self), fields(room_id = ?self.room().room_id()))]
896    pub async fn fetch_details_for_event(&self, event_id: &EventId) -> Result<(), Error> {
897        self.controller.fetch_in_reply_to_details(event_id).await
898    }
899
900    /// Fetch all member events for the room this timeline is displaying.
901    ///
902    /// If the full member list is not known, sender profiles are currently
903    /// likely not going to be available. This will be fixed in the future.
904    ///
905    /// If fetching the members fails, any affected timeline items will have the
906    /// `sender_profile` set to [`TimelineDetails::Error`].
907    #[instrument(skip_all)]
908    pub async fn fetch_members(&self) {
909        self.controller.set_sender_profiles_pending().await;
910        match self.room().sync_members().await {
911            Ok(_) => {
912                self.controller.update_missing_sender_profiles().await;
913            }
914            Err(e) => {
915                self.controller.set_sender_profiles_error(Arc::new(e)).await;
916            }
917        }
918    }
919
920    /// Get the latest read receipt for the given user.
921    ///
922    /// Contrary to [`Room::load_user_receipt()`] that only keeps track of read
923    /// receipts received from the homeserver, this keeps also track of implicit
924    /// read receipts in this timeline, i.e. when a room member sends an event.
925    #[instrument(skip(self))]
926    pub async fn latest_user_read_receipt(
927        &self,
928        user_id: &UserId,
929    ) -> Option<(OwnedEventId, Receipt)> {
930        self.controller.latest_user_read_receipt(user_id).await
931    }
932
933    /// Get the ID of the timeline event with the latest read receipt for the
934    /// given user.
935    ///
936    /// In contrary to [`Self::latest_user_read_receipt()`], this allows to know
937    /// the position of the read receipt in the timeline even if the event it
938    /// applies to is not visible in the timeline, unless the event is unknown
939    /// by this timeline.
940    #[instrument(skip(self))]
941    pub async fn latest_user_read_receipt_timeline_event_id(
942        &self,
943        user_id: &UserId,
944    ) -> Option<OwnedEventId> {
945        self.controller.latest_user_read_receipt_timeline_event_id(user_id).await
946    }
947
948    /// Subscribe to changes in the read receipts of our own user.
949    pub async fn subscribe_own_user_read_receipts_changed(&self) -> impl Stream<Item = ()> + use<> {
950        self.controller.subscribe_own_user_read_receipts_changed().await
951    }
952
953    /// Send the given receipt.
954    ///
955    /// This uses [`Room::send_single_receipt`] internally, but checks first if
956    /// the receipt points to an event in this timeline that is more recent than
957    /// the current ones, to avoid unnecessary requests.
958    ///
959    /// If an unthreaded receipt is sent, this will also unset the unread flag
960    /// of the room if necessary.
961    ///
962    /// The thread of the receipt is determined by the timeline instance's focus
963    /// mode and `hide_threaded_events` flag.
964    ///
965    /// Returns a boolean indicating if it sent the receipt or not.
966    #[instrument(skip(self), fields(room_id = ?self.room().room_id()))]
967    pub async fn send_single_receipt(
968        &self,
969        receipt_type: ReceiptType,
970        event_id: OwnedEventId,
971    ) -> Result<bool> {
972        self.send_single_receipt_inner(receipt_type, event_id, false).await
973    }
974
975    /// Same as [`Self::send_single_receipt`], but lets the caller state whether
976    /// this is part of marking the whole room as read.
977    ///
978    /// When it is, and the only candidate event is one of the user's own, a
979    /// receipt is still sent against it so the homeserver recomputes its
980    /// push/badge count. See [`TimelineController::should_send_receipt`].
981    async fn send_single_receipt_inner(
982        &self,
983        receipt_type: ReceiptType,
984        event_id: OwnedEventId,
985        is_marking_room_as_read: bool,
986    ) -> Result<bool> {
987        let thread = self.controller.infer_thread_for_read_receipt(&receipt_type);
988
989        let event_id = match self
990            .controller
991            .should_send_receipt(&receipt_type, &thread, &event_id, is_marking_room_as_read)
992            .await
993        {
994            SendReceiptDecision::SendTo(event_id) => event_id,
995            SendReceiptDecision::DoNotSend => {
996                trace!("not sending receipt, because it wouldn't move the real receipt forwards");
997
998                if thread == ReceiptThread::Unthreaded {
999                    // Unset the read marker.
1000                    self.room().set_unread_flag(false).await?;
1001                }
1002
1003                return Ok(false);
1004            }
1005        };
1006
1007        trace!("sending receipt");
1008        self.room().send_single_receipt(receipt_type, thread, event_id).await?;
1009        Ok(true)
1010    }
1011
1012    /// Send the given receipts.
1013    ///
1014    /// This uses [`Room::send_multiple_receipts`] internally, but checks first
1015    /// if the receipts point to events in this timeline that are more recent
1016    /// than the current ones, to avoid unnecessary requests.
1017    ///
1018    /// This also unsets the unread marker of the room if necessary.
1019    #[instrument(skip(self))]
1020    pub async fn send_multiple_receipts(&self, mut receipts: Receipts) -> Result<()> {
1021        if let Some(fully_read) = &receipts.fully_read {
1022            receipts.fully_read = match self
1023                .controller
1024                .should_send_receipt(
1025                    &ReceiptType::FullyRead,
1026                    &ReceiptThread::Unthreaded,
1027                    fully_read,
1028                    false,
1029                )
1030                .await
1031            {
1032                SendReceiptDecision::SendTo(event_id) => Some(event_id),
1033                SendReceiptDecision::DoNotSend => None,
1034            };
1035        }
1036
1037        if let Some(read_receipt) = &receipts.public_read_receipt {
1038            receipts.public_read_receipt = match self
1039                .controller
1040                .should_send_receipt(
1041                    &ReceiptType::Read,
1042                    &ReceiptThread::Unthreaded,
1043                    read_receipt,
1044                    false,
1045                )
1046                .await
1047            {
1048                SendReceiptDecision::SendTo(event_id) => Some(event_id),
1049                SendReceiptDecision::DoNotSend => None,
1050            };
1051        }
1052
1053        if let Some(private_read_receipt) = &receipts.private_read_receipt {
1054            receipts.private_read_receipt = match self
1055                .controller
1056                .should_send_receipt(
1057                    &ReceiptType::ReadPrivate,
1058                    &ReceiptThread::Unthreaded,
1059                    private_read_receipt,
1060                    false,
1061                )
1062                .await
1063            {
1064                SendReceiptDecision::SendTo(event_id) => Some(event_id),
1065                SendReceiptDecision::DoNotSend => None,
1066            };
1067        }
1068
1069        let room = self.room();
1070
1071        if !receipts.is_empty() {
1072            room.send_multiple_receipts(receipts).await?;
1073        } else {
1074            room.set_unread_flag(false).await?;
1075        }
1076
1077        Ok(())
1078    }
1079
1080    /// Mark the timeline as read by attempting to send a read receipt on the
1081    /// latest visible event.
1082    ///
1083    /// The latest visible event is determined from the timeline's focus kind
1084    /// and whether or not it hides threaded events. If no latest event can be
1085    /// determined and the timeline is live, the room's unread marker is unset
1086    /// instead.
1087    ///
1088    /// # Arguments
1089    ///
1090    /// - `receipt_type` - The type of receipt to send. When using
1091    ///   [`ReceiptType::FullyRead`], an unthreaded receipt will be sent. This
1092    ///   works even if the latest event belongs to a thread, as a threaded
1093    ///   reply also belongs to the unthreaded timeline. Otherwise the
1094    ///   [`ReceiptThread`] will be determined based on the timeline's focus
1095    ///   kind.
1096    ///
1097    /// # Returns
1098    ///
1099    /// A boolean indicating if the receipt was sent or not.
1100    #[instrument(skip(self), fields(room_id = ?self.room().room_id()))]
1101    pub async fn mark_as_read(&self, receipt_type: ReceiptType) -> Result<bool> {
1102        if let Some(event_id) = self.controller.latest_event_id().await {
1103            self.send_single_receipt_inner(receipt_type, event_id, true).await
1104        } else {
1105            trace!("can't mark room as read because there's no latest event id");
1106
1107            // For live timelines, unset the read marker in this case.
1108            if self.controller.is_live() {
1109                self.room().set_unread_flag(false).await?;
1110            }
1111
1112            Ok(false)
1113        }
1114    }
1115
1116    /// Create a [`EmbeddedEvent`] from an arbitrary event, be it in the
1117    /// timeline or not.
1118    ///
1119    /// Can be `None` if the event cannot be represented as a standalone item,
1120    /// because it's an aggregation.
1121    pub async fn make_replied_to(
1122        &self,
1123        event: TimelineEvent,
1124    ) -> Result<Option<EmbeddedEvent>, Error> {
1125        self.controller.make_replied_to(event).await
1126    }
1127
1128    /// Returns whether this timeline is focused on a thread (be it live, or
1129    /// from a permalink to a threaded event).
1130    pub fn is_threaded(&self) -> bool {
1131        self.controller.is_threaded()
1132    }
1133}
1134
1135/// Test helpers, likely not very useful in production.
1136#[doc(hidden)]
1137impl Timeline {
1138    /// Get the current list of timeline items.
1139    pub async fn items(&self) -> Vector<Arc<TimelineItem>> {
1140        self.controller.items().await
1141    }
1142
1143    pub async fn subscribe_filter_map<U: Clone>(
1144        &self,
1145        f: impl Fn(Arc<TimelineItem>) -> Option<U>,
1146    ) -> (Vector<U>, impl Stream<Item = VectorDiff<U>>) {
1147        let (items, stream) = self.controller.subscribe_filter_map(f).await;
1148        let stream = TimelineWithDropHandle::new(stream, self.drop_handle.clone());
1149        (items, stream)
1150    }
1151}
1152
1153#[derive(Debug)]
1154struct TimelineDropHandle {
1155    _room_update_join_handle: BackgroundTaskHandle,
1156    #[cfg(feature = "unstable-msc4426")]
1157    _global_profile_updates_handle: BackgroundTaskHandle,
1158    _local_echo_listener_handle: BackgroundTaskHandle,
1159    _rtc_membership_listener_handle: BackgroundTaskHandle,
1160    _event_cache_drop_handle: Arc<EventCacheDropHandles>,
1161    _focus_drop_handle: Option<BackgroundTaskHandle>,
1162    _crypto_drop_handles: CryptoDropHandles,
1163}
1164
1165#[cfg(not(target_family = "wasm"))]
1166pub type TimelineEventFilterFn =
1167    dyn Fn(&AnySyncTimelineEvent, &RoomVersionRules) -> bool + Send + Sync;
1168#[cfg(target_family = "wasm")]
1169pub type TimelineEventFilterFn = dyn Fn(&AnySyncTimelineEvent, &RoomVersionRules) -> bool;
1170
1171/// A source for sending an attachment.
1172///
1173/// The [`AttachmentSource::File`] variant can be constructed from any type that
1174/// implements `Into<PathBuf>`.
1175#[derive(Debug, Clone)]
1176pub enum AttachmentSource {
1177    /// The data of the attachment.
1178    Data {
1179        /// The bytes of the attachment.
1180        bytes: Vec<u8>,
1181
1182        /// The filename of the attachment.
1183        filename: String,
1184    },
1185
1186    /// An attachment loaded from a file.
1187    ///
1188    /// The bytes and the filename will be read from the file at the given path.
1189    File(PathBuf),
1190}
1191
1192impl AttachmentSource {
1193    /// Try to convert this attachment source into a `(bytes, filename)` tuple.
1194    pub(crate) fn try_into_bytes_and_filename(self) -> Result<(Vec<u8>, String), Error> {
1195        match self {
1196            Self::Data { bytes, filename } => Ok((bytes, filename)),
1197            Self::File(path) => {
1198                let filename = path
1199                    .file_name()
1200                    .ok_or(Error::InvalidAttachmentFileName)?
1201                    .to_str()
1202                    .ok_or(Error::InvalidAttachmentFileName)?
1203                    .to_owned();
1204                let bytes = fs::read(&path).map_err(|_| Error::InvalidAttachmentData)?;
1205                Ok((bytes, filename))
1206            }
1207        }
1208    }
1209}
1210
1211impl<P> From<P> for AttachmentSource
1212where
1213    P: Into<PathBuf>,
1214{
1215    fn from(value: P) -> Self {
1216        Self::File(value.into())
1217    }
1218}
1219
1220/// Configuration for sending a gallery.
1221///
1222/// This duplicates [`matrix_sdk::attachment::GalleryConfig`] but uses an
1223/// `AttachmentSource` so that we can delay loading the actual data until we're
1224/// inside the SendGallery future. This allows [`Timeline::send_gallery`] to
1225/// return early without blocking the caller.
1226#[cfg(feature = "unstable-msc4274")]
1227#[derive(Debug, Default)]
1228pub struct GalleryConfig {
1229    pub(crate) txn_id: Option<OwnedTransactionId>,
1230    pub(crate) items: Vec<GalleryItemInfo>,
1231    pub(crate) caption: Option<TextMessageEventContent>,
1232    pub(crate) mentions: Option<Mentions>,
1233    pub(crate) in_reply_to: Option<OwnedEventId>,
1234    pub(crate) extra_content: Option<serde_json::Map<String, serde_json::Value>>,
1235}
1236
1237#[cfg(feature = "unstable-msc4274")]
1238impl GalleryConfig {
1239    /// Create a new empty `GalleryConfig`.
1240    pub fn new() -> Self {
1241        Self::default()
1242    }
1243
1244    /// Set the transaction ID to send.
1245    ///
1246    /// # Arguments
1247    ///
1248    /// - `txn_id` - A unique ID that can be attached to a `MessageEvent` held
1249    ///   in its unsigned field as `transaction_id`. If not given, one is
1250    ///   created for the message.
1251    #[must_use]
1252    pub fn txn_id(mut self, txn_id: OwnedTransactionId) -> Self {
1253        self.txn_id = Some(txn_id);
1254        self
1255    }
1256
1257    /// Adds a media item to the gallery.
1258    ///
1259    /// # Arguments
1260    ///
1261    /// * `item` - Information about the item to be added.
1262    #[must_use]
1263    pub fn add_item(mut self, item: GalleryItemInfo) -> Self {
1264        self.items.push(item);
1265        self
1266    }
1267
1268    /// Set the optional caption.
1269    ///
1270    /// # Arguments
1271    ///
1272    /// * `caption` - The optional caption.
1273    pub fn caption(mut self, caption: Option<TextMessageEventContent>) -> Self {
1274        self.caption = caption;
1275        self
1276    }
1277
1278    /// Set the mentions of the message.
1279    ///
1280    /// # Arguments
1281    ///
1282    /// * `mentions` - The mentions of the message.
1283    pub fn mentions(mut self, mentions: Option<Mentions>) -> Self {
1284        self.mentions = mentions;
1285        self
1286    }
1287
1288    /// Set the reply information of the message.
1289    ///
1290    /// # Arguments
1291    ///
1292    /// * `event_id` - The event ID to reply to.
1293    pub fn in_reply_to(mut self, event_id: Option<OwnedEventId>) -> Self {
1294        self.in_reply_to = event_id;
1295        self
1296    }
1297
1298    /// Set additional top-level fields for the gallery event's content.
1299    ///
1300    /// Objects are merged recursively; the event's own fields take precedence
1301    /// on conflicts. To add fields to individual items, use
1302    /// [`GalleryItemInfo::extra_content`].
1303    #[must_use]
1304    pub fn extra_content(
1305        mut self,
1306        extra_content: Option<serde_json::Map<String, serde_json::Value>>,
1307    ) -> Self {
1308        self.extra_content = extra_content;
1309        self
1310    }
1311
1312    /// Returns the number of media items in the gallery.
1313    pub fn len(&self) -> usize {
1314        self.items.len()
1315    }
1316
1317    /// Checks whether the gallery contains any media items or not.
1318    pub fn is_empty(&self) -> bool {
1319        self.items.is_empty()
1320    }
1321}
1322
1323#[cfg(feature = "unstable-msc4274")]
1324#[derive(Debug)]
1325/// Metadata for a gallery item
1326pub struct GalleryItemInfo {
1327    /// The attachment source.
1328    pub source: AttachmentSource,
1329    /// The mime type.
1330    pub content_type: Mime,
1331    /// The attachment info.
1332    pub attachment_info: AttachmentInfo,
1333    /// The caption.
1334    pub caption: Option<TextMessageEventContent>,
1335    /// The thumbnail.
1336    pub thumbnail: Option<Thumbnail>,
1337    /// Additional fields to merge into this item's content, for example a
1338    /// spoiler flag. Objects are merged recursively; the item's own fields take
1339    /// precedence on conflicts.
1340    pub extra_content: Option<serde_json::Map<String, serde_json::Value>>,
1341}
1342
1343#[cfg(feature = "unstable-msc4274")]
1344impl TryFrom<GalleryItemInfo> for matrix_sdk::attachment::GalleryItemInfo {
1345    type Error = Error;
1346
1347    fn try_from(value: GalleryItemInfo) -> Result<Self, Self::Error> {
1348        let (data, filename) = value.source.try_into_bytes_and_filename()?;
1349        Ok(matrix_sdk::attachment::GalleryItemInfo {
1350            filename,
1351            content_type: value.content_type,
1352            data,
1353            attachment_info: value.attachment_info,
1354            caption: value.caption,
1355            thumbnail: value.thumbnail,
1356            extra_content: value.extra_content,
1357        })
1358    }
1359}
1360
1361#[derive(Clone, Debug)]
1362#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
1363/// The level of read receipt tracking for the timeline.
1364pub enum TimelineReadReceiptTracking {
1365    /// Track read receipts for all events.
1366    AllEvents,
1367    /// Track read receipts only for message-like events.
1368    MessageLikeEvents,
1369    /// Disable read receipt tracking.
1370    Disabled,
1371}
1372
1373impl TimelineReadReceiptTracking {
1374    /// Whether or not read receipt tracking is enabled.
1375    pub fn is_enabled(&self) -> bool {
1376        match self {
1377            TimelineReadReceiptTracking::AllEvents
1378            | TimelineReadReceiptTracking::MessageLikeEvents => true,
1379            TimelineReadReceiptTracking::Disabled => false,
1380        }
1381    }
1382}