src/notifications.rs

324 lines · 10627 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                                    &notify_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    match desktop_notification.show() {
169        Err(err) => tracing::error!("Failed to send notification: {err}"),
170        Ok(handle) => {
171            #[cfg(all(unix, not(target_os = "macos")))]
172            _store
173                .lock()
174                .await
175                .application
176                .open_notifications
177                .entry(room_id)
178                .or_default()
179                .push(NotificationHandle(Some(handle)));
180        },
181    }
182}
183
184async fn global_or_room_mode(
185    settings: &NotificationSettings,
186    room: &MatrixRoom,
187) -> RoomNotificationMode {
188    let room_mode = settings.get_user_defined_room_notification_mode(room.room_id()).await;
189    if let Some(mode) = room_mode {
190        return mode;
191    }
192    let is_one_to_one = match room.is_direct().await {
193        Ok(true) => IsOneToOne::Yes,
194        _ => IsOneToOne::No,
195    };
196    let is_encrypted = match room.latest_encryption_state().await {
197        Ok(EncryptionState::Encrypted) => IsEncrypted::Yes,
198        _ => IsEncrypted::No,
199    };
200    settings
201        .get_default_room_notification_mode(is_encrypted, is_one_to_one)
202        .await
203}
204
205fn is_missing_mention(body: &Option<String>, mode: RoomNotificationMode, client: &Client) -> bool {
206    if let Some(body) = body {
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    }
215    false
216}
217
218fn is_open(locked: &mut ProgramStore, room_id: &RoomId) -> bool {
219    if let Some(draw_curr) = locked.application.draw_curr {
220        let info = locked.application.get_room_info(room_id.to_owned());
221        if let Some(draw_last) = info.draw_last {
222            return draw_last == draw_curr;
223        }
224    }
225    false
226}
227
228fn is_focused(locked: &ProgramStore) -> bool {
229    locked.application.focused
230}
231
232async fn is_visible_room(store: &AsyncProgramStore, room_id: &RoomId) -> bool {
233    let mut locked = store.lock().await;
234
235    is_focused(&locked) && is_open(&mut locked, room_id)
236}
237
238pub async fn parse_full_notification(
239    event: Raw<AnySyncTimelineEvent>,
240    room: MatrixRoom,
241    show_body: bool,
242) -> IambResult<(String, Option<String>, MilliSecondsSinceUnixEpoch)> {
243    let event = event.deserialize().map_err(IambError::from)?;
244
245    let server_ts = event.origin_server_ts();
246
247    let sender_id = event.sender();
248    let sender = room.get_member_no_sync(sender_id).await.map_err(IambError::from)?;
249
250    let sender_name = sender
251        .as_ref()
252        .and_then(|m| m.display_name())
253        .unwrap_or_else(|| sender_id.localpart());
254
255    let summary = if let Some(room_name) = room.cached_display_name() {
256        if room.is_direct().await.map_err(IambError::from)? && sender_name == room_name.to_string()
257        {
258            sender_name.to_string()
259        } else {
260            format!("{sender_name} in {room_name}")
261        }
262    } else {
263        sender_name.to_string()
264    };
265
266    let body = if show_body {
267        event_notification_body(&event, sender_name).map(truncate)
268    } else {
269        None
270    };
271
272    return Ok((summary, body, server_ts));
273}
274
275pub fn event_notification_body(event: &AnySyncTimelineEvent, sender_name: &str) -> Option<String> {
276    let AnySyncTimelineEvent::MessageLike(event) = event else {
277        return None;
278    };
279
280    match event.original_content()? {
281        AnyMessageLikeEventContent::RoomMessage(message) => {
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(body)
310        },
311        AnyMessageLikeEventContent::Sticker(_) => Some(format!("{sender_name} sent a sticker.")),
312        _ => None,
313    }
314}
315
316fn truncate(s: String) -> String {
317    static MAX_LENGTH: usize = 5000;
318    if s.graphemes(true).count() > MAX_LENGTH {
319        let truncated: String = s.graphemes(true).take(MAX_LENGTH).collect();
320        truncated + "..."
321    } else {
322        s
323    }
324}