1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
// Copyright 2023 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::ops::ControlFlow;

use async_rx::StreamExt as _;
use async_stream::stream;
use futures_core::Stream;
use futures_util::{pin_mut, StreamExt as _};
use matrix_sdk::event_cache::{
    self,
    paginator::{PaginatorError, PaginatorState},
    BackPaginationOutcome, EventCacheError, RoomPagination,
};
use tracing::{instrument, trace, warn};

use super::Error;
use crate::timeline::{controller::TimelineEnd, event_item::RemoteEventOrigin};

impl super::Timeline {
    /// Add more events to the start of the timeline.
    ///
    /// Returns whether we hit the start of the timeline.
    #[instrument(skip_all, fields(room_id = ?self.room().room_id()))]
    pub async fn paginate_backwards(&self, num_events: u16) -> Result<bool, Error> {
        if self.controller.is_live().await {
            Ok(self.live_paginate_backwards(num_events).await?)
        } else {
            Ok(self.focused_paginate_backwards(num_events).await?)
        }
    }

    /// Assuming the timeline is focused on an event, starts a forwards
    /// pagination.
    ///
    /// Returns whether we hit the end of the timeline.
    #[instrument(skip_all)]
    pub async fn focused_paginate_forwards(&self, num_events: u16) -> Result<bool, Error> {
        Ok(self.controller.focused_paginate_forwards(num_events).await?)
    }

    /// Assuming the timeline is focused on an event, starts a backwards
    /// pagination.
    ///
    /// Returns whether we hit the start of the timeline.
    #[instrument(skip(self), fields(room_id = ?self.room().room_id()))]
    pub async fn focused_paginate_backwards(&self, num_events: u16) -> Result<bool, Error> {
        Ok(self.controller.focused_paginate_backwards(num_events).await?)
    }

    /// Paginate backwards in live mode.
    ///
    /// This can only be called when the timeline is in live mode, not focused
    /// on a specific event.
    ///
    /// Returns whether we hit the start of the timeline.
    #[instrument(skip_all, fields(room_id = ?self.room().room_id()))]
    pub async fn live_paginate_backwards(&self, batch_size: u16) -> event_cache::Result<bool> {
        let pagination = self.event_cache.pagination();

        let result = pagination
            .run_backwards(
                batch_size,
                |BackPaginationOutcome { events, reached_start },
                 _timeline_has_been_reset| async move {
                    let num_events = events.len();
                    trace!("Back-pagination succeeded with {num_events} events");

                    // TODO(hywan): Remove, and let spread events via
                    // `matrix_sdk::event_cache::RoomEventCacheUpdate` from
                    // `matrix_sdk::event_cache::RoomPagination::run_backwards`.
                    self.controller
                        .add_events_at(events, TimelineEnd::Front, RemoteEventOrigin::Pagination)
                        .await;

                    if num_events == 0 && !reached_start {
                        // As an exceptional contract: if there were no events in the response,
                        // and we've not hit the start of the timeline, retry until we get
                        // some events or reach the start of the timeline.
                        return ControlFlow::Continue(());
                    }

                    ControlFlow::Break(reached_start)
                },
            )
            .await;

        match result {
            Err(EventCacheError::BackpaginationError(PaginatorError::InvalidPreviousState {
                actual: PaginatorState::Paginating,
                ..
            })) => {
                warn!("Another pagination request is already happening, returning early");
                Ok(false)
            }

            result => result,
        }
    }

    /// Subscribe to the back-pagination status of a live timeline.
    ///
    /// This will return `None` if the timeline is in the focused mode.
    ///
    /// Note: this may send multiple Paginating/Idle sequences during a single
    /// call to [`Self::paginate_backwards()`].
    pub async fn live_back_pagination_status(
        &self,
    ) -> Option<(LiveBackPaginationStatus, impl Stream<Item = LiveBackPaginationStatus>)> {
        if !self.controller.is_live().await {
            return None;
        }

        let pagination = self.event_cache.pagination();

        let mut status = pagination.status();

        let current_value =
            LiveBackPaginationStatus::from_paginator_status(&pagination, status.next_now());

        let stream = Box::pin(stream! {
            let status_stream = status.dedup();

            pin_mut!(status_stream);

            while let Some(state) = status_stream.next().await {
                yield LiveBackPaginationStatus::from_paginator_status(&pagination, state);
            }
        });

        Some((current_value, stream))
    }
}

/// Status for the back-pagination on a live timeline.
#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
pub enum LiveBackPaginationStatus {
    /// No back-pagination is happening right now.
    Idle {
        /// Have we hit the start of the timeline, i.e. back-paginating wouldn't
        /// have any effect?
        hit_start_of_timeline: bool,
    },

    /// Back-pagination is already running in the background.
    Paginating,
}

impl LiveBackPaginationStatus {
    /// Converts from a [`PaginatorState`] into the live back-pagination status.
    ///
    /// Private method instead of `From`/`Into` impl, to avoid making it public
    /// API.
    fn from_paginator_status(pagination: &RoomPagination, state: PaginatorState) -> Self {
        match state {
            PaginatorState::Initial => Self::Idle { hit_start_of_timeline: false },
            PaginatorState::FetchingTargetEvent => {
                panic!("unexpected paginator state for a live backpagination")
            }
            PaginatorState::Idle => {
                Self::Idle { hit_start_of_timeline: pagination.hit_timeline_start() }
            }
            PaginatorState::Paginating => Self::Paginating,
        }
    }
}