Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions apps/mailcraft/src/dav_find.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// SPDX-FileCopyrightText: MailCraft contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The host's side of Find in File › Info › Calendars and Contacts (#209, D7), on a thread of its
//! own, once the owner pressed Find and not before.
//!
//! The search is `mailcraft_net::dav_find`'s: it decides where the password may go. This only
//! carries its question to the window (`DavFindEvent::Question`), waits for the owner's answer,
//! and tells the window how it ended. A window that closed (the dialog went away) stops it before
//! its next request or question, and nothing more is told. Nothing here is logged.

use std::sync::atomic::Ordering;
use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
use std::time::Duration;

use mailcraft_model::{DavFindFailure, DavFindQuestion, DavFound};
use mailcraft_net::dav_find::DavFindAsk;
use mailcraft_ui_egui::dav_find::{DavFindEvent, DavFindJob};

/// The search itself: the real one, or a test's.
pub(crate) type Search<'a> =
&'a dyn Fn(&DavFindAsk<'_>, &mut dyn FnMut(&str, DavFindQuestion) -> Option<bool>, &dyn Fn() -> bool) -> Result<DavFound, DavFindFailure>;

/// Waits for the owner's answer; `None` when the owner gave up.
fn answer(job: &DavFindJob) -> Option<bool> {
loop {
match job.answers.recv_timeout(Duration::from_millis(100)) {
Ok(yes) => return Some(yes),
Err(RecvTimeoutError::Timeout) if job.cancel.load(Ordering::Relaxed) => return None,
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => return None,
}
}
}

/// Runs a job to its end, telling `emit` of the owner's questions and, last, how it ended (nothing,
/// when the owner has given up).
pub(crate) fn find_with(search: Search<'_>, job: &DavFindJob, emit: &mut dyn FnMut(DavFindEvent)) {
let ask = DavFindAsk {
email: &job.email,
mail_host: &job.mail_host,
username: &job.username,
password: &job.password,
calendars: &job.calendars,
contacts: &job.contacts,
trusted: &job.trusted,
};
let stopped = || job.cancel.load(Ordering::Relaxed);
let end = search(
&ask,
&mut |host, why| {
if stopped() {
return None;
}
emit(DavFindEvent::Question { host: host.to_owned(), why });
answer(job)
},
&stopped,
);
if !job.cancel.load(Ordering::Relaxed) {
emit(DavFindEvent::Finished(end));
}
}

/// Runs a job on a thread of its own, waking the window for each thing it tells.
pub(crate) fn run(job: DavFindJob, wake: &egui::Context) -> Receiver<DavFindEvent> {
let (tx, rx) = channel();
let wake = wake.clone();
let spawned = std::thread::Builder::new().name("calendar server search".into()).spawn(move || {
find_with(&|ask, question, stopped| mailcraft_net::dav_find::find(ask, question, stopped), &job, &mut |event| {
// Nobody is listening any more (the dialog closed): stop.
if tx.send(event).is_err() {
job.cancel.store(true, Ordering::Relaxed);
}
wake.request_repaint();
});
});
// A dropped sender reads as nothing found in the window.
if let Err(e) = spawned {
log::error!("couldn't start searching for a calendar server: {e}");
}
rx
}
97 changes: 97 additions & 0 deletions apps/mailcraft/src/dav_find_flow.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// SPDX-FileCopyrightText: MailCraft contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The host's side of Find (#209, D7): the search's question goes to the window, the owner's
//! answer comes back to it, and a window that went away stops it quietly. The search is a
//! stand-in here; `mailcraft_net::dav_find`'s own tests drive the real one against `mailcraft-dav`'s
//! stand-in server.

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Sender, channel};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use mailcraft_model::{DavFindFailure, DavFindQuestion, DavFound};
use mailcraft_net::dav_find::DavFindAsk;
use mailcraft_ui_egui::dav_find::{DavFindEvent, DavFindJob};

use crate::dav_find::find_with;

fn job() -> (DavFindJob, Sender<bool>) {
let (tx, answers) = channel();
let job = DavFindJob {
email: "ada@example.org".into(),
mail_host: "imap.example.org".into(),
username: String::new(),
password: "test-only-not-a-secret".into(),
calendars: String::new(),
contacts: String::new(),
trusted: String::new(),
cancel: Arc::new(AtomicBool::new(false)),
answers,
};
(job, tx)
}

