use anyhow::Result;
use crate::gmail::auth;
use crate::gmail::client::GmailClient;
pub fn create_client() -> Result<GmailClient> {
create_client_for(None)
}
pub fn create_client_for(account: Option<&str>) -> Result<GmailClient> {
create_client_from(auth::load_credentials_for(account)?)
}
pub fn create_client_from(credentials: auth::GmailCredentials) -> Result<GmailClient> {
GmailClient::from_credentials(&credentials)
}
pub fn print_shadowing_notice() {
eprintln!(
"note: legacy Gmail credentials are now shadowed for invocations without --account. \
Run `gmail account import-legacy` to migrate any other legacy account, or \
`gmail auth logout` to remove the old credentials once every mailbox you use is \
migrated."
);
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use crate::gmail::auth::{GmailCredentials, GmailScope};
use crate::utils::secret::Secret;
#[test]
fn create_client_from_uses_gmail_api_host() {
let creds = GmailCredentials {
client_id: "client".to_string(),
client_secret: Secret::new("secret"),
refresh_token: Secret::new("refresh"),
scope: GmailScope::ReadOnly,
};
let client = create_client_from(creds).unwrap();
assert_eq!(client.base_url(), "https://gmail.googleapis.com");
}
#[test]
fn create_client_for_named_account_uses_that_accounts_credentials() {
let guard = crate::gmail::test_support::EnvGuard::take();
let dir = guard.clear_credentials();
let settings_path = dir.path().join(".omni-dev").join("settings.json");
crate::utils::settings::Settings::upsert_gmail_account(
&settings_path,
"work",
&[
(
"client_id",
serde_json::Value::String("work-id".to_string()),
),
(
"client_secret",
serde_json::Value::String("work-secret".to_string()),
),
(
"refresh_token",
serde_json::Value::String("work-refresh".to_string()),
),
],
)
.unwrap();
let client = create_client_for(Some("work")).unwrap();
assert_eq!(client.base_url(), "https://gmail.googleapis.com");
}
#[test]
fn create_client_for_unknown_account_errors() {
let guard = crate::gmail::test_support::EnvGuard::take();
let _dir = guard.clear_credentials();
let err = create_client_for(Some("bogus")).unwrap_err();
assert!(err.to_string().contains("unknown Gmail account 'bogus'"));
}
}