1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
// Copyright 2022 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.

//! The SDK's representation of the result of a `/sync` request.

use std::{collections::BTreeMap, fmt};

use matrix_sdk_common::{debug::DebugRawEvent, deserialized_responses::SyncTimelineEvent};
use ruma::{
    api::client::sync::sync_events::{
        v3::InvitedRoom as InvitedRoomUpdate,
        UnreadNotificationsCount as RumaUnreadNotificationsCount,
    },
    events::{
        presence::PresenceEvent, AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent,
        AnySyncEphemeralRoomEvent, AnySyncStateEvent, AnyToDeviceEvent,
    },
    push::Action,
    serde::Raw,
    OwnedEventId, OwnedRoomId,
};
use serde::{Deserialize, Serialize};

use crate::{
    debug::{DebugInvitedRoom, DebugListOfRawEvents, DebugListOfRawEventsNoId},
    deserialized_responses::{AmbiguityChange, RawAnySyncOrStrippedTimelineEvent},
};

/// Generalized representation of a `/sync` response.
///
/// This type is intended to be applicable regardless of the endpoint used for
/// syncing.
#[derive(Clone, Default)]
pub struct SyncResponse {
    /// Updates to rooms.
    pub rooms: RoomUpdates,
    /// Updates to the presence status of other users.
    pub presence: Vec<Raw<PresenceEvent>>,
    /// The global private data created by this user.
    pub account_data: Vec<Raw<AnyGlobalAccountDataEvent>>,
    /// Messages sent directly between devices.
    pub to_device: Vec<Raw<AnyToDeviceEvent>>,
    /// New notifications per room.
    pub notifications: BTreeMap<OwnedRoomId, Vec<Notification>>,
}

#[cfg(not(tarpaulin_include))]
impl fmt::Debug for SyncResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SyncResponse")
            .field("rooms", &self.rooms)
            .field("account_data", &DebugListOfRawEventsNoId(&self.account_data))
            .field("to_device", &DebugListOfRawEventsNoId(&self.to_device))
            .field("notifications", &self.notifications)
            .finish_non_exhaustive()
    }
}

/// Updates to rooms in a [`SyncResponse`].
#[derive(Clone, Default)]
pub struct RoomUpdates {
    /// The rooms that the user has left or been banned from.
    pub leave: BTreeMap<OwnedRoomId, LeftRoomUpdate>,
    /// The rooms that the user has joined.
    pub join: BTreeMap<OwnedRoomId, JoinedRoomUpdate>,
    /// The rooms that the user has been invited to.
    pub invite: BTreeMap<OwnedRoomId, InvitedRoomUpdate>,
}

#[cfg(not(tarpaulin_include))]
impl fmt::Debug for RoomUpdates {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Rooms")
            .field("leave", &self.leave)
            .field("join", &self.join)
            .field("invite", &DebugInvitedRoomUpdates(&self.invite))
            .finish()
    }
}

/// Updates to joined rooms.
#[derive(Clone, Default)]
pub struct JoinedRoomUpdate {
    /// Counts of unread notifications for this room.
    pub unread_notifications: UnreadNotificationsCount,
    /// The timeline of messages and state changes in the room.
    pub timeline: Timeline,
    /// Updates to the state, between the time indicated by the `since`
    /// parameter, and the start of the `timeline` (or all state up to the
    /// start of the `timeline`, if `since` is not given, or `full_state` is
    /// true).
    pub state: Vec<Raw<AnySyncStateEvent>>,
    /// The private data that this user has attached to this room.
    pub account_data: Vec<Raw<AnyRoomAccountDataEvent>>,
    /// The ephemeral events in the room that aren't recorded in the timeline or
    /// state of the room. e.g. typing.
    pub ephemeral: Vec<Raw<AnySyncEphemeralRoomEvent>>,
    /// Collection of ambiguity changes that room member events trigger.
    ///
    /// This is a map of event ID of the `m.room.member` event to the
    /// details of the ambiguity change.
    pub ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
}

#[cfg(not(tarpaulin_include))]
impl fmt::Debug for JoinedRoomUpdate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("JoinedRoom")
            .field("unread_notifications", &self.unread_notifications)
            .field("timeline", &self.timeline)
            .field("state", &DebugListOfRawEvents(&self.state))
            .field("account_data", &DebugListOfRawEventsNoId(&self.account_data))
            .field("ephemeral", &self.ephemeral)
            .field("ambiguity_changes", &self.ambiguity_changes)
            .finish()
    }
}

