use std::io::IsTerminal;
use serde_json::{Value, json};
use vta_sdk::prelude::*;
use vta_sdk::trust_tasks as tt;
use super::calendar_connector_help::{self as help, offer_help, operator_guide, operator_help};
use super::calendar_connectors::{
Loopback, SHARED_ACCOUNT_NOTICE, busy_choice, call_newest, 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,
pub also_contexts: Vec<String>,
pub calendar_name: Option<String>,
pub help_operator: 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>;
fn say(&mut self, _text: &str) {}
}
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())
}
fn say(&mut self, text: &str) {
println!("{YELLOW}{text}{RESET}");
}
}
#[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>,
pub calendar_name: Option<String>,
pub communities: Vec<(String, String)>,
pub also: Vec<AlsoContext>,
pub busy_contexts: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlsoContext {
pub context: String,
pub write: String,
pub calendar_name: Option<String>,
pub communities: Vec<(String, String)>,
}
impl Plan {
#[must_use]
pub fn coverage(&self) -> Option<Value> {
let write = self.write.as_ref()?;
let one = |ctx: &str, w: &str, name: &Option<String>, comm: &[(String, String)]| {
let mut v = json!({ "contextId": ctx, "write": w });
if let Some(n) = name {
v["calendarName"] = json!(n);
}
if !comm.is_empty() {
v["communities"] = json!(
comm.iter()
.map(|(c, m)| json!({ "community": c, "write": m }))
.collect::<Vec<_>>()
);
}
v
};
let mut out = vec![one(
&self.context,
write,
&self.calendar_name,
&self.communities,
)];
out.extend(
self.also
.iter()
.map(|a| one(&a.context, &a.write, &a.calendar_name, &a.communities)),
);
Some(json!(out))
}
}
fn context_item(contexts: &[(String, String)], id: &str) -> String {
match contexts.iter().find(|(i, _)| i == id) {
Some((_, name)) if !name.is_empty() && name != id => format!("{name} ({id})"),
_ => id.to_string(),
}
}
fn default_calendar_name(contexts: &[(String, String)], id: &str) -> String {
let name = contexts
.iter()
.find(|(i, _)| i == id)
.map_or(id, |(_, n)| if n.is_empty() { id } else { n.as_str() });
format!("VTI \u{2014} {name}")
}
const MODES: [&str; 3] = ["busy", "titles", "off"];
fn mode_items() -> [String; 3] {
[
"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(),
]
}
fn ask_calendar(
a: &mut dyn Ask,
contexts: &[(String, String)],
ctx: &str,
) -> Result<(Option<String>, Vec<(String, String)>), String> {
let default = default_calendar_name(contexts, ctx);
let name = a.input(
&format!(
"Name of {}'s calendar at the provider",
context_item(contexts, ctx)
),
Some(&default),
)?;
let name = (name.trim() != default && !name.trim().is_empty()).then(|| name.trim().to_string());
let mut communities = Vec::new();
while a.confirm(
&format!(
"Write a different mode for one community in {}?",
context_item(contexts, ctx)
),
false,
)? {
let did = a.input("The community's DID", None)?;
if did.trim().is_empty() {
break;
}
let m = MODES[a.select("What should be written for it?", &mode_items(), 0)?];
communities.push((did.trim().to_string(), m.to_string()));
}
Ok((name, communities))
}
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 {
let why = o["reason"]
.as_str()
.or_else(|| o["unavailableBecause"].as_str());
return Some(match why {
Some("disabledByOperator") => "its operator turned it off".into(),
Some("unreachable") => "the VTA cannot reach it".into(),
Some("builtinOff") => "its operator turned the built-in clients off and registered \
no app of its own"
.into(),
Some("redirectNotRegistered") => "no app its operator registered admits a \
redirect this command can catch"
.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,
contexts: &[(String, String)],
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();
let fix = offer(offers, c.provider())
.map(offer_help)
.unwrap_or_default()
.join("\n\n");
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"),
if fix.is_empty() {
String::new()
} else {
format!("\n\nWhat the VTA's operator can do:\n\n{fix}")
},
));
}
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)) if !contexts.is_empty() => {
let items: Vec<String> = contexts
.iter()
.map(|(id, _)| context_item(contexts, id))
.collect();
contexts[a.select("Trust context for this calendar", &items, 0)?]
.0
.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)) => {
MODES[a.select("What should the VTA write into it?", &mode_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.as_deref_mut()) {
(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(),
};
let writes = write.as_deref().is_some_and(|w| w != "off");
let (mut calendar_name, mut communities) = (opts.calendar_name.clone(), Vec::new());
if let (true, None, Some(a)) = (writes, &calendar_name, ask.as_deref_mut()) {
(calendar_name, communities) = ask_calendar(a, contexts, &context)?;
}
let mut also: Vec<AlsoContext> = Vec::new();
let mut busy_contexts: Vec<String> = Vec::new();
if choice != Choice::IcsBusy {
for ctx in &opts.also_contexts {
if *ctx == context || also.iter().any(|x| x.context == *ctx) {
return Err(format!("{ctx} is named twice"));
}
also.push(AlsoContext {
context: ctx.clone(),
write: write.clone().unwrap_or_else(|| "busy".into()),
calendar_name: None,
communities: Vec::new(),
});
}
if let Some(a) = ask.as_deref_mut() {
let mut told = !also.is_empty();
loop {
let left: Vec<&(String, String)> = contexts
.iter()
.filter(|(id, _)| *id != context && !also.iter().any(|x| x.context == *id))
.collect();
if left.is_empty() {
break;
}
if !told {
a.say(SHARED_ACCOUNT_NOTICE);
told = true;
}
if !a.confirm(
"Add another trust context to this connector (same sign-in)?",
false,
)? {
break;
}
let items: Vec<String> = left
.iter()
.map(|(id, _)| context_item(contexts, id))
.collect();
let ctx = left[a.select("Which trust context?", &items, 0)?].0.clone();
let w = MODES[a.select(
&format!(
"What should be written for {}?",
context_item(contexts, &ctx)
),
&mode_items()[..2],
0,
)?]
.to_string();
let (calendar_name, communities) = ask_calendar(a, contexts, &ctx)?;
also.push(AlsoContext {
context: ctx,
write: w,
calendar_name,
communities,
});
}
}
if busy && !also.is_empty() {
busy_contexts.push(context.clone());
for x in &also {
let counts = match ask.as_deref_mut() {
Some(a) => a.confirm(
&format!(
"Count busy time read back in {} too?",
context_item(contexts, &x.context)
),
true,
)?,
None => true,
};
if counts {
busy_contexts.push(x.context.clone());
}
}
if busy_contexts.len() == 1 {
busy_contexts.clear();
}
}
} else if !opts.also_contexts.is_empty() {
return Err(
"busy time only writes nothing: it serves one context; choose where it \
counts with --busy-context on `pnm calendar connectors create`"
.into(),
);
}
Ok(Plan {
choice,
context,
label,
write,
busy,
flow,
endpoint,
username,
calendar_name,
communities,
also,
busy_contexts,
})
}
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 = match call_newest(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_PROVIDERS_LIST_0_2,
Some(tt::TASK_VTA_CALENDAR_CONNECTORS_PROVIDERS_LIST_0_1),
req,
None,
)
.await
{
Ok(o) => o,
Err(e) if opts.help_operator => {
println!(
"Could not read what this VTA offers ({e}); every provider's setup follows.\n"
);
println!("{}", operator_guide());
return Ok(());
}
Err(e) => return Err(e),
};
if opts.help_operator {
return print_operator_help(&offers);
}
let interactive = !opts.non_interactive && !is_json_output() && std::io::stdin().is_terminal();
let contexts: Vec<(String, String)> = if interactive {
client
.list_contexts()
.await
.map(|r| r.contexts.into_iter().map(|c| (c.id, c.name)).collect())
.unwrap_or_default()
} else {
Vec::new()
};
let mut term = Terminal;
let p = plan(
if interactive {
Some(&mut term as &mut dyn Ask)
} else {
None
},
&offers,
&contexts,
opts,
)?;
if !interactive && !p.also.is_empty() && !is_json_output() {
println!("{YELLOW}{SHARED_ACCOUNT_NOTICE}{RESET}");
}
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, &p.busy_contexts, &[]),
});
if let Some(cov) = p.coverage() {
create["coverage"] = cov;
}
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 interactive {
println!("{DIM}{}{RESET}", help::USER_APP_PASSWORD);
}
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}{}{RESET}", help::USER_PRIVATE_ICAL);
}
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 older = (p.also.is_empty() && super::calendar_connectors::same_at_v2(&create))
.then_some(tt::TASK_VTA_CALENDAR_CONNECTORS_CREATE_0_2);
let resp = call_newest(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_CREATE_0_3,
older,
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_newest(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_UPDATE_0_3,
Some(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)
}
fn print_operator_help(offers: &Value) -> CmdResult {
let blocks = operator_help(offers);
if is_json_output() {
return Ok(print_json(&serde_json::json!({
"providers": offers["providers"],
"help": blocks.iter().map(|(p, b)| json!({ "provider": p, "text": b })).collect::<Vec<_>>(),
}))?);
}
if blocks.is_empty() {
println!("This VTA offers every provider and every way in; there is nothing to configure.");
return Ok(());
}
for (i, (_, b)) in blocks.iter().enumerate() {
if i > 0 {
println!("\n----\n");
}
println!("{b}");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Default)]
struct Scripted {
answers: Vec<(&'static str, &'static str)>,
asked: Vec<String>,
said: Vec<String>,
}
impl Scripted {
fn new(answers: &[(&'static str, &'static str)]) -> Self {
Self {
answers: answers.to_vec(),
asked: Vec::new(),
said: 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 say(&mut self, text: &str) {
self.said.push(text.to_string());
self.asked.push(format!("(said) {text}"));
}
}
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", ""),
("calendar at the provider", ""),
("different mode for one community", ""),
]);
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", ""),
("calendar at the provider", "Outlook (VTI)"),
("different mode for one community", ""),
]);
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);
assert_eq!(p.calendar_name.as_deref(), Some("Outlook (VTI)"));
}
#[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}");
}
fn two_contexts() -> Vec<(String, String)> {
vec![
("work".to_string(), "Work".to_string()),
("home".to_string(), "Home".to_string()),
]
}
#[test]
fn vti_cal_127_one_sign_in_serves_a_second_context_after_the_notice() {
let mut a = Scripted::new(&[
("Which calendar", "Google"),
("Trust context", "Work"),
("write", ""),
("busy time back", ""),
("A name", ""),
("Name of Work (work)'s calendar", ""),
("different mode for one community in Work", ""),
("Add another trust context", "yes"),
("Which trust context", "Home"),
("written for Home", "Titles"),
("Name of Home (home)'s calendar", "Family"),
("different mode for one community in Home", "yes"),
("The community's DID", "did:web:club.example"),
("written for it", "Busy"),
("different mode for one community in Home", "no"),
("Count busy time read back in Home", "no"),
]);
let p = plan(Some(&mut a), &everything(), &two_contexts(), &opts()).unwrap();
assert!(a.answers.is_empty(), "unasked: {:?}", a.answers);
let notice = a
.asked
.iter()
.position(|q| q.starts_with("(said)"))
.unwrap();
let add = a
.asked
.iter()
.position(|q| q.contains("Add another trust context"))
.unwrap();
assert!(notice < add, "{:?}", a.asked);
assert!(a.said[0].contains("same account"));
assert_eq!(
p.coverage().unwrap(),
json!([
{ "contextId": "work", "write": "busy" },
{ "contextId": "home", "write": "titles", "calendarName": "Family",
"communities": [{ "community": "did:web:club.example", "write": "busy" }] }
])
);
assert!(p.busy_contexts.is_empty(), "counted in work alone");
}
#[test]
fn vti_cal_127_also_contexts_by_flag_count_busy_everywhere() {
let mut o = opts();
o.provider = Some("microsoft".into());
o.context = Some("work".into());
o.also_contexts = vec!["home".into()];
o.calendar_name = Some("Work (VTI)".into());
let p = plan(None, &everything(), &[], &o).unwrap();
assert_eq!(
p.coverage().unwrap(),
json!([{ "contextId": "work", "write": "busy", "calendarName": "Work (VTI)" },
{ "contextId": "home", "write": "busy" }])
);
assert_eq!(
p.busy_contexts,
vec!["work".to_string(), "home".to_string()]
);
o.also_contexts = vec!["work".into()];
assert!(
plan(None, &everything(), &[], &o)
.unwrap_err()
.contains("named twice")
);
}
#[test]
fn vti_cal_132_a_provider_not_offered_says_the_operator_fix() {
let mut offers = everything();
offers["providers"][1] = json!({ "provider": "microsoft", "available": false,
"unavailableBecause": "builtinOff", "reason": "builtinOff",
"writes": true, "readsBusy": true, "flows": [] });
let mut o = opts();
o.provider = Some("microsoft".into());
let e = plan(None, &offers, &[], &o).unwrap_err();
assert!(e.contains("turned the built-in clients off"), "{e}");
assert!(e.contains("builtin_clients = true"), "{e}");
}
}