src/notifications.rs
329 lines · 10798 bytes
1use std::time::SystemTime;
2
3use matrix_sdk::{
4 deserialized_responses::RawAnySyncOrStrippedTimelineEvent,
5 notification_settings::{IsEncrypted, IsOneToOne, NotificationSettings, RoomNotificationMode},
6 room::Room as MatrixRoom,
7 ruma::{
8 events::{room::message::MessageType, AnyMessageLikeEventContent, AnySyncTimelineEvent},
9 serde::Raw,
10 MilliSecondsSinceUnixEpoch,
11 OwnedRoomId,
12 RoomId,
13 },
14 Client,
15 EncryptionState,
16};
17use unicode_segmentation::UnicodeSegmentation;
18
19use crate::{
20 base::{AsyncProgramStore, IambError, IambResult, ProgramStore},
21 config::{ApplicationSettings, NotifyVia},
22};
23
24const IAMB_XDG_NAME: &str = match option_env!("IAMB_XDG_NAME") {
25 None => "iamb",
26 Some(iamb) => iamb,
27};
28
29/// Handle for an open notification that should be closed when the user views it.
30pub struct NotificationHandle(
31 #[cfg(all(feature = "desktop", unix, not(target_os = "macos")))]
32 Option<notify_rust::NotificationHandle>,
33);
34
35impl Drop for NotificationHandle {
36 fn drop(&mut self) {
37 #[cfg(all(feature = "desktop", unix, not(target_os = "macos")))]
38 if let Some(handle) = self.0.take() {
39 handle.close();
40 }
41 }
42}
43
44pub async fn register_notifications(
45 client: &Client,
46 settings: &ApplicationSettings,
47 store: &AsyncProgramStore,
48) {
49 if !settings.tunables.notifications.enabled {
50 return;
51 }
52 let notify_via = settings.tunables.notifications.via;
53 let show_message = settings.tunables.notifications.show_message;
54 let sound_hint = settings.tunables.notifications.sound_hint.clone();
55 let server_settings = client.notification_settings().await;
56 let Some(startup_ts) = MilliSecondsSinceUnixEpoch::from_system_time(SystemTime::now()) else {
57 return;
58 };
59
60 let store = store.clone();
61 client
62 .register_notification_handler(move |notification, room: MatrixRoom, client: Client| {
63 let store = store.clone();
64 let server_settings = server_settings.clone();
65 let sound_hint = sound_hint.clone();
66 async move {
67 let mode = global_or_room_mode(&server_settings, &room).await;
68 if mode == RoomNotificationMode::Mute {
69 return;
70 }
71
72 if is_visible_room(&store, room.room_id()).await {
73 return;
74 }
75
76 let room_id = room.room_id().to_owned();
77 match notification.event {
78 RawAnySyncOrStrippedTimelineEvent::Sync(e) => {
79 match parse_full_notification(e, room, show_message).await {
80 Ok((summary, body, server_ts)) => {
81 if server_ts < startup_ts {
82 return;
83 }
84
85 if is_missing_mention(&body, mode, &client) {
86 return;
87 }
88
89 send_notification(
90 ¬ify_via,
91 &summary,
92 body.as_deref(),
93 room_id,
94 &store,
95 sound_hint.as_deref(),
96 )
97 .await;
98 },
99 Err(err) => {
100 tracing::error!("Failed to extract notification data: {err}")
101 },
102 }
103 },
104 // Stripped events may be dropped silently because they're
105 // only relevant if we're not in a room, and we presumably
106 // don't want notifications for rooms we're not in.
107 RawAnySyncOrStrippedTimelineEvent::Stripped(_) => (),
108 }
109 }
110 })
111 .await;
112}
113
114async fn send_notification(
115 via: &NotifyVia,
116 summary: &str,
117 body: Option<&str>,
118 room_id: OwnedRoomId,
119 store: &AsyncProgramStore,
120 sound_hint: Option<&str>,
121) {
122 #[cfg(feature = "desktop")]
123 if via.desktop {
124 send_notification_desktop(summary, body, room_id, store, sound_hint).await;
125 }
126 #[cfg(not(feature = "desktop"))]
127 {
128 let _ = (summary, body, IAMB_XDG_NAME);
129 }
130
131 if via.bell {
132 send_notification_bell(store).await;
133 }
134}
135
136async fn send_notification_bell(store: &AsyncProgramStore) {
137 let mut locked = store.lock().await;
138 locked.application.ring_bell = true;
139}
140
141#[cfg(feature = "desktop")]
142#[cfg_attr(target_os = "macos", allow(unused_variables))]
143async fn send_notification_desktop(
144 summary: &str,
145 body: Option<&str>,
146 room_id: OwnedRoomId,
147 _store: &AsyncProgramStore,
148 sound_hint: Option<&str>,
149) {
150 let mut desktop_notification = notify_rust::Notification::new();
151 desktop_notification
152 .summary(summary)
153 .appname(IAMB_XDG_NAME)
154 .icon(IAMB_XDG_NAME)
155 .action("default", "default");
156
157 if let Some(sound_hint) = sound_hint {
158 desktop_notification.sound_name(sound_hint);
159 }
160
161 #[cfg(all(unix, not(target_os = "macos")))]
162 desktop_notification.urgency(notify_rust::Urgency::Normal);
163
164 if let Some(body) = body {
165 desktop_notification.body(body);
166 }
167
168 #[cfg(all(unix, not(target_os = "macos")))]
169 let res = desktop_notification.show_async().await;
170 #[cfg(any(not(unix), target_os = "macos"))]
171 let res = desktop_notification.show();
172
173 match res {
174 Err(err) => tracing::error!("Failed to send notification: {err}"),
175 Ok(handle) => {
176 #[cfg(all(unix, not(target_os = "macos")))]
177 _store
178 .lock()
179 .await
180 .application
181 .open_notifications
182 .entry(room_id)
183 .or_default()
184 .push(NotificationHandle(Some(handle)));
185 },
186 }
187}
188
189async fn global_or_room_mode(
190 settings: &NotificationSettings,
191 room: &MatrixRoom,
192) -> RoomNotificationMode {
193 let room_mode = settings.get_user_defined_room_notification_mode(room.room_id()).await;
194 if let Some(mode) = room_mode {
195 return mode;
196 }
197 let is_one_to_one = match room.is_direct().await {
198 Ok(true) => IsOneToOne::Yes,
199 _ => IsOneToOne::No,
200 };
201 let is_encrypted = match room.latest_encryption_state().await {
202 Ok(EncryptionState::Encrypted) => IsEncrypted::Yes,
203 _ => IsEncrypted::No,
204 };
205 settings
206 .get_default_room_notification_mode(is_encrypted, is_one_to_one)
207 .await
208}
209
210fn is_missing_mention(body: &Option<String>, mode: RoomNotificationMode, client: &Client) -> bool {
211 if let Some(body) = body {
212 if mode == RoomNotificationMode::MentionsAndKeywordsOnly {
213 let mentioned = match client.user_id() {
214 Some(user_id) => body.contains(user_id.localpart()),
215 _ => false,
216 };
217 return !mentioned;
218 }
219 }
220 false
221}
222
223fn is_open(locked: &mut ProgramStore, room_id: &RoomId) -> bool {
224 if let Some(draw_curr) = locked.application.draw_curr {
225 let info = locked.application.get_room_info(room_id.to_owned());
226 if let Some(draw_last) = info.draw_last {
227 return draw_last == draw_curr;
228 }
229 }
230 false
231}
232
233fn is_focused(locked: &ProgramStore) -> bool {
234 locked.application.focused
235}
236
237async fn is_visible_room(store: &AsyncProgramStore, room_id: &RoomId) -> bool {
238 let mut locked = store.lock().await;
239
240 is_focused(&locked) && is_open(&mut locked, room_id)
241}
242
243pub async fn parse_full_notification(
244 event: Raw<AnySyncTimelineEvent>,
245 room: MatrixRoom,
246 show_body: bool,
247) -> IambResult<(String, Option<String>, MilliSecondsSinceUnixEpoch)> {
248 let event = event.deserialize().map_err(IambError::from)?;
249
250 let server_ts = event.origin_server_ts();
251
252 let sender_id = event.sender();
253 let sender = room.get_member_no_sync(sender_id).await.map_err(IambError::from)?;
254
255 let sender_name = sender
256 .as_ref()
257 .and_then(|m| m.display_name())
258 .unwrap_or_else(|| sender_id.localpart());
259
260 let summary = if let Some(room_name) = room.cached_display_name() {
261 if room.is_direct().await.map_err(IambError::from)? && sender_name == room_name.to_string()
262 {
263 sender_name.to_string()
264 } else {
265 format!("{sender_name} in {room_name}")
266 }
267 } else {
268 sender_name.to_string()
269 };
270
271 let body = if show_body {
272 event_notification_body(&event, sender_name).map(truncate)
273 } else {
274 None
275 };
276
277 return Ok((summary, body, server_ts));
278}
279
280pub fn event_notification_body(event: &AnySyncTimelineEvent, sender_name: &str) -> Option<String> {
281 let AnySyncTimelineEvent::MessageLike(event) = event else {
282 return None;
283 };
284
285 match event.original_content()? {
286 AnyMessageLikeEventContent::RoomMessage(message) => {
287 let body = match message.msgtype {
288 MessageType::Audio(_) => {
289 format!("{sender_name} sent an audio file.")
290 },
291 MessageType::Emote(content) => content.body,
292 MessageType::File(_) => {
293 format!("{sender_name} sent a file.")
294 },
295 MessageType::Image(_) => {
296 format!("{sender_name} sent an image.")
297 },
298 MessageType::Location(_) => {
299 format!("{sender_name} sent their location.")
300 },
301 MessageType::Notice(content) => content.body,
302 MessageType::ServerNotice(content) => content.body,
303 MessageType::Text(content) => content.body,
304 MessageType::Video(_) => {
305 format!("{sender_name} sent a video.")
306 },
307 MessageType::VerificationRequest(_) => {
308 format!("{sender_name} sent a verification request.")
309 },
310 _ => {
311 format!("[Unknown message type: {:?}]", &message.msgtype)
312 },
313 };
314 Some(body)
315 },
316 AnyMessageLikeEventContent::Sticker(_) => Some(format!("{sender_name} sent a sticker.")),
317 _ => None,
318 }
319}
320
321fn truncate(s: String) -> String {
322 static MAX_LENGTH: usize = 5000;
323 if s.graphemes(true).count() > MAX_LENGTH {
324 let truncated: String = s.graphemes(true).take(MAX_LENGTH).collect();
325 truncated + "..."
326 } else {
327 s
328 }
329}