src/notifications.rs

264 lines · 8551 bytes

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