src/notifications.rs

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