src/notifications.rs

382 lines · 12540 bytes

  1use std::time::SystemTime;
  2
  3use matrix_sdk::EncryptionState;
  4use matrix_sdk::deserialized_responses::RawAnySyncOrStrippedTimelineEvent;
  5use matrix_sdk::notification_settings::{
  6    IsEncrypted,
  7    IsOneToOne,
  8    NotificationSettings,
  9    RoomNotificationMode,
 10};
 11use matrix_sdk::ruma::events::room::message::Relation;
 12use matrix_sdk::ruma::events::{
 13    AnyMessageLikeEventContent,
 14    AnySyncMessageLikeEvent,
 15    AnySyncTimelineEvent,
 16    Mentions,
 17    SyncMessageLikeEvent,
 18};
 19use matrix_sdk::ruma::serde::Raw;
 20
 21use crate::config::NotifyVia;
 22use crate::prelude::*;
 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 server_settings = client.notification_settings().await;
 54    let Some(startup_ts) = MilliSecondsSinceUnixEpoch::from_system_time(SystemTime::now()) else {
 55        return;
 56    };
 57
 58    let store = store.clone();
 59    client
 60        .register_notification_handler(move |notification, room: MatrixRoom, client: Client| {
 61            let store = store.clone();
 62            let server_settings = server_settings.clone();
 63            async move {
 64                let mode = global_or_room_mode(&server_settings, &room).await;
 65                if mode == RoomNotificationMode::Mute {
 66                    return;
 67                }
 68
 69                if is_visible_room(&store, room.room_id()).await {
 70                    return;
 71                }
 72
 73                let room_id = room.room_id().to_owned();
 74                match notification.event {
 75                    RawAnySyncOrStrippedTimelineEvent::Sync(e) => {
 76                        match parse_full_notification(e, room, &store).await {
 77                            Ok((summary, body, server_ts, mentions)) => {
 78                                if server_ts < startup_ts {
 79                                    return;
 80                                }
 81
 82                                let Some(body) = body else {
 83                                    // Don't show notifications for unsupported event types.
 84                                    return;
 85                                };
 86
 87                                if is_missing_mention(
 88                                    &body,
 89                                    mentions,
 90                                    mode,
 91                                    &client,
 92                                    &server_settings,
 93                                )
 94                                .await
 95                                {
 96                                    return;
 97                                }
 98
 99                                send_notification(&notify_via, &summary, &body, room_id, &store)
100                                    .await;
101                            },
102                            Err(err) => {
103                                tracing::error!("Failed to extract notification data: {err}")
104                            },
105                        }
106                    },
107                    // Stripped events may be dropped silently because they're
108                    // only relevant if we're not in a room, and we presumably
109                    // don't want notifications for rooms we're not in.
110                    RawAnySyncOrStrippedTimelineEvent::Stripped(_) => (),
111                }
112            }
113        })
114        .await;
115}
116
117async fn send_notification(
118    via: &NotifyVia,
119    summary: &str,
120    body: &str,
121    room_id: OwnedRoomId,
122    store: &AsyncProgramStore,
123) {
124    #[cfg(feature = "desktop")]
125    if via.desktop {
126        send_notification_desktop(summary, body, room_id, store).await;
127    }
128    #[cfg(not(feature = "desktop"))]
129    {
130        let _ = (summary, body, IAMB_XDG_NAME);
131    }
132
133    if via.bell {
134        send_notification_bell(store).await;
135    }
136}
137
138async fn send_notification_bell(store: &AsyncProgramStore) {
139    let mut locked = store.lock().await;
140    locked.application.ring_bell = true;
141}
142
143#[cfg(feature = "desktop")]
144#[cfg_attr(target_os = "macos", allow(unused_variables, unused_mut))]
145async fn send_notification_desktop(
146    summary: &str,
147    body: &str,
148    room_id: OwnedRoomId,
149    store: &AsyncProgramStore,
150) {
151    let mut locked = store.lock().await;
152    let settings = &locked.application.settings;
153
154    let mut desktop_notification = notify_rust::Notification::new();
155    desktop_notification
156        .summary(summary)
157        .appname(IAMB_XDG_NAME)
158        .icon(IAMB_XDG_NAME)
159        .action("default", "default");
160
161    if let Some(sound_hint) = &settings.tunables.notifications.sound_hint {
162        desktop_notification.sound_name(sound_hint);
163    }
164
165    #[cfg(all(unix, not(target_os = "macos")))]
166    desktop_notification.urgency(notify_rust::Urgency::Normal);
167
168    if settings.tunables.notifications.show_message {
169        desktop_notification.body(body);
170    }
171
172    #[cfg(all(unix, not(target_os = "macos")))]
173    let res = desktop_notification.show_async().await;
174    #[cfg(any(not(unix), target_os = "macos"))]
175    let res = desktop_notification.show();
176
177    match res {
178        Err(err) => tracing::error!("Failed to send notification: {err}"),
179        Ok(handle) => {
180            #[cfg(all(unix, not(target_os = "macos")))]
181            locked
182                .application
183                .open_notifications
184                .entry(room_id)
185                .or_default()
186                .push(NotificationHandle(Some(handle)));
187        },
188    }
189}
190
191async fn global_or_room_mode(
192    settings: &NotificationSettings,
193    room: &MatrixRoom,
194) -> RoomNotificationMode {
195    let room_mode = settings.get_user_defined_room_notification_mode(room.room_id()).await;
196    if let Some(mode) = room_mode {
197        return mode;
198    }
199    let is_one_to_one = match room.is_direct().await {
200        Ok(true) => IsOneToOne::Yes,
201        _ => IsOneToOne::No,
202    };
203    let is_encrypted = match room.latest_encryption_state().await {
204        Ok(EncryptionState::Encrypted) => IsEncrypted::Yes,
205        _ => IsEncrypted::No,
206    };
207    settings
208        .get_default_room_notification_mode(is_encrypted, is_one_to_one)
209        .await
210}
211
212async fn is_missing_mention(
213    body: &str,
214    mentions: Mentions,
215    mode: RoomNotificationMode,
216    client: &Client,
217    settings: &NotificationSettings,
218) -> bool {
219    if mode != RoomNotificationMode::MentionsAndKeywordsOnly {
220        return false;
221    }
222
223    if mentions.room {
224        return false;
225    }
226    if client.user_id().is_some_and(|user_id| mentions.user_ids.contains(user_id)) {
227        return false;
228    }
229
230    for keyword in settings.enabled_keywords().await {
231        if body.contains(&keyword) {
232            return false;
233        }
234    }
235
236    true
237}
238
239fn is_open(locked: &mut ProgramStore, room_id: &RoomId) -> bool {
240    if let Some(draw_curr) = locked.application.draw_curr {
241        let info = locked.application.get_room_info(room_id.to_owned());
242        if let Some(draw_last) = info.draw_last {
243            return draw_last == draw_curr;
244        }
245    }
246    false
247}
248
249fn is_focused(locked: &ProgramStore) -> bool {
250    locked.application.focused
251}
252
253async fn is_visible_room(store: &AsyncProgramStore, room_id: &RoomId) -> bool {
254    let mut locked = store.lock().await;
255
256    is_focused(&locked) && is_open(&mut locked, room_id)
257}
258
259pub async fn parse_full_notification(
260    event: Raw<AnySyncTimelineEvent>,
261    room: MatrixRoom,
262    store: &AsyncProgramStore,
263) -> IambResult<(String, Option<String>, MilliSecondsSinceUnixEpoch, Mentions)> {
264    let event = event.deserialize().map_err(IambError::from)?;
265
266    let server_ts = event.origin_server_ts();
267
268    let mut locked = store.lock().await;
269    let ChatStore { rooms, settings, .. } = &mut locked.application;
270    let info = rooms.get_or_default(room.room_id().to_owned());
271
272    // Get the sender name from room info or the room directly and respect the display_name setting
273    let sender;
274    let mut sender_name = info.display_names.get(event.sender());
275    if sender_name.is_none() {
276        sender = room.get_member_no_sync(event.sender()).await.map_err(IambError::from)?;
277        sender_name = sender.as_ref().and_then(|m| m.display_name()).map(Cow::Borrowed);
278    }
279    let sender_name = settings.get_user_span(event.sender(), sender_name).content;
280
281    let summary = if let Some(room_name) = room.cached_display_name() {
282        if room.is_direct().await.map_err(IambError::from)? && sender_name == room_name.to_string()
283        {
284            sender_name.to_string()
285        } else {
286            format!("{sender_name} in {room_name}")
287        }
288    } else {
289        sender_name.to_string()
290    };
291
292    let body = event_notification_body(&event, &sender_name).map(truncate);
293
294    let mentions = if let AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(
295        SyncMessageLikeEvent::Original(ev),
296    )) = event
297    {
298        ev.content.mentions.unwrap_or_default()
299    } else {
300        Default::default()
301    };
302
303    return Ok((summary, body, server_ts, mentions));
304}
305
306pub fn event_notification_body(event: &AnySyncTimelineEvent, sender_name: &str) -> Option<String> {
307    let AnySyncTimelineEvent::MessageLike(event) = event else {
308        return None;
309    };
310
311    match event.original_content()? {
312        AnyMessageLikeEventContent::RoomMessage(message) => {
313            let is_thread = matches!(message.relates_to, Some(Relation::Thread(_)));
314            let body = match message.msgtype {
315                MessageType::Audio(_) => {
316                    format!("{sender_name} sent an audio file.")
317                },
318                MessageType::Emote(content) => content.body,
319                MessageType::File(_) => {
320                    format!("{sender_name} sent a file.")
321                },
322                MessageType::Image(_) => {
323                    format!("{sender_name} sent an image.")
324                },
325                MessageType::Location(_) => {
326                    format!("{sender_name} sent their location.")
327                },
328                MessageType::Notice(content) => content.body,
329                MessageType::ServerNotice(content) => content.body,
330                MessageType::Text(content) => content.body,
331                MessageType::Video(_) => {
332                    format!("{sender_name} sent a video.")
333                },
334                MessageType::VerificationRequest(_) => {
335                    format!("{sender_name} sent a verification request.")
336                },
337                _ => {
338                    format!("[Unknown message type: {:?}]", &message.msgtype)
339                },
340            };
341            Some(thread_notification_body(body, is_thread))
342        },
343        AnyMessageLikeEventContent::Sticker(_) => Some(format!("{sender_name} sent a sticker.")),
344        AnyMessageLikeEventContent::PollStart(_) |
345        AnyMessageLikeEventContent::UnstablePollStart(_) => {
346            Some(format!("{sender_name} started a poll."))
347        },
348        AnyMessageLikeEventContent::PollEnd(_) | AnyMessageLikeEventContent::UnstablePollEnd(_) => {
349            Some(format!("{sender_name} closed a poll."))
350        },
351        _ => None,
352    }
353}
354
355fn thread_notification_body(body: String, is_thread: bool) -> String {
356    if is_thread {
357        format!("Thread: {body}")
358    } else {
359        body
360    }
361}
362
363fn truncate(s: String) -> String {
364    static MAX_LENGTH: usize = 5000;
365    if s.graphemes(true).count() > MAX_LENGTH {
366        let truncated: String = s.graphemes(true).take(MAX_LENGTH).collect();
367        truncated + "..."
368    } else {
369        s
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    use super::thread_notification_body;
376
377    #[test]
378    fn thread_messages_are_identified_in_notifications() {
379        assert_eq!(thread_notification_body("hello".into(), true), "Thread: hello");
380        assert_eq!(thread_notification_body("hello".into(), false), "hello");
381    }
382}