src/notifications.rs

323 lines · 10569 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")]
142async fn send_notification_desktop(
143    summary: &str,
144    body: Option<&str>,
145    room_id: OwnedRoomId,
146    _store: &AsyncProgramStore,
147    sound_hint: Option<&str>,
148) {
149    let mut desktop_notification = notify_rust::Notification::new();
150    desktop_notification
151        .summary(summary)
152        .appname(IAMB_XDG_NAME)
153        .icon(IAMB_XDG_NAME)
154        .action("default", "default");
155
156    if let Some(sound_hint) = sound_hint {
157        desktop_notification.sound_name(sound_hint);
158    }
159
160    #[cfg(all(unix, not(target_os = "macos")))]
161    desktop_notification.urgency(notify_rust::Urgency::Normal);
162
163    if let Some(body) = body {
164        desktop_notification.body(body);
165    }
166
167    match desktop_notification.show() {
168        Err(err) => tracing::error!("Failed to send notification: {err}"),
169        Ok(handle) => {
170            #[cfg(all(unix, not(target_os = "macos")))]
171            _store
172                .lock()
173                .await
174                .application
175                .open_notifications
176                .entry(room_id)
177                .or_default()
178                .push(NotificationHandle(Some(handle)));
179        },
180    }
181}
182
183async fn global_or_room_mode(
184    settings: &NotificationSettings,
185    room: &MatrixRoom,
186) -> RoomNotificationMode {
187    let room_mode = settings.get_user_defined_room_notification_mode(room.room_id()).await;
188    if let Some(mode) = room_mode {
189        return mode;
190    }
191    let is_one_to_one = match room.is_direct().await {
192        Ok(true) => IsOneToOne::Yes,
193        _ => IsOneToOne::No,
194    };
195    let is_encrypted = match room.latest_encryption_state().await {
196        Ok(EncryptionState::Encrypted) => IsEncrypted::Yes,
197        _ => IsEncrypted::No,
198    };
199    settings
200        .get_default_room_notification_mode(is_encrypted, is_one_to_one)
201        .await
202}
203
204fn is_missing_mention(body: &Option<String>, mode: RoomNotificationMode, client: &Client) -> bool {
205    if let Some(body) = body {
206        if mode == RoomNotificationMode::MentionsAndKeywordsOnly {
207            let mentioned = match client.user_id() {
208                Some(user_id) => body.contains(user_id.localpart()),
209                _ => false,
210            };
211            return !mentioned;
212        }
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 body = match message.msgtype {
282                MessageType::Audio(_) => {
283                    format!("{sender_name} sent an audio file.")
284                },
285                MessageType::Emote(content) => content.body,
286                MessageType::File(_) => {
287                    format!("{sender_name} sent a file.")
288                },
289                MessageType::Image(_) => {
290                    format!("{sender_name} sent an image.")
291                },
292                MessageType::Location(_) => {
293                    format!("{sender_name} sent their location.")
294                },
295                MessageType::Notice(content) => content.body,
296                MessageType::ServerNotice(content) => content.body,
297                MessageType::Text(content) => content.body,
298                MessageType::Video(_) => {
299                    format!("{sender_name} sent a video.")
300                },
301                MessageType::VerificationRequest(_) => {
302                    format!("{sender_name} sent a verification request.")
303                },
304                _ => {
305                    format!("[Unknown message type: {:?}]", &message.msgtype)
306                },
307            };
308            Some(body)
309        },
310        AnyMessageLikeEventContent::Sticker(_) => Some(format!("{sender_name} sent a sticker.")),
311        _ => None,
312    }
313}
314
315fn truncate(s: String) -> String {
316    static MAX_LENGTH: usize = 5000;
317    if s.graphemes(true).count() > MAX_LENGTH {
318        let truncated: String = s.graphemes(true).take(MAX_LENGTH).collect();
319        truncated + "..."
320    } else {
321        s
322    }
323}