/// A search that asks once about `dav.example.net` and finds a calendar there on a yes.
fn asking(
ask: &DavFindAsk<'_>,
question: &mut dyn FnMut(&str, DavFindQuestion) -> Option<bool>,
_stopped: &dyn Fn() -> bool,
) -> Result<DavFound, DavFindFailure> {
assert_eq!(ask.email, "ada@example.org");
match question("dav.example.net", DavFindQuestion::Elsewhere) {
Some(true) => Ok(DavFound { calendar_homes: vec!["https://dav.example.net/cal/ada/".into()], calendars: 1, ..Default::default() }),
_ => Err(DavFindFailure::Declined),
}
}

#[test]
fn the_question_goes_to_the_window_and_the_answer_comes_back() {
for yes in [true, false] {
let (job, answers) = job();
let (events, seen) = channel();
let told = std::thread::scope(|scope| {
scope.spawn(move || find_with(&asking, &job, &mut |event| events.send(event).unwrap()));
let first = seen.recv_timeout(Duration::from_secs(10)).expect("the owner is asked");
answers.send(yes).unwrap();
let last = seen.recv_timeout(Duration::from_secs(10)).expect("and told how it ended");
vec![first, last]
});
assert_eq!(told[0], DavFindEvent::Question { host: "dav.example.net".into(), why: DavFindQuestion::Elsewhere });
match &told[1] {
DavFindEvent::Finished(Ok(found)) => assert!(yes && found.calendars == 1),
DavFindEvent::Finished(Err(failure)) => assert!(!yes && *failure == DavFindFailure::Declined),
other => panic!("{other:?}"),
}
}
}

#[test]
fn a_window_that_went_away_while_the_question_is_open_ends_the_search_quietly() {
let (job, _answers) = job();
let cancel = job.cancel.clone();
let told: Arc<Mutex<Vec<DavFindEvent>>> = Arc::default();
std::thread::scope(|scope| {
let (sink, seen) = (told.clone(), told.clone());
let handle = scope.spawn(move || find_with(&asking, &job, &mut |event| sink.lock().unwrap().push(event)));
for _ in 0..1_000 {
if !seen.lock().unwrap().is_empty() {
break;
}
std::thread::sleep(Duration::from_millis(5));
}
cancel.store(true, Ordering::Relaxed);
handle.join().unwrap();
});
let told = told.lock().unwrap();
assert_eq!(told.len(), 1, "the question, and no ending");
assert!(matches!(told[0], DavFindEvent::Question { .. }));
}

#[test]
fn a_search_without_questions_tells_its_end_once() {
let (job, _answers) = job();
let mut told = Vec::new();
find_with(&|_, _, _| Err(DavFindFailure::NotFound), &job, &mut |event| told.push(event));
assert_eq!(told, vec![DavFindEvent::Finished(Err(DavFindFailure::NotFound))]);
}
7 changes: 7 additions & 0 deletions apps/mailcraft/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ mod clipboard_mime;
#[cfg(test)]
mod control_challenge_flow;
mod control_server;
mod dav_find;
#[cfg(test)]
mod dav_find_flow;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly"))]
mod desktop_icons;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly"))]
Expand Down Expand Up @@ -1098,6 +1101,7 @@ fn services(
let unsubscribe_ctx = ctx.clone();
let subscription_ctx = ctx.clone();
let dav_ctx = ctx.clone();
let dav_find_ctx = ctx.clone();
let pictures_kept = kept_pictures.clone();
let (images_ctx, images_kept) = (ctx.clone(), kept_pictures.clone());
let wipe_pictures = kept_pictures.clone();
Expand Down Expand Up @@ -1321,6 +1325,9 @@ fn services(
mailcraft_ui_egui::DavDone { download }
})
})),
// Find in File › Info › Calendars and Contacts: the search, on the owner's click, asking
// the window before the password may go to a host that isn't the owner's (#209).
dav_find: Some(Box::new(move |job| dav_find::run(job, &dav_find_ctx))),
// A sender's picture for the message list, once the owner turned that on: from
// Gravatar, favicon.im or Google, downloaded and kept like a message's pictures.
sender_images: Some(Box::new(move |address, wanted| {
Expand Down
4 changes: 2 additions & 2 deletions crates/engine/src/cmd/dav_account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ pub(super) fn switched_on(s: &Session) -> Option<&'static str> {
/// Whether an account of this kind may have calendar and contacts servers of its own: one that
/// has mail servers or a server of its own (IMAP, JMAP, Exchange server), not a Microsoft account
/// (Microsoft Graph keeps its calendars) nor one that only lives here, nor a shared mailbox
/// (which follows its owner's).
fn may_have(a: &Account) -> bool {
/// (which follows its owner's). The window asks the same before it offers them.
pub fn may_have(a: &Account) -> bool {
!a.is_shared() && matches!(a.kind, AccountKind::Imap | AccountKind::Jmap | AccountKind::Exchange)
}

Expand Down
Loading