Skip to content

Commit d933569

Browse files
committed
various small cleanups
1 parent 04c3f86 commit d933569

File tree

6 files changed

+54
-77
lines changed

6 files changed

+54
-77
lines changed

ntfy-daemon/src/message_repo/mod.rs

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,9 @@ impl Db {
2626
Ok(this)
2727
}
2828
fn migrate(&mut self) -> Result<()> {
29-
{
30-
self.conn
31-
.borrow()
32-
.execute_batch(include_str!("./migrations/00.sql"))?
33-
};
29+
self.conn
30+
.borrow()
31+
.execute_batch(include_str!("./migrations/00.sql"))?;
3432
Ok(())
3533
}
3634
fn get_or_insert_server(&mut self, server: &str) -> Result<i64> {
@@ -90,9 +88,9 @@ impl Db {
9088
",
9189
)?;
9290
let msgs: Result<Vec<String>, _> = stmt
93-
.query_map(params![server, topic, since], |row| Ok(row.get(0)?))?
91+
.query_map(params![server, topic, since], |row| row.get(0))?
9492
.collect();
95-
Ok(msgs?)
93+
msgs
9694
}
9795
pub fn insert_subscription(&mut self, sub: models::Subscription) -> Result<(), Error> {
9896
let server_id = self.get_or_insert_server(&sub.server)?;
@@ -116,7 +114,7 @@ impl Db {
116114
WHERE server = ?1 AND topic = ?2",
117115
params![server_id, topic],
118116
)?;
119-
if res <= 0 {
117+
if res == 0 {
120118
return Err(Error::SubscriptionNotFound("removing subscription".into()));
121119
}
122120
Ok(())
@@ -162,7 +160,7 @@ impl Db {
162160
sub.topic,
163161
],
164162
)?;
165-
if res <= 0 {
163+
if res == 0 {
166164
return Err(Error::SubscriptionNotFound("updating subscription".into()));
167165
}
168166
info!(info = ?sub, "stored subscription info");
@@ -184,7 +182,7 @@ impl Db {
184182
",
185183
params![server_id, topic, value],
186184
)?;
187-
if res <= 0 {
185+
if res == 0 {
188186
return Err(Error::SubscriptionNotFound("updating read_until".into()));
189187
}
190188
Ok(())
@@ -198,7 +196,7 @@ impl Db {
198196
",
199197
params![server_id, topic],
200198
)?;
201-
if res <= 0 {
199+
if res == 0 {
202200
return Err(Error::SubscriptionNotFound("deleting messages".into()));
203201
}
204202
Ok(())

ntfy-daemon/src/models.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ impl Subscription {
148148
let mut url = url::Url::parse(server)?;
149149
url.path_segments_mut()
150150
.map_err(|_| url::ParseError::RelativeUrlWithCannotBeABaseBase)?
151-
.push(&topic)
151+
.push(topic)
152152
.push("json");
153153
url.query_pairs_mut()
154154
.append_pair("since", &since.to_string());
@@ -162,7 +162,7 @@ impl Subscription {
162162
if let Err(e) = Self::build_url(&self.server, &self.topic, 0) {
163163
errs.push(e);
164164
};
165-
if errs.len() > 0 {
165+
if !errs.is_empty() {
166166
return Err(errs);
167167
}
168168
Ok(self)

ntfy-daemon/src/system_client.rs

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ impl output_channel::Server for NotifyForwarder {
6363
let already_stored: bool = {
6464
// If this fails parsing, the message is not valid at all.
6565
// The server is probably misbehaving.
66-
let min_message: MinMessage = pry!(serde_json::from_str(&message)
66+
let min_message: MinMessage = pry!(serde_json::from_str(message)
6767
.map_err(|e| Error::InvalidMinMessage(message.to_string(), e)));
6868
let model = self.model.borrow();
6969
match self.env.db.insert_message(&model.server, message) {
@@ -83,20 +83,15 @@ impl output_channel::Server for NotifyForwarder {
8383
// Show notification
8484
// Our priority is to show notifications. If anything fails, panic.
8585
if !{ self.model.borrow().muted } {
86-
let msg: Message = pry!(serde_json::from_str(&message)
86+
let msg: Message = pry!(serde_json::from_str(message)
8787
.map_err(|e| Error::InvalidMessage(message.to_string(), e)));
8888
let np = self.env.proxy.clone();
8989

90-
let title = { msg.notification_title(&*self.model.borrow()) };
90+
let title = { msg.notification_title(&self.model.borrow()) };
9191

9292
let n = models::Notification {
93-
title: title.to_string(),
94-
body: msg
95-
.display_message()
96-
.as_ref()
97-
.map(|x| x.as_str())
98-
.unwrap_or("")
99-
.to_string(),
93+
title,
94+
body: msg.display_message().as_deref().unwrap_or("").to_string(),
10095
actions: msg.actions,
10196
};
10297

@@ -380,7 +375,7 @@ impl SystemNotifier {
380375
pub fn watch_subscribed(&mut self) -> Promise<(), capnp::Error> {
381376
let f: Vec<_> = pry!(self.env.db.list_subscriptions())
382377
.into_iter()
383-
.map(|m| self.watch(m.clone()))
378+
.map(|m| self.watch(m))
384379
.collect();
385380
Promise::from_future(async move {
386381
join_all(f.into_iter().map(|x| async move {
@@ -434,7 +429,7 @@ impl system_notifier::Server for SystemNotifier {
434429
pry!(self
435430
.env
436431
.db
437-
.remove_subscription(&server, &topic)
432+
.remove_subscription(server, topic)
438433
.map_err(|e| capnp::Error::failed(e.to_string())));
439434
info!(server, topic, "Unsubscribed");
440435
}

src/subscription.rs

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use glib::Properties;
99
use gtk::{gio, glib};
1010
use ntfy_daemon::models;
1111
use ntfy_daemon::ntfy_capnp::{output_channel, subscription, watch_handle, Status};
12-
use tracing::{debug, debug_span, error, instrument};
12+
use tracing::{debug, error, instrument};
1313

1414
struct TopicWatcher {
1515
sub: glib::WeakRef<Subscription>,
@@ -217,8 +217,7 @@ impl Subscription {
217217
val.set_display_name(&*imp.display_name.borrow());
218218
val.set_read_until(imp.read_until.get());
219219
Promise::from_future(async move {
220-
let _span = debug_span!("send_updated_info").entered();
221-
debug!("sending");
220+
debug!("sending update_info");
222221
req.send().promise.await?;
223222
Ok(())
224223
})
@@ -233,12 +232,8 @@ impl Subscription {
233232
}
234233
fn update_unread_count(&self) {
235234
let imp = self.imp();
236-
if let Some(last) = Self::last_message(&imp.messages) {
237-
if last.time > imp.read_until.get() {
238-
imp.unread_count.set(1);
239-
} else {
240-
imp.unread_count.set(0);
241-
}
235+
if Self::last_message(&imp.messages).map(|last| last.time) > Some(imp.read_until.get()) {
236+
imp.unread_count.set(1);
242237
} else {
243238
imp.unread_count.set(0);
244239
}
@@ -256,13 +251,12 @@ impl Subscription {
256251
}
257252
pub fn flag_all_as_read(&self) -> Promise<(), capnp::Error> {
258253
let imp = self.imp();
259-
let Some(last) = Self::last_message(&imp.messages) else {
254+
let Some(value) = Self::last_message(&imp.messages)
255+
.map(|last| last.time)
256+
.filter(|time| *time > self.imp().read_until.get())
257+
else {
260258
return Promise::ok(());
261259
};
262-
let value = last.time;
263-
if self.imp().read_until.get() == value {
264-
return Promise::ok(());
265-
}
266260

267261
let this = self.clone();
268262
Promise::from_future(async move {
@@ -276,14 +270,15 @@ impl Subscription {
276270
}
277271
pub fn publish_msg(&self, mut msg: models::Message) -> Promise<(), capnp::Error> {
278272
let imp = self.imp();
273+
let json = {
274+
msg.topic = self.topic();
275+
serde_json::to_string(&msg).map_err(|e| capnp::Error::failed(e.to_string()))
276+
};
279277
let mut req = imp.client.get().unwrap().publish_request();
280-
msg.topic = self.topic();
281-
let json = serde_json::to_string(&msg).map_err(|e| capnp::Error::failed(e.to_string()));
282278
req.get().set_message(&pry!(json));
283279

284280
Promise::from_future(async move {
285-
let _span = debug_span!("publish").entered();
286-
debug!("sending");
281+
debug!("sending publish");
287282
req.send().promise.await?;
288283
Ok(())
289284
})
@@ -294,8 +289,7 @@ impl Subscription {
294289
let req = imp.client.get().unwrap().clear_notifications_request();
295290
let this = self.clone();
296291
Promise::from_future(async move {
297-
let _span = debug_span!("clear_notifications").entered();
298-
debug!("sending");
292+
debug!("sending clear_notifications");
299293
req.send().promise.await?;
300294
this.imp().messages.remove_all();
301295
Ok(())

src/widgets/message_row.rs

Lines changed: 20 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -145,39 +145,29 @@ impl MessageRow {
145145
self.attach(&tags, 0, row, 3, 1);
146146
}
147147
}
148+
fn fetch_image_bytes(url: &str) -> anyhow::Result<Vec<u8>> {
149+
let path = glib::user_cache_dir().join("com.ranfdev.Notify").join(&url);
150+
let bytes = if path.exists() {
151+
std::fs::read(&path)?
152+
} else {
153+
let mut bytes = vec![];
154+
ureq::get(&url)
155+
.call()?
156+
.into_reader()
157+
.take(5 * 1_000_000) // 5 MB
158+
.read_to_end(&mut bytes)?;
159+
bytes
160+
};
161+
Ok(bytes)
162+
}
148163
fn build_image(&self, url: String) -> gtk::Picture {
149164
let (tx, rx) = glib::MainContext::channel(Default::default());
150165
gio::spawn_blocking(move || {
151-
let path = glib::user_cache_dir().join("com.ranfdev.Notify").join(&url);
152-
let bytes = if path.exists() {
153-
match std::fs::read(&path) {
154-
Ok(v) => v,
155-
Err(e) => {
156-
error!(error = %e, path = %path.display(), "reading image from disk");
157-
return glib::ControlFlow::Break;
158-
}
159-
}
160-
} else {
161-
let res = match ureq::get(&url).call() {
162-
Ok(res) => res,
163-
Err(e) => {
164-
error!(error = %e, "fetching image");
165-
return glib::ControlFlow::Break;
166-
}
167-
};
168-
let mut bytes = vec![];
169-
if let Err(e) = res
170-
.into_reader()
171-
.take(5 * 1_000_000) // 5 MB
172-
.read_to_end(&mut bytes)
173-
{
174-
error!(error = %e, "reading image data");
175-
return glib::ControlFlow::Break;
176-
}
177-
bytes
178-
};
179-
180-
tx.send(glib::Bytes::from_owned(bytes)).unwrap();
166+
if let Err(e) =
167+
Self::fetch_image_bytes(&url).map(|bytes| tx.send(glib::Bytes::from_owned(bytes)))
168+
{
169+
error!(error = %e)
170+
}
181171
glib::ControlFlow::Break
182172
});
183173
let picture = gtk::Picture::new();

src/widgets/window.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,7 @@ impl NotifyWindow {
346346
.bind_model(Some(&imp.subscription_list_model), |obj| {
347347
let sub = obj.downcast_ref::<Subscription>().unwrap();
348348

349-
Self::build_subscription_ui(&sub).upcast()
349+
Self::build_subscription_row(&sub).upcast()
350350
});
351351

352352
let this = self.clone();
@@ -445,7 +445,7 @@ impl NotifyWindow {
445445
chip
446446
}
447447

448-
fn build_subscription_ui(sub: &Subscription) -> impl glib::IsA<gtk::Widget> {
448+
fn build_subscription_row(sub: &Subscription) -> impl glib::IsA<gtk::Widget> {
449449
let b = gtk::Box::builder().spacing(4).build();
450450

451451
let label = gtk::Label::builder()

0 commit comments

Comments
 (0)