use std::io::{IsTerminal, Read};
use serde_json::{Value, json};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use vta_sdk::error::VtaError;
use vta_sdk::prelude::*;
use vta_sdk::trust_tasks as tt;
use crate::render::{BOLD, CYAN, DIM, GREEN, RESET, YELLOW, is_json_output, print_json};
type CmdResult = Result<(), Box<dyn std::error::Error>>;
const LISTEN_SECONDS: u64 = 600;
pub(crate) fn local_code(e: &VtaError) -> Option<&str> {
e.rejection_code()
.map(|c| c.rsplit_once(':').map_or(c, |(_, l)| l))
}
pub(crate) fn fix_for(code: &str, id: Option<&str>) -> Option<String> {
let id = id.unwrap_or("<connector-id>");
Some(match code {
"providerUnavailable" => "This VTA does not offer that provider: its operator has not \
registered an OAuth client for it, or turned it off ([calendar.connectors] in the \
VTA's config; docs/02-vta/calendar.md). What it offers, and the operator's exact \
fix for what it does not:\n \
pnm calendar connect --help-operator\nAn iCloud calendar needs no registration:\n \
pnm calendar connect --provider apple --username <apple-id> --context <id>"
.to_string(),
"flowUnavailable" => "This VTA cannot take a grant from that provider that way: Google \
has no device code for calendars, and a Microsoft device code needs a client whose \
app registration allows public client flows. Sign in through the browser instead:\n \
pnm calendar connect --provider microsoft --flow authorization-code --context <id>"
.to_string(),
"addressRejected" => "That address did not answer with a calendar. Copy the calendar's \
private address in iCal format again (Google: Settings → your calendar → \
\"Secret address in iCal format\"; Outlook: Settings → Calendar → Shared calendars \
→ Publish a calendar → ICS) and:\n \
pnm calendar connect --provider ics-busy --context <id>"
.to_string(),
"endpointInvalid" => "The address must be HTTPS at a public host this VTA may reach \
(a webcal:// address is read as https://)."
.to_string(),
"authorizationDenied" => format!(
"The provider did not grant access. If your organisation forbids signing in with a \
code, sign in through the browser:\n \
pnm calendar connectors update {id} --reauthorize"
),
"limitReached" => "Remove a connector you no longer use first:\n \
pnm calendar connectors list\n pnm calendar connectors remove <connector-id>"
.to_string(),
"redirectInvalid" => "The redirect address must be one the operator registered, or a \
loopback address; omit --redirect-uri to let this command listen on one."
.to_string(),
"authorizationExpired" | "stateMismatch" => format!(
"Ask the provider again:\n pnm calendar connectors update {id} --reauthorize"
),
"credentialRejected" => format!(
"The server refused the password. Make a new app-specific password and:\n \
pnm calendar connectors update {id} --password"
),
"removing" => "The connector is being removed; nothing more can change on it.".to_string(),
"notFound" => "List the connectors you may see — one serving several contexts needs \
standing in each:\n pnm calendar connectors list"
.to_string(),
"permissionDenied" => "A context added to a connector needs your standing in it \
(VTI-CAL-128): see the contexts you have with\n pnm contexts list"
.to_string(),
_ => return None,
})
}
pub(crate) async fn call_newest(
client: &VtaClient,
newest: &str,
older: Option<&str>,
payload: Value,
id: Option<&str>,
) -> Result<Value, Box<dyn std::error::Error>> {
match client
.dispatch_trust_task(newest, payload.clone(), 30)
.await
{
Ok(v) => Ok(v),
Err(VtaError::UnsupportedTaskType { .. }) => match older {
Some(o) => call(client, o, payload, id).await,
None => Err(format!(
"this VTA does not serve `{newest}`, which a calendar per context or a calendar \
name needs (VTI-CAL-127): ask its operator to upgrade it, or leave the \
connector to one context."
)
.into()),
},
Err(e) => match local_code(&e).and_then(|c| fix_for(c, id)) {
Some(fix) => Err(format!("{e}\n {fix}").into()),
None => Err(Box::new(e)),
},
}
}
pub(crate) fn same_at_v2(req: &Value) -> bool {
!req["coverage"]
.as_array()
.into_iter()
.flatten()
.any(|c| c.get("calendarName").is_some())
}
pub(crate) async fn call(
client: &VtaClient,
uri: &str,
payload: Value,
id: Option<&str>,
) -> Result<Value, Box<dyn std::error::Error>> {
match client.dispatch_trust_task(uri, payload, 30).await {
Ok(v) => Ok(v),
Err(e) => match local_code(&e).and_then(|c| fix_for(c, id)) {
Some(fix) => Err(format!("{e}\n {fix}").into()),
None => Err(Box::new(e)),
},
}
}
#[derive(Debug, Default)]
pub struct ConnectorCreate {
pub context: String,
pub provider: String,
pub label: String,
pub write: String,
pub busy: bool,
pub busy_contexts: Vec<String>,
pub busy_calendars: Vec<String>,
pub redirect_uri: Option<String>,
pub endpoint: Option<String>,
pub username: Option<String>,
pub device_code: bool,
pub calendar_name: Option<String>,
}
#[derive(Debug, Default)]
pub struct ConnectorUpdate {
pub label: Option<String>,
pub write: Option<String>,
pub busy: Option<bool>,
pub busy_contexts: Vec<String>,
pub reauthorize: bool,
pub redirect_uri: Option<String>,
pub password_for: Option<(String, String)>,
pub device_code: bool,
pub ics_address: bool,
}
pub(crate) fn busy_choice(on: bool, contexts: &[String], calendars: &[String]) -> Value {
let mut b = json!({ "enabled": on });
if !contexts.is_empty() {
b["contextIds"] = json!(contexts);
}
if !calendars.is_empty() {
b["calendars"] = json!(calendars);
}
b
}
pub(crate) fn read_secret(
prompt: &str,
) -> Result<zeroize::Zeroizing<String>, Box<dyn std::error::Error>> {
let s = zeroize::Zeroizing::new(if std::io::stdin().is_terminal() {
dialoguer::Password::new().with_prompt(prompt).interact()?
} else {
let mut s = String::new();
std::io::stdin().read_to_string(&mut s)?;
s.trim_end_matches(['\r', '\n']).to_string()
});
Ok(s)
}
async fn sealed_password(
client: &VtaClient,
endpoint: &str,
username: &str,
) -> Result<String, Box<dyn std::error::Error>> {
let password = read_secret(&format!("App-specific password for {username}"))?;
seal_password(client, endpoint, username, &password).await
}
pub(crate) async fn seal_password(
client: &VtaClient,
endpoint: &str,
username: &str,
password: &str,
) -> Result<String, Box<dyn std::error::Error>> {
if password.is_empty() {
return Err("no password was given".into());
}
let wrapping = client.get_wrapping_key().await?;
Ok(vta_sdk::sealed_transfer::seal_calendar_credential(
&wrapping.wrapping_key,
endpoint,
username,
password,
)
.await?)
}
pub(crate) async fn seal_ics_address(
client: &VtaClient,
address: &str,
) -> Result<String, Box<dyn std::error::Error>> {
let address = address.trim();
let lower = address.to_ascii_lowercase();
if !(lower.starts_with("https://") || lower.starts_with("webcal://")) {
return Err("a private calendar address starts with https:// or webcal://".into());
}
let wrapping = client.get_wrapping_key().await?;
Ok(
vta_sdk::sealed_transfer::seal_calendar_ics_address(&wrapping.wrapping_key, address)
.await?,
)
}
pub(crate) struct Loopback {
listener: tokio::net::TcpListener,
pub(crate) redirect_uri: String,
}
impl Loopback {
pub(crate) async fn bind() -> Result<Self, Box<dyn std::error::Error>> {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
let port = listener.local_addr()?.port();
Ok(Self {
listener,
redirect_uri: format!("http://127.0.0.1:{port}/callback"),
})
}
async fn wait(self, state: &str) -> Result<Vec<(String, String)>, Box<dyn std::error::Error>> {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(LISTEN_SECONDS);
loop {
let (mut sock, _) = tokio::time::timeout_at(deadline, self.listener.accept())
.await
.map_err(|_| "no redirect came back from the provider within 10 minutes")??;
let mut buf = vec![0u8; 8192];
let n = tokio::time::timeout(std::time::Duration::from_secs(10), sock.read(&mut buf))
.await
.unwrap_or(Ok(0))
.unwrap_or(0);
let head = String::from_utf8_lossy(&buf[..n]);
let target = head
.lines()
.next()
.and_then(|l| l.strip_prefix("GET "))
.and_then(|l| l.split(' ').next())
.unwrap_or("");
let query = target
.strip_prefix("/callback?")
.map(|q| {
q.split('&')
.filter_map(|kv| kv.split_once('='))
.map(|(k, v)| (k.to_string(), percent_decode(v)))
.collect::<Vec<_>>()
})
.unwrap_or_default();
if !query.iter().any(|(k, v)| k == "state" && v == state) {
let _ = sock
.write_all(
b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
)
.await;
continue;
}
let page = "<!doctype html><meta charset=utf-8><title>VTA</title>\
<p>Done. You can close this tab and return to the terminal.";
let _ = sock
.write_all(
format!(
"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\
Content-Length: {}\r\nConnection: close\r\n\r\n{page}",
page.len()
)
.as_bytes(),
)
.await;
return Ok(query);
}
}
}
fn percent_decode(s: &str) -> String {
let s = s.replace('+', " ");
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& i + 2 < bytes.len()
&& let Some(b) = std::str::from_utf8(&bytes[i + 1..i + 3])
.ok()
.and_then(|h| u8::from_str_radix(h, 16).ok())
{
out.push(b);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8_lossy(&out).into_owned()
}
pub(crate) async fn device_wait(
client: &VtaClient,
id: &str,
device: &Value,
) -> Result<Value, Box<dyn std::error::Error>> {
let uri = device["verificationUri"].as_str().unwrap_or("?");
let code = device["userCode"].as_str().unwrap_or("?");
let every = device["checkAfterSeconds"]
.as_u64()
.unwrap_or(5)
.clamp(1, 300);
let until = device["expiresAt"]
.as_str()
.and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok())
.map(|t| t.with_timezone(&chrono::Utc));
if !is_json_output() {
println!("On any device, open {BOLD}{uri}{RESET} and enter the code:");
println!();
println!(" {BOLD}{CYAN}{code}{RESET}");
println!();
println!(
"{DIM}Enter it only at the provider's own address, and only because this terminal \
is showing it to you: whoever enters it grants their account to this VTA.{RESET}"
);
if let Some(t) = until {
println!(
"{DIM}Waiting for you to sign in (until {} UTC)…{RESET}",
t.format("%H:%M")
);
}
}
loop {
tokio::time::sleep(std::time::Duration::from_secs(every)).await;
let shown = show(client, id).await?;
let c = &shown["connector"];
if c["state"] != "awaitingUser" {
return Ok(shown);
}
if until.is_some_and(|t| chrono::Utc::now() > t + chrono::Duration::seconds(30)) {
return Ok(shown);
}
}
}
pub(crate) fn device_outcome(id: &str, opened: &str, shown: &Value) -> CmdResult {
let c = &shown["connector"];
let refused_since = c["lastFault"]["occurredAt"]
.as_str()
.is_some_and(|t| t >= opened);
if c["state"] == "active" && !refused_since {
if !is_json_output() {
println!("{GREEN}\u{2713}{RESET} Connected.");
}
return done(shown);
}
let fault = c["lastFault"]["code"]
.as_str()
.unwrap_or("authorizationExpired");
let fix = fix_for(fault, Some(id)).unwrap_or_default();
Err(format!("the provider did not grant access ({fault}).\n {fix}").into())
}
pub(crate) async fn grant(
client: &VtaClient,
id: &str,
provider: &str,
authorization: &Value,
listener: Option<Loopback>,
) -> Result<Value, Box<dyn std::error::Error>> {
let url = authorization["url"].as_str().unwrap_or("?");
let state = authorization["state"]
.as_str()
.unwrap_or_default()
.to_string();
println!("Open this address in your browser and grant access:");
println!();
println!(" {url}");
println!();
if provider == "microsoft" {
println!(
"{YELLOW}Microsoft grants more than the VTA keeps:{RESET} its narrowest calendar \
permission (Calendars.ReadWrite) lets the VTA read and change every calendar in the \
account. The VTA writes only to a calendar it creates and reads only start, end \
and free/busy status (VTI-CAL-105)."
);
println!();
}
let Some(listener) = listener else {
println!(
"{DIM}When the provider redirects back, relay the code with:{RESET}\n \
pnm calendar connectors complete {id} --state {state} --code <code>"
);
return Ok(Value::Null);
};
println!("{DIM}Waiting for the provider to redirect back (10 minutes)…{RESET}");
let query = listener.wait(&state).await?;
let get = |k: &str| query.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
let mut req = json!({ "connectorId": id, "state": state });
match (get("code"), get("error")) {
(Some(code), _) => req["code"] = json!(code),
(None, Some(err)) => req["providerError"] = json!(err),
(None, None) => {
return Err("the provider redirected back with neither a code nor an error".into());
}
}
call(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_AUTHORIZE_COMPLETE_0_1,
req,
Some(id),
)
.await
}
fn print_connector(c: &Value) {
let fault = c["lastFault"]["code"]
.as_str()
.map(|f| format!(" · last fault {f}"))
.unwrap_or_default();
let flow = match c["flow"].as_str() {
Some("deviceCode") => " (device code)",
_ => "",
};
println!(
" {CYAN}{}{RESET} {BOLD}{}{RESET} {DIM}{}{} · {} · context {} · {} pending{}{RESET}",
c["connectorId"].as_str().unwrap_or("?"),
c["label"].as_str().unwrap_or(""),
c["provider"].as_str().unwrap_or("?"),
flow,
c["state"].as_str().unwrap_or("?"),
c["contextId"].as_str().unwrap_or("?"),
c["pendingWrites"].as_u64().unwrap_or(0),
fault,
);
let calendars = c["calendars"].as_array().cloned().unwrap_or_default();
for cov in c["coverage"].as_array().into_iter().flatten() {
let ctx = cov["contextId"].as_str().unwrap_or("?");
let cal = calendars
.iter()
.find(|x| x["contextId"] == ctx)
.map(|x| {
format!(
" into \"{}\" ({})",
x["name"].as_str().unwrap_or("?"),
x["state"].as_str().unwrap_or("?")
)
})
.unwrap_or_default();
let overrides = cov["communities"].as_array().map_or(0, Vec::len);
println!(
" {DIM}context {ctx}: writes {}{cal}{}{RESET}",
cov["write"].as_str().unwrap_or("?"),
if overrides > 0 {
format!(" · {overrides} community override(s)")
} else {
String::new()
}
);
}
for x in calendars.iter().filter(|x| x["state"] == "removing") {
println!(
" {DIM}context {}: no longer served — deleting \"{}\"{RESET}",
x["contextId"].as_str().unwrap_or("?"),
x["name"].as_str().unwrap_or("?")
);
}
if c["busy"]["enabled"].as_bool() == Some(true) {
let counted: Vec<&str> = c["busy"]["contextIds"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.collect();
println!(
" {DIM}reads busy time, counted in {}{}{RESET}",
if counted.is_empty() {
c["contextId"].as_str().unwrap_or("?").to_string()
} else {
counted.join(", ")
},
c["lastReadAt"]
.as_str()
.map(|t| format!(", last {t}"))
.unwrap_or_default()
);
}
}
pub(crate) async fn show(
client: &VtaClient,
id: &str,
) -> Result<Value, Box<dyn std::error::Error>> {
call_newest(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_SHOW_0_3,
Some(tt::TASK_VTA_CALENDAR_CONNECTORS_SHOW_0_2),
json!({ "connectorId": id }),
Some(id),
)
.await
}
pub(crate) fn done(resp: &Value) -> CmdResult {
if is_json_output() {
return Ok(print_json(resp)?);
}
if let Some(c) = resp.get("connector") {
print_connector(c);
}
Ok(())
}
pub async fn cmd_connectors_create(client: &VtaClient, opts: &ConnectorCreate) -> CmdResult {
let mut req = json!({
"contextId": opts.context,
"provider": opts.provider,
"label": opts.label,
"busy": busy_choice(opts.busy, &opts.busy_contexts, &opts.busy_calendars),
});
if opts.provider != "icsBusy" {
let mut cov = json!({ "contextId": opts.context, "write": opts.write });
if let Some(n) = &opts.calendar_name {
cov["calendarName"] = json!(n);
}
req["coverage"] = json!([cov]);
}
let mut listener = None;
if opts.provider == "icsBusy" {
req["busy"] = busy_choice(true, &opts.busy_contexts, &[]);
let address = read_secret("Private iCal address (https:// or webcal://)")?;
req["ics"] = json!({ "sealedAddress": seal_ics_address(client, &address).await? });
} else if opts.device_code {
req["flow"] = json!("deviceCode");
} else if opts.provider == "caldav" {
let (Some(endpoint), Some(username)) = (&opts.endpoint, &opts.username) else {
return Err("a CalDAV connector needs --endpoint and --username".into());
};
let sealed = sealed_password(client, endpoint, username).await?;
req["caldav"] =
json!({ "endpoint": endpoint, "username": username, "sealedPassword": sealed });
} else if let Some(r) = &opts.redirect_uri {
req["redirectUri"] = json!(r);
} else {
let l = Loopback::bind().await?;
req["redirectUri"] = json!(l.redirect_uri);
listener = Some(l);
}
let older = same_at_v2(&req).then_some(tt::TASK_VTA_CALENDAR_CONNECTORS_CREATE_0_2);
let resp = call_newest(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_CREATE_0_3,
older,
req,
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();
let shown = device_wait(client, &id, device).await?;
return device_outcome(&id, opened, &shown);
}
let Some(authorization) = resp.get("authorization") else {
if !is_json_output() {
println!("{GREEN}\u{2713}{RESET} Connected.");
}
return done(&resp);
};
if is_json_output() && listener.is_none() {
return Ok(print_json(&resp)?);
}
let completed = grant(client, &id, &opts.provider, authorization, listener).await?;
if completed.is_null() {
return Ok(());
}
if !is_json_output() {
println!("{GREEN}\u{2713}{RESET} Connected.");
}
done(&completed)
}
pub async fn cmd_connectors_complete(
client: &VtaClient,
id: &str,
state: &str,
code: Option<&str>,
error: Option<&str>,
) -> CmdResult {
let mut req = json!({ "connectorId": id, "state": state });
match (code, error) {
(Some(c), _) => req["code"] = json!(c),
(None, Some(e)) => req["providerError"] = json!(e),
(None, None) => {
return Err("give --code, or --error with what the provider answered".into());
}
}
let resp = call(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_AUTHORIZE_COMPLETE_0_1,
req,
Some(id),
)
.await?;
done(&resp)
}
pub async fn cmd_connectors_list(client: &VtaClient, context: Option<&str>) -> CmdResult {
let mut req = json!({});
if let Some(c) = context {
req["contextId"] = json!(c);
}
let resp = call_newest(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_LIST_0_3,
Some(tt::TASK_VTA_CALENDAR_CONNECTORS_LIST_0_2),
req,
None,
)
.await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
let items = resp["connectors"].as_array().cloned().unwrap_or_default();
if items.is_empty() {
println!("No connectors. `pnm calendar connect` makes one.");
}
for c in &items {
print_connector(c);
}
Ok(())
}
pub async fn cmd_connectors_show(client: &VtaClient, id: &str) -> CmdResult {
let resp = show(client, id).await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
done(&resp)
}
pub async fn cmd_connectors_update(
client: &VtaClient,
id: &str,
opts: &ConnectorUpdate,
) -> CmdResult {
let current = show(client, id).await?;
let c = ¤t["connector"];
let provider = c["provider"].as_str().unwrap_or_default().to_string();
let mut req = json!({ "connectorId": id });
if let Some(l) = &opts.label {
req["label"] = json!(l);
}
if let Some(w) = &opts.write {
let home = c["contextId"].clone();
let mut coverage = c["coverage"].as_array().cloned().unwrap_or_default();
match coverage.iter_mut().find(|v| v["contextId"] == home) {
Some(v) => v["write"] = json!(w),
None => coverage.push(json!({ "contextId": home, "write": w })),
}
req["coverage"] = json!(coverage);
}
if let Some(on) = opts.busy {
req["busy"] = busy_choice(on, &opts.busy_contexts, &[]);
}
let mut listener = None;
if opts.reauthorize {
if opts.device_code {
req["reauthorize"] = json!({ "flow": "deviceCode" });
} else if let Some(r) = &opts.redirect_uri {
req["reauthorize"] = json!({ "redirectUri": r });
} else {
let l = Loopback::bind().await?;
req["reauthorize"] = json!({ "redirectUri": l.redirect_uri });
listener = Some(l);
}
}
if let Some((endpoint, username)) = &opts.password_for {
req["caldavPassword"] = json!(sealed_password(client, endpoint, username).await?);
}
if opts.ics_address {
let address = read_secret("New private iCal address (https:// or webcal://)")?;
req["icsAddress"] = json!(seal_ics_address(client, &address).await?);
}
let older = same_at_v2(&req).then_some(tt::TASK_VTA_CALENDAR_CONNECTORS_UPDATE_0_2);
let resp = call_newest(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_UPDATE_0_3,
older,
req,
Some(id),
)
.await?;
if let Some(device) = resp.get("deviceAuthorization") {
let opened = resp["connector"]["updatedAt"].as_str().unwrap_or_default();
let shown = device_wait(client, id, device).await?;
return device_outcome(id, opened, &shown);
}
match resp.get("authorization") {
Some(a) => {
let completed = grant(client, id, &provider, a, listener).await?;
if completed.is_null() {
return Ok(());
}
done(&completed)
}
None => done(&resp),
}
}
pub async fn cmd_connectors_remove(client: &VtaClient, id: &str, keep_calendar: bool) -> CmdResult {
let resp = call_newest(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_REMOVE_0_3,
Some(tt::TASK_VTA_CALENDAR_CONNECTORS_REMOVE_0_2),
json!({ "connectorId": id, "keepCalendar": keep_calendar }),
Some(id),
)
.await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
if resp["connector"]["provider"].as_str() == Some("icsBusy") {
println!(
"{GREEN}\u{2713}{RESET} Removing. The VTA erases the calendar address and the busy \
time read from it, and forgets the connector; `pnm calendar connectors list` \
shows it until then."
);
return Ok(());
}
println!(
"{GREEN}\u{2713}{RESET} Removing. The VTA {}, revokes its grant and forgets the \
connector; `pnm calendar connectors list` shows it until then.",
if keep_calendar {
"leaves its calendars at the provider"
} else {
"deletes every calendar it made at the provider, one per context"
}
);
Ok(())
}
pub const SHARED_ACCOUNT_NOTICE: &str = "The provider will hold this context's entries in the \
same account as the connector's other contexts — each in a calendar of its own, but in one \
account — so it can relate them to one another and to everything else it holds there. Use \
a separate connector, signed in to another account, to keep them apart.";
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ContextChange {
Add {
context: String,
write: String,
calendar_name: Option<String>,
count_busy: bool,
},
Remove { context: String },
Set {
context: String,
write: Option<String>,
calendar_name: Option<String>,
},
}
pub fn contexts_change(connector: &Value, change: &ContextChange) -> Result<Value, String> {
let mut coverage = connector["coverage"]
.as_array()
.cloned()
.unwrap_or_default();
let mut busy = connector["busy"].clone();
let at = |cov: &[Value], ctx: &str| cov.iter().position(|v| v["contextId"] == ctx);
match change {
ContextChange::Add {
context,
write,
calendar_name,
count_busy,
} => {
if at(&coverage, context).is_some() {
return Err(format!(
"the connector already serves {context}; change it with\n \
pnm calendar connectors contexts set <connector-id> --context {context} \
--write {write}"
));
}
let mut v = json!({ "contextId": context, "write": write });
if let Some(n) = calendar_name {
v["calendarName"] = json!(n);
}
coverage.push(v);
if *count_busy && busy["enabled"] == true {
let mut ids: Vec<Value> =
busy["contextIds"].as_array().cloned().unwrap_or_default();
if ids.is_empty() {
ids.push(connector["contextId"].clone());
}
if !ids.iter().any(|i| i == context) {
ids.push(json!(context));
}
busy["contextIds"] = json!(ids);
}
}
ContextChange::Remove { context } => {
let Some(i) = at(&coverage, context) else {
return Err(format!("the connector does not serve {context}"));
};
coverage.remove(i);
if let Some(ids) = busy["contextIds"].as_array_mut() {
ids.retain(|i| i != context);
if ids.is_empty() {
busy.as_object_mut().map(|o| o.remove("contextIds"));
}
}
}
ContextChange::Set {
context,
write,
calendar_name,
} => {
let Some(i) = at(&coverage, context) else {
return Err(format!(
"the connector does not serve {context}; add it with\n \
pnm calendar connectors contexts add <connector-id> --context {context}"
));
};
if write.is_none() && calendar_name.is_none() {
return Err("give --write or --calendar-name".into());
}
if let Some(w) = write {
coverage[i]["write"] = json!(w);
}
if let Some(n) = calendar_name {
coverage[i]["calendarName"] = json!(n);
}
}
}
Ok(json!({ "coverage": coverage, "busy": busy }))
}
pub async fn cmd_connectors_contexts(
client: &VtaClient,
id: &str,
change: &ContextChange,
yes: bool,
) -> CmdResult {
let current = call(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_SHOW_0_3,
json!({ "connectorId": id }),
Some(id),
)
.await?;
let c = ¤t["connector"];
if c["provider"] == "icsBusy" {
return Err(
"an icsBusy connector writes nothing; choose where its busy time counts \
with pnm calendar connectors update <connector-id> --busy-context <id>"
.into(),
);
}
let body = contexts_change(c, change)?;
match change {
ContextChange::Add { .. } => {
if !is_json_output() {
println!("{YELLOW}Before you add it:{RESET} {SHARED_ACCOUNT_NOTICE}");
}
let go = yes
|| (std::io::stdin().is_terminal()
&& dialoguer::Confirm::new()
.with_prompt("Add this context to the connector?")
.default(true)
.interact()?);
if !go {
return Err("not added (give --yes to add it without asking)".into());
}
}
ContextChange::Remove { context } => {
if !is_json_output() {
println!(
"{DIM}The VTA stops writing {context} at once, deletes its calendar at the \
provider with everything written there, and stops counting its busy time \
there (VTI-CAL-129).{RESET}"
);
}
}
ContextChange::Set { .. } => {}
}
let mut req = json!({ "connectorId": id, "coverage": body["coverage"] });
if body["busy"] != c["busy"] {
req["busy"] = body["busy"].clone();
}
let resp = call(
client,
tt::TASK_VTA_CALENDAR_CONNECTORS_UPDATE_0_3,
req,
Some(id),
)
.await?;
done(&resp)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vti_cal_128_contexts_add_remove_set_change_only_their_context() {
let c = json!({
"contextId": "work",
"coverage": [{ "contextId": "work", "write": "busy" }],
"busy": { "enabled": true },
});
let add = ContextChange::Add {
context: "home".into(),
write: "titles".into(),
calendar_name: Some("Home (VTI)".into()),
count_busy: true,
};
let b = contexts_change(&c, &add).unwrap();
assert_eq!(
b["coverage"],
json!([{ "contextId": "work", "write": "busy" },
{ "contextId": "home", "write": "titles", "calendarName": "Home (VTI)" }])
);
assert_eq!(b["busy"]["contextIds"], json!(["work", "home"]));
assert!(
contexts_change(
&c,
&ContextChange::Add {
context: "work".into(),
write: "busy".into(),
calendar_name: None,
count_busy: false,
}
)
.unwrap_err()
.contains("contexts set")
);
let two = json!({ "contextId": "work", "coverage": b["coverage"], "busy": b["busy"] });
let r = contexts_change(
&two,
&ContextChange::Remove {
context: "home".into(),
},
)
.unwrap();
assert_eq!(
r["coverage"],
json!([{ "contextId": "work", "write": "busy" }])
);
assert_eq!(r["busy"]["contextIds"], json!(["work"]));
let s = contexts_change(
&two,
&ContextChange::Set {
context: "work".into(),
write: None,
calendar_name: Some("Work".into()),
},
)
.unwrap();
assert_eq!(s["coverage"][0]["calendarName"], "Work");
assert_eq!(
s["coverage"][1]["write"], "titles",
"the other context untouched"
);
}
#[test]
fn a_calendar_name_is_a_0_3_request_alone() {
assert!(same_at_v2(
&json!({ "coverage": [{ "contextId": "a", "write": "busy" }] })
));
assert!(!same_at_v2(
&json!({ "coverage": [{ "contextId": "a", "write": "busy", "calendarName": "A" }] })
));
}
#[test]
fn a_redirect_query_is_percent_decoded() {
assert_eq!(percent_decode("4%2F0Aean%2Bx"), "4/0Aean+x");
assert_eq!(percent_decode("access_denied"), "access_denied");
assert_eq!(percent_decode("a+b%"), "a b%");
}
#[tokio::test]
async fn the_loopback_listener_answers_only_its_own_state() {
let l = Loopback::bind().await.unwrap();
let addr = l.redirect_uri.trim_end_matches("/callback").to_string();
let host = addr.trim_start_matches("http://").to_string();
let waiter = tokio::spawn(async move { l.wait("S1").await.unwrap() });
for target in [
"/favicon.ico",
"/callback?state=OTHER&code=x",
"/callback?state=S1&code=4%2Fabc",
] {
let mut s = tokio::net::TcpStream::connect(&host).await.unwrap();
s.write_all(format!("GET {target} HTTP/1.1\r\nHost: x\r\n\r\n").as_bytes())
.await
.unwrap();
let mut out = String::new();
let _ = s.read_to_string(&mut out).await;
}
let q = waiter.await.unwrap();
assert!(q.contains(&("code".to_string(), "4/abc".to_string())));
}
}