use std::io::IsTerminal;
use serde_json::{Value, json};
use vta_sdk::prelude::*;
use vta_sdk::trust_tasks as tt;
use super::calendar_connectors::{
Loopback, busy_choice, call, device_outcome, device_wait, done, grant, read_secret,
seal_ics_address, seal_password,
};
use crate::render::{DIM, GREEN, RESET, YELLOW, is_json_output, print_json};
type CmdResult = Result<(), Box<dyn std::error::Error>>;
pub const ICLOUD_CALDAV: &str = "https://caldav.icloud.com/";
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct ConnectOptions {
pub provider: Option<String>,
pub context: Option<String>,
pub label: Option<String>,
pub write: Option<String>,
pub no_busy: bool,
pub flow: Option<String>,
pub username: Option<String>,
pub endpoint: Option<String>,
pub non_interactive: bool,
}
impl ConnectOptions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
pub trait Ask {
fn select(&mut self, prompt: &str, items: &[String], default: usize) -> Result<usize, String>;
fn input(&mut self, prompt: &str, default: Option<&str>) -> Result<String, String>;
fn confirm(&mut self, prompt: &str, default: bool) -> Result<bool, String>;
}
struct Terminal;
impl Ask for Terminal {
fn select(&mut self, prompt: &str, items: &[String], default: usize) -> Result<usize, String> {
dialoguer::Select::new()
.with_prompt(prompt)
.items(items)
.default(default)
.interact()
.map_err(|e| e.to_string())
}
fn input(&mut self, prompt: &str, default: Option<&str>) -> Result<String, String> {
let mut i = dialoguer::Input::<String>::new().with_prompt(prompt);
if let Some(d) = default {
i = i.default(d.to_string());
}
i.interact_text().map_err(|e| e.to_string())
}
fn confirm(&mut self, prompt: &str, default: bool) -> Result<bool, String> {
dialoguer::Confirm::new()
.with_prompt(prompt)
.default(default)
.interact()
.map_err(|e| e.to_string())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Choice {
Apple,
Google,
Microsoft,
IcsBusy,
Caldav,
}
impl Choice {
const ALL: [Self; 5] = [
Self::Apple,
Self::Google,
Self::Microsoft,
Self::IcsBusy,
Self::Caldav,
];
fn flag(self) -> &'static str {
match self {
Self::Apple => "apple",
Self::Google => "google",
Self::Microsoft => "microsoft",
Self::IcsBusy => "ics-busy",
Self::Caldav => "caldav",
}
}
fn menu(self) -> &'static str {
match self {
Self::Apple => "Apple iCloud",
Self::Google => "Google Calendar",
Self::Microsoft => "Microsoft (Outlook.com, Microsoft 365)",
Self::IcsBusy => "Busy time only, from a private iCal address (any calendar)",
Self::Caldav => "Another CalDAV server (Fastmail, Nextcloud, …)",
}
}
fn label(self) -> &'static str {
match self {
Self::Apple => "iCloud",
Self::Google => "Google Calendar",
Self::Microsoft => "Outlook",
Self::IcsBusy => "Busy time",
Self::Caldav => "Calendar",
}
}
fn provider(self) -> &'static str {
match self {
Self::Apple | Self::Caldav => "caldav",
Self::Google => "google",
Self::Microsoft => "microsoft",
Self::IcsBusy => "icsBusy",
}
}
fn parse(s: &str) -> Option<Self> {
Self::ALL
.into_iter()
.find(|c| c.flag() == s || (s == "icloud" && *c == Self::Apple))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Plan {
pub choice: Choice,
pub context: String,
pub label: String,
pub write: Option<String>,
pub busy: bool,
pub flow: Option<&'static str>,
pub endpoint: Option<String>,
pub username: Option<String>,
}
fn offer<'a>(offers: &'a Value, provider: &str) -> Option<&'a Value> {
offers["providers"]
.as_array()?
.iter()
.find(|o| o["provider"] == provider)
}
fn flows_here(o: &Value) -> Vec<&'static str> {
o["flows"]
.as_array()
.into_iter()
.flatten()
.filter_map(|f| match f["flow"].as_str() {
Some("deviceCode") => Some("deviceCode"),
Some("authorizationCode")
if f["redirectKinds"]
.as_array()
.is_some_and(|k| k.iter().any(|k| k == "loopback")) =>
{
Some("authorizationCode")
}
_ => None,
})
.collect()
}
fn unavailable(offers: &Value, c: Choice) -> Option<String> {
let Some(o) = offer(offers, c.provider()) else {
return Some("this VTA does not know it".into());
};
if o["available"] != true {
return Some(match o["unavailableBecause"].as_str() {
Some("disabledByOperator") => "its operator turned it off".into(),
Some("unreachable") => "the VTA cannot reach it".into(),
_ => "its operator has not registered an app for it".into(),
});
}
match c {
Choice::Google | Choice::Microsoft if flows_here(o).is_empty() => Some(
"its operator registered no app this command can sign in through (a loopback \
redirect, or for Microsoft a device code)"
.into(),
),
Choice::Apple
if o["caldavHosts"]
.as_array()
.is_some_and(|h| !h.iter().any(|h| h.as_str() == Some("caldav.icloud.com"))) =>
{
Some("its operator does not let the VTA reach caldav.icloud.com".into())
}
_ => None,
}
}
fn missing(flag: &str, why: &str) -> String {
format!(
"{why}: give {flag}, or run `pnm calendar connect` in a terminal to be asked.\n e.g. \
pnm calendar connect --provider microsoft --context <id>"
)
}
pub fn plan(
mut ask: Option<&mut dyn Ask>,
offers: &Value,
opts: &ConnectOptions,
) -> Result<Plan, String> {
let choice = match &opts.provider {
Some(p) => {
let c = Choice::parse(p).ok_or_else(|| {
format!(
"unknown provider {p:?}: give --provider apple, google, microsoft, \
ics-busy or caldav"
)
})?;
if let Some(why) = unavailable(offers, c) {
let others: Vec<&str> = Choice::ALL
.into_iter()
.filter(|o| unavailable(offers, *o).is_none())
.map(Choice::flag)
.collect();
return Err(format!(
"{} cannot be connected through this VTA: {why}.\n It offers: {}.\n \
e.g. pnm calendar connect --provider {} --context <id>",
c.menu(),
if others.is_empty() {
"nothing".to_string()
} else {
others.join(", ")
},
others.first().copied().unwrap_or("ics-busy"),
));
}
c
}
None => {
let offered: Vec<Choice> = Choice::ALL
.into_iter()
.filter(|c| unavailable(offers, *c).is_none())
.collect();
if offered.is_empty() {
return Err(
"this VTA offers no calendar provider; its operator configures them \
under [calendar.connectors] (docs/02-vta/calendar.md)"
.into(),
);
}
let Some(a) = ask.as_deref_mut() else {
return Err(missing("--provider", "which calendar to connect"));
};
let items: Vec<String> = offered.iter().map(|c| c.menu().to_string()).collect();
offered[a.select("Which calendar?", &items, 0)?]
}
};
let o = offer(offers, choice.provider())
.cloned()
.unwrap_or(Value::Null);
let flow = match choice {
Choice::Google | Choice::Microsoft => {
let here = flows_here(&o);
Some(match opts.flow.as_deref() {
Some("device-code") if here.contains(&"deviceCode") => "deviceCode",
Some("device-code") => {
return Err(format!(
"{} cannot be signed in to with a code here{}.\n Sign in through \
the browser: pnm calendar connect --provider {} --flow \
authorization-code",
choice.menu(),
if choice == Choice::Google {
" — Google has no device code for calendars"
} else {
" — the VTA's Microsoft app does not allow public client flows"
},
choice.flag()
));
}
Some("authorization-code") if here.contains(&"authorizationCode") => {
"authorizationCode"
}
Some("authorization-code") => {
return Err(format!(
"this VTA has no {} app that redirects to this machine; sign in with \
a code: pnm calendar connect --provider {} --flow device-code",
choice.menu(),
choice.flag()
));
}
Some(f) => {
return Err(format!(
"unknown flow {f:?}: give --flow device-code or authorization-code"
));
}
None => match (here.as_slice(), ask.as_deref_mut()) {
([only], _) | ([only, ..], None) => only,
(several, Some(a)) => {
let items: Vec<String> = several
.iter()
.enumerate()
.map(|(i, f)| {
let s = if *f == "deviceCode" {
"Enter a code at the provider, on any device"
} else {
"Sign in through a browser on this machine"
};
if i == 0 {
format!("{s} (recommended)")
} else {
s.to_string()
}
})
.collect();
several[a.select("How do you want to sign in?", &items, 0)?]
}
([], _) => unreachable!("an offered choice has a way in"),
},
})
}
_ => {
if opts.flow.is_some() {
return Err(format!(
"--flow is for Google and Microsoft; {} takes a password or an address",
choice.menu()
));
}
None
}
};
let context = match (&opts.context, ask.as_deref_mut()) {
(Some(c), _) => c.clone(),
(None, Some(a)) => a.input("Trust context for this calendar", None)?,
(None, None) => return Err(missing("--context <id>", "which trust context it is for")),
};
if context.trim().is_empty() {
return Err(missing("--context <id>", "a trust context is needed"));
}
let (endpoint, username) = match choice {
Choice::Apple | Choice::Caldav => {
let endpoint = match (choice, &opts.endpoint, ask.as_deref_mut()) {
(Choice::Apple, _, _) => ICLOUD_CALDAV.to_string(),
(_, Some(e), _) => e.clone(),
(_, None, Some(a)) => a.input("CalDAV server address (https://…)", None)?,
(_, None, None) => {
return Err(missing(
"--endpoint https://…",
"the CalDAV server is needed",
));
}
};
let prompt = if choice == Choice::Apple {
"Apple ID (the email you sign in to iCloud with)"
} else {
"User name at that server"
};
let username = match (&opts.username, ask.as_deref_mut()) {
(Some(u), _) => u.clone(),
(None, Some(a)) => a.input(prompt, None)?,
(None, None) => return Err(missing("--username", "the account is needed")),
};
(Some(endpoint), Some(username))
}
_ => (None, None),
};
let write = if choice == Choice::IcsBusy {
if opts.write.is_some() {
return Err(
"a private iCal address is read for busy time only; it writes \
nothing, so --write does not apply"
.into(),
);
}
None
} else {
Some(match (&opts.write, ask.as_deref_mut()) {
(Some(w), _) if ["busy", "titles", "off"].contains(&w.as_str()) => w.clone(),
(Some(w), _) => {
return Err(format!(
"unknown write mode {w:?}: give --write busy, titles or off"
));
}
(None, Some(a)) => {
let items = [
"Busy — each event's times, no titles (recommended)".to_string(),
"Titles — each event's title and times".to_string(),
"Nothing — only read my busy time".to_string(),
];
["busy", "titles", "off"]
[a.select("What should the VTA write into it?", &items, 0)?]
.to_string()
}
(None, None) => "busy".to_string(),
})
};
let busy = match choice {
Choice::IcsBusy => {
if opts.no_busy {
return Err(
"a private iCal address is read for busy time; --no-busy leaves \
it nothing to do"
.into(),
);
}
true
}
_ if opts.no_busy => false,
_ => match ask.as_deref_mut() {
Some(a) => a.confirm(
"Read your busy time back, so polls and find-a-time count it?",
true,
)?,
None => true,
},
};
if write.as_deref() == Some("off") && !busy {
return Err(
"with nothing written and nothing read the connector would do nothing: \
drop --no-busy or give --write busy"
.into(),
);
}
let label = match (&opts.label, ask) {
(Some(l), _) => l.clone(),
(None, Some(a)) => a.input("A name for it (only you see this)", Some(choice.label()))?,
(None, None) => choice.label().to_string(),
};
Ok(Plan {
choice,
context,
label,
write,
busy,
flow,
endpoint,
username,
})
}
pub async fn cmd_calendar_connect(client: &VtaClient, opts: &ConnectOptions) -> CmdResult {
let mut req = json!({});
if let Some(c) = &opts.context {
req["contextId"] = json!(c);
}
let offers = call(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_PROVIDERS_LIST_0_1,
req,
None,
)
.await?;
let interactive = !opts.non_interactive && !is_json_output() && std::io::stdin().is_terminal();
let mut term = Terminal;
let p = plan(
if interactive {
Some(&mut term as &mut dyn Ask)
} else {
None
},
&offers,
opts,
)?;
if let (Some(held), Some(limit)) = (
offers["connectorsHeld"].as_u64(),
offers["connectorLimit"].as_u64(),
) && held >= limit
{
return Err(format!(
"this VTA holds {held} of at most {limit} connectors; remove one first:\n \
pnm calendar connectors list\n pnm calendar connectors remove <connector-id>"
)
.into());
}
let mut create = json!({
"contextId": p.context,
"provider": p.choice.provider(),
"label": p.label,
"busy": busy_choice(p.busy, &[], &[]),
});
if let Some(w) = &p.write {
create["coverage"] = json!([{ "contextId": p.context, "write": w }]);
}
let mut listener = None;
match p.choice {
Choice::Apple | Choice::Caldav => {
let (Some(endpoint), Some(username)) = (&p.endpoint, &p.username) else {
return Err("the CalDAV server and account are needed".into());
};
if p.choice == Choice::Apple && interactive {
println!(
"{DIM}iCloud needs an app-specific password, not your Apple ID password: \
make one at https://account.apple.com → Sign-In and Security → \
App-Specific Passwords.{RESET}"
);
}
let password = read_secret(&format!("App-specific password for {username}"))?;
create["caldav"] = json!({
"endpoint": endpoint,
"username": username,
"sealedPassword": seal_password(client, endpoint, username, &password).await?,
});
}
Choice::IcsBusy => {
if interactive {
println!(
"{DIM}Use the calendar's private address in iCal format — Google: Settings \
→ your calendar → \"Secret address in iCal format\"; Outlook: Settings → \
Calendar → Shared calendars → Publish a calendar → ICS. Only times are kept \
of what it holds.{RESET}"
);
}
let address = read_secret("Private iCal address (https:// or webcal://)")?;
create["ics"] = json!({ "sealedAddress": seal_ics_address(client, &address).await? });
}
Choice::Google | Choice::Microsoft => {
if p.flow == Some("deviceCode") {
create["flow"] = json!("deviceCode");
} else {
let l = Loopback::bind().await?;
create["redirectUri"] = json!(l.redirect_uri);
listener = Some(l);
}
}
}
let resp = call(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_CREATE_0_2,
create,
None,
)
.await?;
let id = resp["connector"]["connectorId"]
.as_str()
.unwrap_or_default()
.to_string();
if let Some(device) = resp.get("deviceAuthorization") {
let opened = resp["connector"]["updatedAt"]
.as_str()
.unwrap_or_default()
.to_string();
let shown = device_wait(client, &id, device).await?;
let outcome = device_outcome(&id, &opened, &shown);
let browser = offer(&offers, "microsoft")
.is_some_and(|o| flows_here(o).contains(&"authorizationCode"));
if outcome.is_err() && interactive && browser {
println!("{YELLOW}The code was not accepted.{RESET}");
if Terminal
.confirm("Sign in through a browser on this machine instead?", true)
.unwrap_or(false)
{
let l = Loopback::bind().await?;
let again = call(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_UPDATE_0_2,
json!({ "connectorId": id, "reauthorize": { "redirectUri": l.redirect_uri } }),
Some(&id),
)
.await?;
if let Some(a) = again.get("authorization") {
let completed = grant(client, &id, "microsoft", a, Some(l)).await?;
println!("{GREEN}\u{2713}{RESET} Connected.");
return done(&completed);
}
}
}
return outcome;
}
if let Some(a) = resp.get("authorization") {
let completed = grant(client, &id, p.choice.provider(), a, listener).await?;
if !is_json_output() {
println!("{GREEN}\u{2713}{RESET} Connected.");
}
return done(&completed);
}
if is_json_output() {
return Ok(print_json(&resp)?);
}
println!("{GREEN}\u{2713}{RESET} Connected.");
done(&resp)
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Default)]
struct Scripted {
answers: Vec<(&'static str, &'static str)>,
asked: Vec<String>,
}
impl Scripted {
fn new(answers: &[(&'static str, &'static str)]) -> Self {
Self {
answers: answers.to_vec(),
asked: Vec::new(),
}
}
fn take(&mut self, prompt: &str) -> Result<&'static str, String> {
self.asked.push(prompt.to_string());
let at = self
.answers
.iter()
.position(|(p, _)| prompt.contains(p))
.ok_or_else(|| format!("no scripted answer for {prompt:?}"))?;
Ok(self.answers.remove(at).1)
}
}
impl Ask for Scripted {
fn select(
&mut self,
prompt: &str,
items: &[String],
default: usize,
) -> Result<usize, String> {
match self.take(prompt)? {
"" => Ok(default),
label => items
.iter()
.position(|i| i.starts_with(label))
.ok_or_else(|| format!("{label:?} is not offered for {prompt:?}: {items:?}")),
}
}
fn input(&mut self, prompt: &str, default: Option<&str>) -> Result<String, String> {
match self.take(prompt)? {
"" => Ok(default.unwrap_or_default().to_string()),
v => Ok(v.to_string()),
}
}
fn confirm(&mut self, prompt: &str, default: bool) -> Result<bool, String> {
match self.take(prompt)? {
"" => Ok(default),
v => Ok(v == "yes"),
}
}
}
fn everything() -> Value {
json!({ "providers": [
{ "provider": "google", "available": true, "writes": true, "readsBusy": true,
"flows": [{ "flow": "authorizationCode", "redirectKinds": ["loopback"], "builtIn": true }] },
{ "provider": "microsoft", "available": true, "writes": true, "readsBusy": true,
"flows": [{ "flow": "deviceCode", "builtIn": true },
{ "flow": "authorizationCode", "redirectKinds": ["loopback", "extension"], "builtIn": true }] },
{ "provider": "caldav", "available": true, "writes": true, "readsBusy": true, "flows": [] },
{ "provider": "icsBusy", "available": true, "writes": false, "readsBusy": true, "flows": [] }
], "connectorsHeld": 0, "connectorLimit": 8 })
}
fn opts() -> ConnectOptions {
ConnectOptions::new()
}
#[test]
fn vti_cal_119_microsoft_without_a_terminal_takes_the_recommended_device_code() {
let mut o = opts();
o.provider = Some("microsoft".into());
o.context = Some("work".into());
let p = plan(None, &everything(), &o).unwrap();
assert_eq!(p.flow, Some("deviceCode"));
assert_eq!(
p.write.as_deref(),
Some("busy"),
"busy time, no titles, by default"
);
assert!(p.busy, "busy time read back by default");
assert_eq!(p.label, "Outlook");
}
#[test]
fn vti_cal_119_google_is_never_offered_a_device_code() {
let mut o = opts();
o.provider = Some("google".into());
o.context = Some("work".into());
o.flow = Some("device-code".into());
let e = plan(None, &everything(), &o).unwrap_err();
assert!(e.contains("Google has no device code"), "{e}");
assert!(e.contains("--flow authorization-code"), "the fix: {e}");
}
#[test]
fn apple_asks_for_the_account_and_takes_the_defaults() {
let mut a = Scripted::new(&[
("Which calendar", "Apple iCloud"),
("Trust context", "personal"),
("Apple ID", "ada@example.com"),
("write", ""),
("busy time back", ""),
("A name", ""),
]);
let p = plan(Some(&mut a), &everything(), &opts()).unwrap();
assert_eq!(p.choice, Choice::Apple);
assert_eq!(p.endpoint.as_deref(), Some(ICLOUD_CALDAV));
assert_eq!(p.username.as_deref(), Some("ada@example.com"));
assert_eq!(p.write.as_deref(), Some("busy"));
assert!(p.busy);
assert_eq!(p.label, "iCloud");
assert!(a.answers.is_empty(), "every scripted question was asked");
}
#[test]
fn vti_cal_123_busy_time_only_asks_nothing_about_writing() {
let mut a = Scripted::new(&[
("Which calendar", "Busy time only"),
("Trust context", "personal"),
("A name", "Work (busy)"),
]);
let p = plan(Some(&mut a), &everything(), &opts()).unwrap();
assert_eq!(p.choice, Choice::IcsBusy);
assert_eq!(p.write, None);
assert!(p.busy);
assert_eq!(p.flow, None);
assert_eq!(p.label, "Work (busy)");
assert!(
!a.asked
.iter()
.any(|q| q.contains("write") || q.contains("busy time back")),
"{:?}",
a.asked
);
}
#[test]
fn microsoft_in_a_terminal_offers_both_ways_recommended_first() {
let mut a = Scripted::new(&[
("Which calendar", "Microsoft"),
("How do you want to sign in", "Sign in through a browser"),
("Trust context", "work"),
("write", "Titles"),
("busy time back", "no"),
("A name", ""),
]);
let p = plan(Some(&mut a), &everything(), &opts()).unwrap();
assert_eq!(p.flow, Some("authorizationCode"));
assert_eq!(p.write.as_deref(), Some("titles"));
assert!(!p.busy);
}
#[test]
fn vti_cal_125_only_what_the_vta_offers_is_offered() {
let mut offers = everything();
offers["providers"][0] = json!({ "provider": "google", "available": false,
"unavailableBecause": "notConfigured", "writes": true, "readsBusy": true, "flows": [] });
offers["providers"][2]["caldavHosts"] = json!(["caldav.fastmail.com"]);
let mut a = Scripted::new(&[("Which calendar", "Google")]);
let e = plan(Some(&mut a), &offers, &opts()).unwrap_err();
assert!(e.contains("not offered"), "{e}");
let mut o = opts();
o.provider = Some("google".into());
let e = plan(None, &offers, &o).unwrap_err();
assert!(e.contains("has not registered an app"), "{e}");
assert!(e.contains("It offers: microsoft, ics-busy, caldav"), "{e}");
o.provider = Some("apple".into());
let e = plan(None, &offers, &o).unwrap_err();
assert!(e.contains("caldav.icloud.com"), "{e}");
}
#[test]
fn without_a_terminal_a_missing_value_names_its_flag() {
let e = plan(None, &everything(), &opts()).unwrap_err();
assert!(e.contains("--provider"), "{e}");
let mut o = opts();
o.provider = Some("apple".into());
let e = plan(None, &everything(), &o).unwrap_err();
assert!(e.contains("--context <id>"), "{e}");
o.context = Some("personal".into());
let e = plan(None, &everything(), &o).unwrap_err();
assert!(e.contains("--username"), "{e}");
o.username = Some("ada@example.com".into());
o.write = Some("off".into());
o.no_busy = true;
let e = plan(None, &everything(), &o).unwrap_err();
assert!(e.contains("would do nothing"), "{e}");
}
}