src/notifications.rs

273 lines · 8939 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        RoomId,
 12    },
 13    Client,
 14};
 15use unicode_segmentation::UnicodeSegmentation;
 16
 17use crate::{
 18    base::{AsyncProgramStore, IambError, IambResult, ProgramStore},
 19    config::{ApplicationSettings, NotifyVia},
 20};
 21
 22const IAMB_XDG_NAME: &str = match option_env!("IAMB_XDG_NAME") {
 23    None => "iamb",
 24    Some(iamb) => iamb,
 25};
 26
 27pub async fn register_notifications(
 28    client: &Client,
 29    settings: &ApplicationSettings,
 30    store: &AsyncProgramStore,
 31) {
 32    if !settings.tunables.notifications.enabled {
 33        return;
 34    }
 35    let notify_via = settings.tunables.notifications.via;
 36    let show_message = settings.tunables.notifications.show_message;
 37    let server_settings = client.notification_settings().await;
 38    let Some(startup_ts) = MilliSecondsSinceUnixEpoch::from_system_time(SystemTime::now()) else {
 39        return;
 40    };
 41
 42    let store = store.clone();
 43    client
 44        .register_notification_handler(move |notification, room: MatrixRoom, client: Client| {
 45            let store = store.clone();
 46            let server_settings = server_settings.clone();
 47            async move {
 48                let mode = global_or_room_mode(&server_settings, &room).await;
 49                if mode == RoomNotificationMode::Mute {
 50                    return;
 51                }
 52
 53                if is_visible_room(&store, room.room_id()).await {
 54                    return;
 55                }
 56
 57                match notification.event {
 58                    RawAnySyncOrStrippedTimelineEvent::Sync(e) => {
 59                        match parse_full_notification(e, room, show_message).await {
 60                            Ok((summary, body, server_ts)) => {
 61                                if server_ts < startup_ts {
 62                                    return;
 63                                }
 64
 65                                if is_missing_mention(&body, mode, &client) {
 66                                    return;
 67                                }
 68
 69                                send_notification(&notify_via, &store, &summary, body.as_deref())
 70                                    .await;
 71                            },
 72                            Err(err) => {
 73                                tracing::error!("Failed to extract notification data: {err}")
 74                            },
 75                        }
 76                    },
 77                    // Stripped events may be dropped silently because they're
 78                    // only relevant if we're not in a room, and we presumably
 79                    // don't want notifications for rooms we're not in.
 80                    RawAnySyncOrStrippedTimelineEvent::Stripped(_) => (),
 81                }
 82            }
 83        })
 84        .await;
 85}
 86
 87async fn send_notification(
 88    via: &NotifyVia,
 89    store: &AsyncProgramStore,
 90    summary: &str,
 91    body: Option<&str>,
 92) {
 93    #[cfg(feature = "desktop")]
 94    if via.desktop {
 95        send_notification_desktop(summary, body);
 96    }
 97    #[cfg(not(feature = "desktop"))]
 98    {
 99        let _ = (summary, body, IAMB_XDG_NAME);
100    }
101
102    if via.bell {
103        send_notification_bell(store).await;
104    }
105}
106
107async fn send_notification_bell(store: &AsyncProgramStore) {
108    let mut locked = store.lock().await;
109    locked.application.ring_bell = true;
110}
111
112#[cfg(feature = "desktop")]
113fn send_notification_desktop(summary: &str, body: Option<&str>) {
114    let mut desktop_notification = notify_rust::Notification::new();
115    desktop_notification
116        .summary(summary)
117        .appname(IAMB_XDG_NAME)
118        .icon(IAMB_XDG_NAME)
119        .action("default", "default");
120
121    #[cfg(all(unix, not(target_os = "macos")))]
122    desktop_notification.urgency(notify_rust::Urgency::Normal);
123
124    if let Some(body) = body {
125        desktop_notification.body(body);
126    }
127
128    if let Err(err) = desktop_notification.show() {
129        tracing::error!("Failed to send notification: {err}")
130    }
131}
132
133async fn global_or_room_mode(
134    settings: &NotificationSettings,
135    room: &MatrixRoom,
136) -> RoomNotificationMode {
137    let room_mode = settings.get_user_defined_room_notification_mode(room.room_id()).await;
138    if let Some(mode) = room_mode {
139        return mode;
140    }
141    let is_one_to_one = match room.is_direct().await {
142        Ok(true) => IsOneToOne::Yes,
143        _ => IsOneToOne::No,
144    };
145    let is_encrypted = match room.is_encrypted().await {
146        Ok(true) => IsEncrypted::Yes,
147        _ => IsEncrypted::No,
148    };
149    settings
150        .get_default_room_notification_mode(is_encrypted, is_one_to_one)
151        .await
152}
153
154fn is_missing_mention(body: &Option<String>, mode: RoomNotificationMode, client: &Client) -> bool {
155    if let Some(body) = body {
156        if mode == RoomNotificationMode::MentionsAndKeywordsOnly {
157            let mentioned = match client.user_id() {
158                Some(user_id) => body.contains(user_id.localpart()),
159                _ => false,
160            };
161            return !mentioned;
162        }
163    }
164    false
165}
166
167fn is_open(locked: &mut ProgramStore, room_id: &RoomId) -> bool {
168    if let Some(draw_curr) = locked.application.draw_curr {
169        let info = locked.application.get_room_info(room_id.to_owned());
170        if let Some(draw_last) = info.draw_last {
171            return draw_last == draw_curr;
172        }
173    }
174    false
175}
176
177fn is_focused(locked: &ProgramStore) -> bool {
178    locked.application.focused
179}
180
181async fn is_visible_room(store: &AsyncProgramStore, room_id: &RoomId) -> bool {
182    let mut locked = store.lock().await;
183
184    is_focused(&locked) && is_open(&mut locked, room_id)
185}
186
187pub async fn parse_full_notification(
188    event: Raw<AnySyncTimelineEvent>,
189    room: MatrixRoom,
190    show_body: bool,
191) -> IambResult<(String, Option<String>, MilliSecondsSinceUnixEpoch)> {
192    let event = event.deserialize().map_err(IambError::from)?;
193
194    let server_ts = event.origin_server_ts();
195
196    let sender_id = event.sender();
197    let sender = room.get_member_no_sync(sender_id).await.map_err(IambError::from)?;
198
199    let sender_name = sender
200        .as_ref()
201        .and_then(|m| m.display_name())
202        .unwrap_or_else(|| sender_id.localpart());
203
204    let summary = if let Some(room_name) = room.cached_display_name() {
205        if room.is_direct().await.map_err(IambError::from)? && sender_name == room_name.to_string()
206        {
207            sender_name.to_string()
208        } else {
209            format!("{sender_name} in {room_name}")
210        }
211    } else {
212        sender_name.to_string()
213    };
214
215    let body = if show_body {
216        event_notification_body(&event, sender_name).map(truncate)
217    } else {
218        None
219    };
220
221    return Ok((summary, body, server_ts));
222}
223
224pub fn event_notification_body(event: &AnySyncTimelineEvent, sender_name: &str) -> Option<String> {
225    let AnySyncTimelineEvent::MessageLike(event) = event else {
226        return None;
227    };
228
229    match event.original_content()? {
230        AnyMessageLikeEventContent::RoomMessage(message) => {
231            let body = match message.msgtype {
232                MessageType::Audio(_) => {
233                    format!("{sender_name} sent an audio file.")
234                },
235                MessageType::Emote(content) => content.body,
236                MessageType::File(_) => {
237                    format!("{sender_name} sent a file.")
238                },
239                MessageType::Image(_) => {
240                    format!("{sender_name} sent an image.")
241                },
242                MessageType::Location(_) => {
243                    format!("{sender_name} sent their location.")
244                },
245                MessageType::Notice(content) => content.body,
246                MessageType::ServerNotice(content) => content.body,
247                MessageType::Text(content) => content.body,
248                MessageType::Video(_) => {
249                    format!("{sender_name} sent a video.")
250                },
251                MessageType::VerificationRequest(_) => {
252                    format!("{sender_name} sent a verification request.")
253                },
254                _ => {
255                    format!("[Unknown message type: {:?}]", &message.msgtype)
256                },
257            };
258            Some(body)
259        },
260        AnyMessageLikeEventContent::Sticker(_) => Some(format!("{sender_name} sent a sticker.")),
261        _ => None,
262    }
263}
264
265fn truncate(s: String) -> String {
266    static MAX_LENGTH: usize = 5000;
267    if s.graphemes(true).count() > MAX_LENGTH {
268        let truncated: String = s.graphemes(true).take(MAX_LENGTH).collect();
269        truncated + "..."
270    } else {
271        s
272    }
273}