src/notifications.rs

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