src/notifications.rs

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