src/notifications.rs
239 lines · 7845 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 .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
130async fn is_open(store: &AsyncProgramStore, room_id: &RoomId) -> bool {
131 let mut locked = store.lock().await;
132 if let Some(draw_curr) = locked.application.draw_curr {
133 let info = locked.application.get_room_info(room_id.to_owned());
134 if let Some(draw_last) = info.draw_last {
135 return draw_last == draw_curr;
136 }
137 }
138 false
139}
140
141pub async fn parse_notification(
142 notification: Notification,
143 room: MatrixRoom,
144 show_body: bool,
145) -> IambResult<(String, Option<String>, MilliSecondsSinceUnixEpoch)> {
146 let event = notification.event.deserialize().map_err(IambError::from)?;
147
148 let server_ts = event.origin_server_ts();
149
150 let sender_id = event.sender();
151 let sender = room.get_member_no_sync(sender_id).await.map_err(IambError::from)?;
152
153 let sender_name = sender
154 .as_ref()
155 .and_then(|m| m.display_name())
156 .unwrap_or_else(|| sender_id.localpart());
157
158 let body = if show_body {
159 event_notification_body(
160 &event,
161 sender_name,
162 room.is_direct().await.map_err(IambError::from)?,
163 )
164 .map(truncate)
165 } else {
166 None
167 };
168
169 return Ok((sender_name.to_string(), body, server_ts));
170}
171
172pub fn event_notification_body(
173 event: &AnySyncTimelineEvent,
174 sender_name: &str,
175 is_direct: bool,
176) -> Option<String> {
177 let AnySyncTimelineEvent::MessageLike(event) = event else {
178 return None;
179 };
180
181 match event.original_content()? {
182 AnyMessageLikeEventContent::RoomMessage(message) => {
183 let body = match message.msgtype {
184 MessageType::Audio(_) => {
185 format!("{sender_name} sent an audio file.")
186 },
187 MessageType::Emote(content) => {
188 let message = &content.body;
189 format!("{sender_name}: {message}")
190 },
191 MessageType::File(_) => {
192 format!("{sender_name} sent a file.")
193 },
194 MessageType::Image(_) => {
195 format!("{sender_name} sent an image.")
196 },
197 MessageType::Location(_) => {
198 format!("{sender_name} sent their location.")
199 },
200 MessageType::Notice(content) => {
201 let message = &content.body;
202 format!("{sender_name}: {message}")
203 },
204 MessageType::ServerNotice(content) => {
205 let message = &content.body;
206 format!("{sender_name}: {message}")
207 },
208 MessageType::Text(content) => {
209 if is_direct {
210 content.body
211 } else {
212 let message = &content.body;
213 format!("{sender_name}: {message}")
214 }
215 },
216 MessageType::Video(_) => {
217 format!("{sender_name} sent a video.")
218 },
219 MessageType::VerificationRequest(_) => {
220 format!("{sender_name} sent a verification request.")
221 },
222 _ => unimplemented!(),
223 };
224 Some(body)
225 },
226 AnyMessageLikeEventContent::Sticker(_) => Some(format!("{sender_name} sent a sticker.")),
227 _ => None,
228 }
229}
230
231fn truncate(s: String) -> String {
232 static MAX_LENGTH: usize = 100;
233 if s.graphemes(true).count() > MAX_LENGTH {
234 let truncated: String = s.graphemes(true).take(MAX_LENGTH).collect();
235 truncated + "..."
236 } else {
237 s
238 }
239}