atagen

matrix-rust-sdk

public
Star0
Watch0
ssh://brewery@pls.lobotomise.me:33/atagen/matrix-rust-sdk.git
bindings/matrix-sdk-ffi/src/notification.rsRust275 lines9.9 KB
1
// Copyright 2025 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 that specific language governing permissions and
13
// limitations under the License.
14
15
use std::{collections::HashMap, sync::Arc};
16
17
use matrix_sdk_ui::notification_client::{
18
    NotificationClient as SdkNotificationClient, NotificationEvent as SdkNotificationEvent,
19
    NotificationItem as SdkNotificationItem, NotificationStatus as SdkNotificationStatus,
20
    RawNotificationEvent as SdkRawNotificationEvent,
21
};
22
use ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId};
23
24
use crate::{
25
    client::{Client, JoinRule},
26
    error::ClientError,
27
    event::TimelineEvent,
28
    room::Room,
29
};
30
31
#[derive(uniffi::Enum)]
32
pub enum NotificationEvent {
33
    Timeline { event: Arc<TimelineEvent> },
34
    Invite { sender: String },
35
}
36
37
#[derive(uniffi::Record)]
38
pub struct NotificationSenderInfo {
39
    pub display_name: Option<String>,
40
    pub avatar_url: Option<String>,
41
    pub is_name_ambiguous: bool,
42
}
43
44
#[derive(uniffi::Record)]
45
pub struct NotificationRoomInfo {
46
    pub display_name: String,
47
    pub avatar_url: Option<String>,
48
    pub canonical_alias: Option<String>,
49
    pub topic: Option<String>,
50
    pub join_rule: Option<JoinRule>,
51
    pub joined_members_count: u64,
52
    pub active_service_members_count: u64,
53
    pub service_members: Vec<String>,
54
    pub is_encrypted: Option<bool>,
55
    pub is_direct: bool,
56
    pub is_space: bool,
57
    pub is_dm: bool,
58
}
59
60
#[derive(uniffi::Record)]
61
pub struct NotificationItem {
62
    pub event: NotificationEvent,
63
64
    /// The raw JSON of the underlying event.
65
    pub raw_event: String,
66
67
    pub sender_info: NotificationSenderInfo,
68
    pub room_info: NotificationRoomInfo,
69
70
    /// Is the notification supposed to be at the "noisy" level?
71
    /// Can be `None` if we couldn't determine this, because we lacked
72
    /// information to create a push context.
73
    pub is_noisy: Option<bool>,
74
    pub has_mention: Option<bool>,
75
    pub thread_id: Option<String>,
76
77
    /// The push actions for this notification (notify, sound, highlight, etc.).
78
    pub actions: Option<Vec<crate::notification_settings::Action>>,
79
}
80
81
impl NotificationItem {
82
    fn from_inner(item: SdkNotificationItem) -> Self {
83
        let event = match item.event {
84
            SdkNotificationEvent::Timeline(event) => {
85
                NotificationEvent::Timeline { event: Arc::new(TimelineEvent(event)) }
86
            }
87
            SdkNotificationEvent::Invite(event) => {
88
                NotificationEvent::Invite { sender: event.sender.to_string() }
89
            }
90
        };
91
92
        let raw_event = match &item.raw_event {
93
            SdkRawNotificationEvent::Timeline(raw) => raw.json().get().to_owned(),
94
            SdkRawNotificationEvent::Invite(raw) => raw.json().get().to_owned(),
95
        };
96
97
        Self {
98
            event,
99
            raw_event,
100
            sender_info: NotificationSenderInfo {
101
                display_name: item.sender_display_name,
102
                avatar_url: item.sender_avatar_url,
103
                is_name_ambiguous: item.is_sender_name_ambiguous,
104
            },
105
            room_info: NotificationRoomInfo {
106
                display_name: item.room_computed_display_name,
107
                avatar_url: item.room_avatar_url,
108
                canonical_alias: item.room_canonical_alias,
109
                topic: item.room_topic,
110
                join_rule: item.room_join_rule.map(TryInto::try_into).transpose().ok().flatten(),
111
                joined_members_count: item.joined_members_count,
112
                service_members: item.service_members,
113
                active_service_members_count: item.active_service_members_count,
114
                is_encrypted: item.is_room_encrypted,
115
                is_direct: item.is_direct_message_room,
116
                is_space: item.is_space,
117
                is_dm: item.room_is_dm,
118
            },
119
            is_noisy: item.is_noisy,
120
            has_mention: item.has_mention,
121
            thread_id: item.thread_id.map(|t| t.to_string()),
122
            actions: item
123
                .actions
124
                .map(|a| a.into_iter().filter_map(|action| action.try_into().ok()).collect()),
125
        }
126
    }
127
}
128
129
#[allow(clippy::large_enum_variant)]
130
#[derive(uniffi::Enum)]
131
pub enum NotificationStatus {
132
    /// The event has been found and was not filtered out.
133
    Event { item: NotificationItem },
134
    /// The event couldn't be found in the network queries used to find it.
135
    EventNotFound,
136
    /// The event has been filtered out, either because of the user's push
137
    /// rules, or because the user which triggered it is ignored by the
138
    /// current user.
139
    EventFilteredOut,
140
    /// The event has been redacted.
141
    EventRedacted,
142
}
143
144
impl From<SdkNotificationStatus> for NotificationStatus {
145
    fn from(item: SdkNotificationStatus) -> Self {
146
        match item {
147
            SdkNotificationStatus::Event(item) => {
148
                NotificationStatus::Event { item: NotificationItem::from_inner(*item) }
149
            }
150
            SdkNotificationStatus::EventNotFound => NotificationStatus::EventNotFound,
151
            SdkNotificationStatus::EventFilteredOut => NotificationStatus::EventFilteredOut,
152
            SdkNotificationStatus::EventRedacted => NotificationStatus::EventRedacted,
153
        }
154
    }
155
}
156
157
#[allow(clippy::large_enum_variant)]
158
#[derive(uniffi::Enum)]
159
pub enum BatchNotificationResult {
160
    /// We have more detailed information about the notification.
161
    Ok { status: NotificationStatus },
162
    /// An error occurred while trying to fetch the notification.
163
    Error {
164
        /// The error message observed while handling a specific notification.
165
        message: String,
166
    },
167
}
168
169
#[derive(uniffi::Object)]
170
pub struct NotificationClient {
171
    pub(crate) inner: SdkNotificationClient,
172
173
    /// A reference to the FFI client.
174
    ///
175
    /// Note: we do this to make it so that the FFI `NotificationClient` keeps
176
    /// the FFI `Client` and thus the SDK `Client` alive. Otherwise, we
177
    /// would need to repeat the hack done in the FFI `Client::drop` method.
178
    pub(crate) client: Arc<Client>,
179
}
180
181
#[matrix_sdk_ffi_macros::export]
182
impl NotificationClient {
183
    /// Fetches a room by its ID using the in-memory state store backed client.
184
    ///
185
    /// Useful to retrieve room information after running the limited
186
    /// notification client sliding sync loop.
187
    pub fn get_room(&self, room_id: String) -> Result<Option<Arc<Room>>, ClientError> {
188
        let room_id = RoomId::parse(room_id)?;
189
        let sdk_room = self.inner.get_room(&room_id);
190
        let room = sdk_room
191
            .map(|room| Arc::new(Room::new(room, self.client.utd_hook_manager.get().cloned())));
192
        Ok(room)
193
    }
194
195
    /// Fetches the content of a notification.
196
    ///
197
    /// This will first try to get the notification using a short-lived sliding
198
    /// sync, and if the sliding-sync can't find the event, then it'll use a
199
    /// `/context` query to find the event with associated member information.
200
    ///
201
    /// An error result means that we couldn't resolve the notification; in that
202
    /// case, a dummy notification may be displayed instead.
203
    pub async fn get_notification(
204
        &self,
205
        room_id: String,
206
        event_id: String,
207
    ) -> Result<NotificationStatus, ClientError> {
208
        let room_id = RoomId::parse(room_id)?;
209
        let event_id = EventId::parse(event_id)?;
210
211
        let item =
212
            self.inner.get_notification(&room_id, &event_id).await.map_err(ClientError::from)?;
213
214
        Ok(item.into())
215
    }
216
217
    /// Get several notification items in a single batch.
218
    ///
219
    /// Returns an error if the flow failed when preparing to fetch the
220
    /// notifications, and a [`HashMap`] containing either a
221
    /// [`BatchNotificationResult`], that indicates if the notification was
222
    /// successfully fetched (in which case, it's a [`NotificationStatus`]), or
223
    /// an error message if it couldn't be fetched.
224
    pub async fn get_notifications(
225
        &self,
226
        requests: Vec<NotificationItemsRequest>,
227
    ) -> Result<HashMap<String, BatchNotificationResult>, ClientError> {
228
        let requests =
229
            requests.into_iter().map(TryInto::try_into).collect::<Result<Vec<_>, _>>()?;
230
231
        let items = self.inner.get_notifications(&requests).await?;
232
233
        let mut batch_result = HashMap::new();
234
        for (key, value) in items.into_iter() {
235
            let result = match value {
236
                Ok(status) => BatchNotificationResult::Ok { status: status.into() },
237
                Err(error) => BatchNotificationResult::Error { message: error.to_string() },
238
            };
239
            batch_result.insert(key.to_string(), result);
240
        }
241
242
        Ok(batch_result)
243
    }
244
}
245
246
/// A request for notification items grouped by their room.
247
#[derive(uniffi::Record)]
248
pub struct NotificationItemsRequest {
249
    room_id: String,
250
    event_ids: Vec<String>,
251
}
252
253
impl NotificationItemsRequest {
254
    /// The parsed [`OwnedRoomId`] to use with the SDK crates.
255
    pub fn room_id(&self) -> Result<OwnedRoomId, ClientError> {
256
        RoomId::parse(&self.room_id).map_err(ClientError::from)
257
    }
258
259
    /// The parsed [`OwnedEventId`] list to use with the SDK crates.
260
    pub fn event_ids(&self) -> Result<Vec<OwnedEventId>, ClientError> {
261
        self.event_ids
262
            .iter()
263
            .map(|id| EventId::parse(id).map_err(ClientError::from))
264
            .collect::<Result<Vec<_>, _>>()
265
    }
266
}
267
268
impl TryFrom<NotificationItemsRequest>
269
    for matrix_sdk_ui::notification_client::NotificationItemsRequest
270
{
271
    type Error = ClientError;
272
    fn try_from(value: NotificationItemsRequest) -> Result<Self, Self::Error> {
273
        Ok(Self { room_id: value.room_id()?, event_ids: value.event_ids()? })
274
    }
275
}