src/notifications.rs

240 lines · 7904 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},
 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_open(&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        .timeout(notify_rust::Timeout::Milliseconds(3000))
 86        .action("default", "default");
 87
 88    if let Some(body) = body {
 89        desktop_notification.body(&body);
 90    }
 91
 92    if let Err(err) = desktop_notification.show() {
 93        tracing::error!("Failed to send notification: {err}")
 94    }
 95}
 96
 97async fn global_or_room_mode(
 98    settings: &NotificationSettings,
 99    room: &MatrixRoom,
100) -> RoomNotificationMode {
101    let room_mode = settings.get_user_defined_room_notification_mode(room.room_id()).await;
102    if let Some(mode) = room_mode {
103        return mode;
104    }
105    let is_one_to_one = match room.is_direct().await {
106        Ok(true) => IsOneToOne::Yes,
107        _ => IsOneToOne::No,
108    };
109    let is_encrypted = match room.is_encrypted().await {
110        Ok(true) => IsEncrypted::Yes,
111        _ => IsEncrypted::No,
112    };
113    settings
114        .get_default_room_notification_mode(is_encrypted, is_one_to_one)
115        .await
116}
117
118fn is_missing_mention(body: &Option<String>, mode: RoomNotificationMode, client: &Client) -> bool {
119    if let Some(body) = body {
120        if mode == RoomNotificationMode::MentionsAndKeywordsOnly {
121            let mentioned = match client.user_id() {
122                Some(user_id) => body.contains(user_id.localpart()),
123                _ => false,
124            };
125            return !mentioned;
126        }
127    }
128    false
129}
130
131async fn is_open(store: &AsyncProgramStore, room_id: &RoomId) -> bool {
132    let mut locked = store.lock().await;
133    if let Some(draw_curr) = locked.application.draw_curr {
134        let info = locked.application.get_room_info(room_id.to_owned());
135        if let Some(draw_last) = info.draw_last {
136            return draw_last == draw_curr;
137        }
138    }
139    false
140}
141
142pub async fn parse_notification(
143    notification: Notification,
144    room: MatrixRoom,
145    show_body: bool,
146) -> IambResult<(String, Option<String>, MilliSecondsSinceUnixEpoch)> {
147    let event = notification.event.deserialize().map_err(IambError::from)?;
148
149    let server_ts = event.origin_server_ts();
150
151    let sender_id = event.sender();
152    let sender = room.get_member_no_sync(sender_id).await.map_err(IambError::from)?;
153
154    let sender_name = sender
155        .as_ref()
156        .and_then(|m| m.display_name())
157        .unwrap_or_else(|| sender_id.localpart());
158
159    let body = if show_body {
160        event_notification_body(
161            &event,
162            sender_name,
163            room.is_direct().await.map_err(IambError::from)?,
164        )
165        .map(truncate)
166    } else {
167        None
168    };
169
170    return Ok((sender_name.to_string(), body, server_ts));
171}
172
173pub fn event_notification_body(
174    event: &AnySyncTimelineEvent,
175    sender_name: &str,
176    is_direct: bool,
177) -> Option<String> {
178    let AnySyncTimelineEvent::MessageLike(event) = event else {
179        return None;
180    };
181
182    match event.original_content()? {
183        AnyMessageLikeEventContent::RoomMessage(message) => {
184            let body = match message.msgtype {
185                MessageType::Audio(_) => {
186                    format!("{sender_name} sent an audio file.")
187                },
188                MessageType::Emote(content) => {
189                    let message = &content.body;
190                    format!("{sender_name}: {message}")
191                },
192                MessageType::File(_) => {
193                    format!("{sender_name} sent a file.")
194                },
195                MessageType::Image(_) => {
196                    format!("{sender_name} sent an image.")
197                },
198                MessageType::Location(_) => {
199                    format!("{sender_name} sent their location.")
200                },
201                MessageType::Notice(content) => {
202                    let message = &content.body;
203                    format!("{sender_name}: {message}")
204                },
205                MessageType::ServerNotice(content) => {
206                    let message = &content.body;
207                    format!("{sender_name}: {message}")
208                },
209                MessageType::Text(content) => {
210                    if is_direct {
211                        content.body
212                    } else {
213                        let message = &content.body;
214                        format!("{sender_name}: {message}")
215                    }
216                },
217                MessageType::Video(_) => {
218                    format!("{sender_name} sent a video.")
219                },
220                MessageType::VerificationRequest(_) => {
221                    format!("{sender_name} sent a verification request.")
222                },
223                _ => unimplemented!(),
224            };
225            Some(body)
226        },
227        AnyMessageLikeEventContent::Sticker(_) => Some(format!("{sender_name} sent a sticker.")),
228        _ => None,
229    }
230}
231
232fn truncate(s: String) -> String {
233    static MAX_LENGTH: usize = 100;
234    if s.graphemes(true).count() > MAX_LENGTH {
235        let truncated: String = s.graphemes(true).take(MAX_LENGTH).collect();
236        truncated + "..."
237    } else {
238        s
239    }
240}