src/notifications.rs

290 lines · 9365 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    if let Some(body) = body {
122        desktop_notification.body(body);
123    }
124
125    if let Err(err) = desktop_notification.show() {
126        tracing::error!("Failed to send notification: {err}")
127    }
128}
129
130async fn global_or_room_mode(
131    settings: &NotificationSettings,
132    room: &MatrixRoom,
133) -> RoomNotificationMode {
134    let room_mode = settings.get_user_defined_room_notification_mode(room.room_id()).await;
135    if let Some(mode) = room_mode {
136        return mode;
137    }
138    let is_one_to_one = match room.is_direct().await {
139        Ok(true) => IsOneToOne::Yes,
140        _ => IsOneToOne::No,
141    };
142    let is_encrypted = match room.is_encrypted().await {
143        Ok(true) => IsEncrypted::Yes,
144        _ => IsEncrypted::No,
145    };
146    settings
147        .get_default_room_notification_mode(is_encrypted, is_one_to_one)
148        .await
149}
150
151fn is_missing_mention(body: &Option<String>, mode: RoomNotificationMode, client: &Client) -> bool {
152    if let Some(body) = body {
153        if mode == RoomNotificationMode::MentionsAndKeywordsOnly {
154            let mentioned = match client.user_id() {
155                Some(user_id) => body.contains(user_id.localpart()),
156                _ => false,
157            };
158            return !mentioned;
159        }
160    }
161    false
162}
163
164fn is_open(locked: &mut ProgramStore, room_id: &RoomId) -> bool {
165    if let Some(draw_curr) = locked.application.draw_curr {
166        let info = locked.application.get_room_info(room_id.to_owned());
167        if let Some(draw_last) = info.draw_last {
168            return draw_last == draw_curr;
169        }
170    }
171    false
172}
173
174fn is_focused(locked: &ProgramStore) -> bool {
175    locked.application.focused
176}
177
178async fn is_visible_room(store: &AsyncProgramStore, room_id: &RoomId) -> bool {
179    let mut locked = store.lock().await;
180
181    is_focused(&locked) && is_open(&mut locked, room_id)
182}
183
184pub async fn parse_full_notification(
185    event: Raw<AnySyncTimelineEvent>,
186    room: MatrixRoom,
187    show_body: bool,
188) -> IambResult<(String, Option<String>, MilliSecondsSinceUnixEpoch)> {
189    let event = event.deserialize().map_err(IambError::from)?;
190
191    let server_ts = event.origin_server_ts();
192
193    let sender_id = event.sender();
194    let sender = room.get_member_no_sync(sender_id).await.map_err(IambError::from)?;
195
196    let sender_name = sender
197        .as_ref()
198        .and_then(|m| m.display_name())
199        .unwrap_or_else(|| sender_id.localpart());
200
201    let summary = if let Some(room_name) = room.cached_display_name() {
202        format!("{sender_name} in {room_name}")
203    } else {
204        sender_name.to_string()
205    };
206
207    let body = if show_body {
208        event_notification_body(
209            &event,
210            sender_name,
211            room.is_direct().await.map_err(IambError::from)?,
212        )
213        .map(truncate)
214    } else {
215        None
216    };
217
218    return Ok((summary, body, server_ts));
219}
220
221pub fn event_notification_body(
222    event: &AnySyncTimelineEvent,
223    sender_name: &str,
224    is_direct: bool,
225) -> Option<String> {
226    let AnySyncTimelineEvent::MessageLike(event) = event else {
227        return None;
228    };
229
230    match event.original_content()? {
231        AnyMessageLikeEventContent::RoomMessage(message) => {
232            let body = match message.msgtype {
233                MessageType::Audio(_) => {
234                    format!("{sender_name} sent an audio file.")
235                },
236                MessageType::Emote(content) => {
237                    let message = &content.body;
238                    format!("{sender_name}: {message}")
239                },
240                MessageType::File(_) => {
241                    format!("{sender_name} sent a file.")
242                },
243                MessageType::Image(_) => {
244                    format!("{sender_name} sent an image.")
245                },
246                MessageType::Location(_) => {
247                    format!("{sender_name} sent their location.")
248                },
249                MessageType::Notice(content) => {
250                    let message = &content.body;
251                    format!("{sender_name}: {message}")
252                },
253                MessageType::ServerNotice(content) => {
254                    let message = &content.body;
255                    format!("{sender_name}: {message}")
256                },
257                MessageType::Text(content) => {
258                    if is_direct {
259                        content.body
260                    } else {
261                        let message = &content.body;
262                        format!("{sender_name}: {message}")
263                    }
264                },
265                MessageType::Video(_) => {
266                    format!("{sender_name} sent a video.")
267                },
268                MessageType::VerificationRequest(_) => {
269                    format!("{sender_name} sent a verification request.")
270                },
271                _ => {
272                    format!("[Unknown message type: {:?}]", &message.msgtype)
273                },
274            };
275            Some(body)
276        },
277        AnyMessageLikeEventContent::Sticker(_) => Some(format!("{sender_name} sent a sticker.")),
278        _ => None,
279    }
280}
281
282fn truncate(s: String) -> String {
283    static MAX_LENGTH: usize = 100;
284    if s.graphemes(true).count() > MAX_LENGTH {
285        let truncated: String = s.graphemes(true).take(MAX_LENGTH).collect();
286        truncated + "..."
287    } else {
288        s
289    }
290}