src/notifications.rs

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