Commit 99996e275b

99996e275b2dc75d66972816b5be12f5ecacf141

parent: db9cb92737

Unregistered key

Ulyssa <git@ulyssa.dev> · 2024-03-24 17:19 UTC
committer: <noreply@github.com>

Support notifications via terminal bell (#227)

Co-authored-by: Benjamin Grosse <ste3ls@gmail.com>

Layout: unified · split

docs/iamb.5.md +3 −2
@@ -90,9 +90,10 @@ overridden as described in *PROFILES*.
9090> Defines whether or not the message body is colored like the username.
9191
9292**notifications** (type: notifications object)
93> Configures push-notifications, which are delivered as desktop
94> notifications if available.
93> Configures push-notifications.
9594> *enabled* `true` to enable the feature, defaults to `false`.
95> *via* `"desktop"` to use desktop mechanism (default), or `"bell"` to use
96> terminal bell.
9697> *show_message* to show the message in the desktop notification. Defaults
9798> to `true`. Messages are truncated beyond a small length.
9899> The notification _rules_ are stored server side, loaded once at startup,
src/base.rs +4
@@ -1273,6 +1273,9 @@ pub struct ChatStore {
12731273
12741274 /// Last draw time, used to match with RoomInfo's draw_last.
12751275 pub draw_curr: Option<Instant>,
1276
1277 /// Whether to ring the terminal bell on the next redraw.
1278 pub ring_bell: bool,
12761279}
12771280
12781281impl ChatStore {
@@ -1294,6 +1297,7 @@ impl ChatStore {
12941297 need_load: Default::default(),
12951298 sync_info: Default::default(),
12961299 draw_curr: None,
1300 ring_bell: false,
12971301 }
12981302 }
12991303
src/config.rs +19 −1
@@ -86,6 +86,10 @@ fn is_profile_char(c: char) -> bool {
8686 c.is_ascii_alphanumeric() || c == '.' || c == '-'
8787}
8888
89fn default_true() -> bool {
90 true
91}
92
8993fn validate_profile_name(name: &str) -> bool {
9094 if name.is_empty() {
9195 return false;
@@ -391,10 +395,24 @@ pub enum UserDisplayStyle {
391395 DisplayName,
392396}
393397
398#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
399#[serde(rename_all = "lowercase")]
400pub enum NotifyVia {
401 /// Deliver notifications via terminal bell.
402 Bell,
403 /// Deliver notifications via desktop mechanism.
404 #[default]
405 Desktop,
406}
407
394408#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
395409pub struct Notifications {
410 #[serde(default)]
396411 pub enabled: bool,
397 pub show_message: Option<bool>,
412 #[serde(default)]
413 pub via: NotifyVia,
414 #[serde(default = "default_true")]
415 pub show_message: bool,
398416}
399417
400418#[derive(Clone)]
src/main.rs +5 −1
@@ -19,7 +19,7 @@ use std::collections::VecDeque;
1919use std::convert::TryFrom;
2020use std::fmt::Display;
2121use std::fs::{create_dir_all, File};
22use std::io::{stdout, BufWriter, Stdout};
22use std::io::{stdout, BufWriter, Stdout, Write};
2323use std::ops::DerefMut;
2424use std::process;
2525use std::sync::atomic::{AtomicUsize, Ordering};
@@ -293,6 +293,10 @@ impl Application {
293293 let sstate = &mut self.screen;
294294 let term = &mut self.terminal;
295295
296 if store.application.ring_bell {
297 store.application.ring_bell = term.backend_mut().write_all(&[7]).is_err();
298 }
299
296300 if full {
297301 term.clear()?;
298302 }
src/notifications.rs +41 −22
@@ -15,7 +15,7 @@ use unicode_segmentation::UnicodeSegmentation;
1515
1616use crate::{
1717 base::{AsyncProgramStore, IambError, IambResult},
18 config::ApplicationSettings,
18 config::{ApplicationSettings, NotifyVia},
1919};
2020
2121pub async fn register_notifications(
@@ -26,6 +26,7 @@ pub async fn register_notifications(
2626 if !settings.tunables.notifications.enabled {
2727 return;
2828 }
29 let notify_via = settings.tunables.notifications.via;
2930 let show_message = settings.tunables.notifications.show_message;
3031 let server_settings = client.notification_settings().await;
3132 let Some(startup_ts) = MilliSecondsSinceUnixEpoch::from_system_time(SystemTime::now()) else {
@@ -47,29 +48,19 @@ pub async fn register_notifications(
4748 return;
4849 }
4950
50 match parse_notification(notification, room).await {
51 match parse_notification(notification, room, show_message).await {
5152 Ok((summary, body, server_ts)) => {
5253 if server_ts < startup_ts {
5354 return;
5455 }
5556
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
6357 if is_missing_mention(&body, mode, &client) {
6458 return;
6559 }
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}")
60
61 match notify_via {
62 NotifyVia::Desktop => send_notification_desktop(summary, body),
63 NotifyVia::Bell => send_notification_bell(&store).await,
7364 }
7465 },
7566 Err(err) => {
@@ -81,6 +72,28 @@ pub async fn register_notifications(
8172 .await;
8273}
8374
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
8497async fn global_or_room_mode(
8598 settings: &NotificationSettings,
8699 room: &MatrixRoom,
@@ -129,6 +142,7 @@ async fn is_open(store: &AsyncProgramStore, room_id: &RoomId) -> bool {
129142pub async fn parse_notification(
130143 notification: Notification,
131144 room: MatrixRoom,
145 show_body: bool,
132146) -> IambResult<(String, Option<String>, MilliSecondsSinceUnixEpoch)> {
133147 let event = notification.event.deserialize().map_err(IambError::from)?;
134148
@@ -142,12 +156,17 @@ pub async fn parse_notification(
142156 .and_then(|m| m.display_name())
143157 .unwrap_or_else(|| sender_id.localpart());
144158
145 let body = event_notification_body(
146 &event,
147 sender_name,
148 room.is_direct().await.map_err(IambError::from)?,
149 )
150 .map(truncate);
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
151170 return Ok((sender_name.to_string(), body, server_ts));
152171}
153172
src/tests.rs +6 −1
@@ -28,6 +28,7 @@ use crate::{
2828 ApplicationSettings,
2929 DirectoryValues,
3030 Notifications,
31 NotifyVia,
3132 ProfileConfig,
3233 SortOverrides,
3334 TunableValues,
@@ -187,7 +188,11 @@ pub fn mock_tunables() -> TunableValues {
187188 open_command: None,
188189 username_display: UserDisplayStyle::Username,
189190 message_user_color: false,
190 notifications: Notifications { enabled: false, show_message: None },
191 notifications: Notifications {
192 enabled: false,
193 via: NotifyVia::Desktop,
194 show_message: true,
195 },
191196 image_preview: None,
192197 user_gutter_width: 30,
193198 }