src/notifications.rs

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