Medlar/crates/app/src/notify.rs

238 lines
9.1 KiB
Rust

//! Desktop notifications (org.freedesktop.Notifications): done, failed, needs a login, all done. Actions come back as
//! `Do`. A batch of many of one kind becomes one summary; quiet hours send nothing.
use crate::shell::Do;
use eframe::egui::Context;
use medlar_core::model::{ErrorKind, State, TaskId};
use medlar_core::settings::Settings;
use medlar_core::snapshot::Snapshot;
use medlar_core::tr;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use zbus::blocking::Connection;
use zbus::zvariant::Value;
#[derive(Debug, Clone, PartialEq)]
pub enum Event {
Done { id: TaskId, name: String, file: PathBuf },
Failed { id: TaskId, name: String, why: String },
Login { id: TaskId, name: String, url: String },
AllDone,
}
/// Sees what changed between snapshots. The first one only sets the baseline.
#[derive(Default)]
pub struct Watcher {
seen: HashMap<TaskId, State>,
started: bool,
busy: bool,
finished: bool,
}
fn working(s: State) -> bool {
matches!(s, State::Queued | State::Waiting | State::Running | State::Checking | State::Finishing)
}
impl Watcher {
pub fn feed(&mut self, shot: &Snapshot) -> Vec<Event> {
let mut out = vec![];
let (mut busy, mut paused) = (false, false);
for v in shot.iter() {
let (id, state) = (v.id(), v.state());
busy |= working(state);
let before = self.seen.insert(id, state);
let Some(before) = before.filter(|_| self.started) else { continue };
if before == state || !working(before) && before != State::Paused {
continue;
}
let t = &v.task;
match state {
State::Done => {
self.finished = true;
out.push(Event::Done { id, name: t.name.clone(), file: t.folder.join(&t.name) });
}
State::Failed => match &t.error {
Some(e) if e.kind == Some(ErrorKind::Login) => out.push(Event::Login { id, name: t.name.clone(), url: t.url.clone() }),
e => out.push(Event::Failed { id, name: t.name.clone(), why: e.as_ref().map(|e| e.detail.clone()).unwrap_or_default() }),
},
State::Paused => paused = true,
_ => {}
}
}
if self.started && self.busy && !busy && self.finished {
self.finished = false;
// The last one being paused is not an end.
if !paused {
out.push(Event::AllDone);
}
}
self.busy = busy;
self.started = true;
out
}
}
/// Minutes since midnight in the quiet span, which may wrap past midnight. Equal ends mean no span.
pub fn quiet_at(from: u32, to: u32, now: u32) -> bool {
match from.cmp(&to) {
std::cmp::Ordering::Equal => false,
std::cmp::Ordering::Less => (from..to).contains(&now),
std::cmp::Ordering::Greater => now >= from || now < to,
}
}
pub fn quiet_now(s: &Settings) -> bool {
use chrono::Timelike;
let now = chrono::Local::now();
s.quiet && quiet_at(s.quiet_from, s.quiet_to, now.hour() * 60 + now.minute())
}
/// One notification to show.
#[derive(Debug, Clone, PartialEq)]
pub struct Note {
pub summary: String,
pub body: String,
/// `transfer.complete`, `transfer.error` or `network`.
pub category: &'static str,
/// (key, label, what it does).
pub actions: Vec<(&'static str, String, Do)>,
}
/// More than this many of one kind in one batch are a summary.
const MOST: usize = 3;
pub fn notes(events: &[Event]) -> Vec<Note> {
let done: Vec<_> = events.iter().filter(|e| matches!(e, Event::Done { .. })).collect();
let failed: Vec<_> = events.iter().filter(|e| matches!(e, Event::Failed { .. })).collect();
let mut out = vec![];
if done.len() > MOST {
out.push(Note { summary: tr!("notify.many_done", n = done.len()), body: String::new(), category: "transfer.complete", actions: vec![("show", tr!("notify.show"), Do::Show)] });
}
if failed.len() > MOST {
out.push(Note { summary: tr!("notify.many_failed", n = failed.len()), body: String::new(), category: "transfer.error", actions: vec![("show", tr!("notify.show"), Do::Show)] });
}
for e in events {
match e {
Event::Done { name, file, .. } if done.len() <= MOST => out.push(Note {
summary: tr!("notify.done"),
body: name.clone(),
category: "transfer.complete",
actions: vec![("open", tr!("notify.open"), Do::Open(file.clone())), ("folder", tr!("notify.folder"), Do::Folder(file.clone()))],
}),
Event::Failed { id, name, why } if failed.len() <= MOST => out.push(Note {
summary: tr!("notify.failed"),
body: if why.is_empty() { name.clone() } else { format!("{name}\n{why}") },
category: "transfer.error",
actions: vec![("retry", tr!("notify.retry"), Do::Retry(*id))],
}),
Event::Login { id, name, url } => out.push(Note {
summary: tr!("notify.login"),
body: name.clone(),
category: "network",
actions: vec![("continue", tr!("notify.continue"), Do::SignIn(url.clone(), *id))],
}),
Event::AllDone => out.push(Note { summary: tr!("notify.all_done"), body: String::new(), category: "transfer.complete", actions: vec![("show", tr!("notify.show"), Do::Show)] }),
_ => {}
}
}
out
}
type Shown = Arc<Mutex<HashMap<u32, Vec<(&'static str, Do)>>>>;
/// Sends notes through a bus connection and turns clicks on their buttons into `Do`.
pub struct Notifier {
conn: Connection,
shown: Shown,
}
impl Notifier {
pub fn start(conn: Connection, tx: Sender<Do>, ctx: Context) -> Notifier {
let shown: Shown = Arc::default();
let (listen, map) = (conn.clone(), shown.clone());
std::thread::spawn(move || listen_for_actions(listen, map, tx, ctx));
Notifier { conn, shown }
}
/// Shows what the events call for, unless it is quiet. Never blocks the window: it is sent from a thread.
pub fn send(&self, events: &[Event], settings: &Settings) {
if events.is_empty() || quiet_now(settings) {
return;
}
let list = notes(events);
let (conn, shown) = (self.conn.clone(), self.shown.clone());
std::thread::spawn(move || {
for note in list {
match show(&conn, &note) {
Ok(id) => {
shown.lock().unwrap_or_else(|e| e.into_inner()).insert(id, note.actions.into_iter().map(|(k, _, d)| (k, d)).collect());
}
Err(e) => log::debug!("notification: {e}"),
}
}
});
}
}
fn show(conn: &Connection, note: &Note) -> zbus::Result<u32> {
let mut actions: Vec<&str> = vec![];
for (key, label, _) in &note.actions {
actions.extend([*key, label.as_str()]);
}
let mut hints: HashMap<&str, Value> = HashMap::new();
hints.insert("desktop-entry", Value::from("medlar"));
hints.insert("category", Value::from(note.category));
let reply = conn.call_method(
Some("org.freedesktop.Notifications"),
"/org/freedesktop/Notifications",
Some("org.freedesktop.Notifications"),
"Notify",
&("Medlar", 0u32, "medlar", note.summary.as_str(), note.body.as_str(), actions, hints, -1i32),
)?;
reply.body().deserialize::<u32>()
}
fn listen_for_actions(conn: Connection, shown: Shown, tx: Sender<Do>, ctx: Context) {
let Ok(rule) = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.interface("org.freedesktop.Notifications")
.and_then(|b| b.member("ActionInvoked"))
.map(|b| b.build())
else {
return;
};
let Ok(messages) = zbus::blocking::MessageIterator::for_match_rule(rule, &conn, None) else { return };
for message in messages.flatten() {
let Ok((id, key)) = message.body().deserialize::<(u32, String)>() else { continue };
let what = shown.lock().unwrap_or_else(|e| e.into_inner()).get(&id).and_then(|a| a.iter().find(|(k, _)| *k == key).map(|(_, d)| d.clone()));
if let Some(what) = what {
// Opening and showing a folder need no window, but the window is the one that does them.
let _ = tx.send(what);
ctx.request_repaint();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quiet_span_wraps_midnight() {
assert!(quiet_at(22 * 60, 7 * 60, 23 * 60));
assert!(quiet_at(22 * 60, 7 * 60, 3 * 60));
assert!(!quiet_at(22 * 60, 7 * 60, 12 * 60));
assert!(quiet_at(9 * 60, 17 * 60, 10 * 60));
assert!(!quiet_at(9 * 60, 9 * 60, 9 * 60));
}
#[test]
fn many_of_a_kind_become_one() {
let done = |i| Event::Done { id: i, name: format!("f{i}"), file: PathBuf::from("/x") };
assert_eq!(notes(&[done(1), done(2)]).len(), 2);
let many: Vec<_> = (1..=5).map(done).collect();
assert_eq!(notes(&many).len(), 1);
}
}