use crate::error::{Error, Result};
use cosmic_pim_accounts::{Account, AccountStore, Registry};
use cosmic_pim_caldav::itip::Availability;
use cosmic_pim_caldav::{CaldavClient, Flavor};
#[derive(Debug, Clone)]
pub enum Answer {
Unsupported,
Answers(Vec<Availability>),
}
#[must_use]
pub fn account_for_collection(accounts: &AccountStore, collection_id: &str) -> Option<String> {
accounts.accounts().iter().find_map(|account| {
account
.collections
.values()
.any(|bound| bound == collection_id)
.then(|| account.id.clone())
})
}
#[must_use]
pub fn organizer_address(account: &Account) -> String {
cosmic_pim_core::model::normalise_address(&account.username)
}
pub fn availability(
accounts: &mut AccountStore,
registry: &Registry,
account_id: &str,
attendees: &[String],
from_ms: i64,
to_ms: i64,
) -> Result<Answer> {
if attendees.is_empty() {
return Ok(Answer::Answers(Vec::new()));
}
let account = accounts
.get(account_id)
.ok_or_else(|| {
Error::Account(cosmic_pim_accounts::Error::UnknownAccount(
account_id.to_owned(),
))
})?
.clone();
let secret = cosmic_pim_auth::resolve(accounts, registry, account_id).map_err(Error::Auth)?;
let auth = crate::engine::dav_auth(&account, &secret);
let url = crate::engine::service_url(&account, registry, crate::engine::Service::Calendar);
let client = CaldavClient::with_auth(&url, Flavor::CalDav, &auth);
let Some(outbox) = client.discover_scheduling()?.outbox_url else {
return Ok(Answer::Unsupported);
};
let answers = cosmic_pim_caldav::itip::query_availability(
&client,
&outbox,
&organizer_address(&account),
attendees,
from_ms,
to_ms,
)?;
Ok(Answer::Answers(answers))
}