impl JoinedRoomUpdate {
    pub(crate) fn new(
        timeline: Timeline,
        state: Vec<Raw<AnySyncStateEvent>>,
        account_data: Vec<Raw<AnyRoomAccountDataEvent>>,
        ephemeral: Vec<Raw<AnySyncEphemeralRoomEvent>>,
        unread_notifications: UnreadNotificationsCount,
        ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
    ) -> Self {
        Self { unread_notifications, timeline, state, account_data, ephemeral, ambiguity_changes }
    }
}

/// Counts of unread notifications for a room.
#[derive(Copy, Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub struct UnreadNotificationsCount {
    /// The number of unread notifications for this room with the highlight flag
    /// set.
    pub highlight_count: u64,
    /// The total number of unread notifications for this room.
    pub notification_count: u64,
}

impl From<RumaUnreadNotificationsCount> for UnreadNotificationsCount {
    fn from(notifications: RumaUnreadNotificationsCount) -> Self {
        Self {
            highlight_count: notifications.highlight_count.map(|c| c.into()).unwrap_or(0),
            notification_count: notifications.notification_count.map(|c| c.into()).unwrap_or(0),
        }
    }
}

/// Updates to left rooms.
#[derive(Clone, Default)]
pub struct LeftRoomUpdate {
    /// The timeline of messages and state changes in the room up to the point
    /// when the user left.
    pub timeline: Timeline,
    /// Updates to the state, between the time indicated by the `since`
    /// parameter, and the start of the `timeline` (or all state up to the
    /// start of the `timeline`, if `since` is not given, or `full_state` is
    /// true).
    pub state: Vec<Raw<AnySyncStateEvent>>,
    /// The private data that this user has attached to this room.
    pub account_data: Vec<Raw<AnyRoomAccountDataEvent>>,
    /// Collection of ambiguity changes that room member events trigger.
    ///
    /// This is a map of event ID of the `m.room.member` event to the
    /// details of the ambiguity change.
    pub ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
}

impl LeftRoomUpdate {
    pub(crate) fn new(
        timeline: Timeline,
        state: Vec<Raw<AnySyncStateEvent>>,
        account_data: Vec<Raw<AnyRoomAccountDataEvent>>,
        ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
    ) -> Self {
        Self { timeline, state, account_data, ambiguity_changes }
    }
}

#[cfg(not(tarpaulin_include))]
impl fmt::Debug for LeftRoomUpdate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("JoinedRoom")
            .field("timeline", &self.timeline)
            .field("state", &DebugListOfRawEvents(&self.state))
            .field("account_data", &DebugListOfRawEventsNoId(&self.account_data))
            .field("ambiguity_changes", &self.ambiguity_changes)
            .finish()
    }
}

/// Events in the room.
#[derive(Clone, Debug, Default)]
pub struct Timeline {
    /// True if the number of events returned was limited by the `limit` on the
    /// filter.
    pub limited: bool,

    /// A token that can be supplied to to the `from` parameter of the
    /// `/rooms/{roomId}/messages` endpoint.
    pub prev_batch: Option<String>,

    /// A list of events.
    pub events: Vec<SyncTimelineEvent>,
}

impl Timeline {
    pub(crate) fn new(limited: bool, prev_batch: Option<String>) -> Self {
        Self { limited, prev_batch, ..Default::default() }
    }
}

struct DebugInvitedRoomUpdates<'a>(&'a BTreeMap<OwnedRoomId, InvitedRoomUpdate>);

#[cfg(not(tarpaulin_include))]
impl<'a> fmt::Debug for DebugInvitedRoomUpdates<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_map().entries(self.0.iter().map(|(k, v)| (k, DebugInvitedRoom(v)))).finish()
    }
}

/// A notification triggered by a sync response.
#[derive(Clone)]
pub struct Notification {
    /// The actions to perform when the conditions for this rule are met.
    pub actions: Vec<Action>,

    /// The event that triggered the notification.
    pub event: RawAnySyncOrStrippedTimelineEvent,
}

#[cfg(not(tarpaulin_include))]
impl fmt::Debug for Notification {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let event_debug = match &self.event {
            RawAnySyncOrStrippedTimelineEvent::Sync(ev) => DebugRawEvent(ev),
            RawAnySyncOrStrippedTimelineEvent::Stripped(ev) => DebugRawEvent(ev.cast_ref()),
        };

        f.debug_struct("Notification")
            .field("actions", &self.actions)
            .field("event", &event_debug)
            .finish()
    }
}