src/notifications.rs

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