feat(gmail): implement list functionality for Gmail API

- Add list functionality to retrieve and display email subjects from Gmail.
- Integrate with google_gmail1 crate for Gmail API interactions.
- Implement authentication using InstalledFlowAuthenticator.
- Retrieve and display email subjects using the Gmail API.
- Configure max results to limit displayed subjects.
This commit is contained in:
Jeremiah Russell
2025-10-02 13:45:37 +01:00
committed by Jeremiah Russell
parent 44c9220eb1
commit af929a7acb

View File

@@ -1,38 +1,109 @@
use google_clis_common as common;
use google_gmail1::{ use google_gmail1::{
Error, Gmail, hyper_rustls::HttpsConnector, hyper_util::client::legacy::connect::HttpConnector, Gmail,
hyper_rustls::{HttpsConnector, HttpsConnectorBuilder},
hyper_util::{
client::legacy::{Client, connect::HttpConnector},
rt::TokioExecutor,
},
yup_oauth2::{ApplicationSecret, InstalledFlowAuthenticator, InstalledFlowReturnMethod},
}; };
use crate::{Credential, Error};
const DEFAULT_MAX_RESULTS: u32 = 10;
/// Struct to capture configuration for List API call. /// Struct to capture configuration for List API call.
pub struct List { pub struct List {
hub: Gmail<HttpsConnector<HttpConnector>>, hub: Gmail<HttpsConnector<HttpConnector>>,
max_results: u32,
} }
impl List { impl List {
/// Create a new List struct and add the Gmail api connection. /// Create a new List struct and add the Gmail api connection.
pub fn new(hub: Gmail<HttpsConnector<HttpConnector>>) -> Self { pub async fn new(credential: &str) -> Result<Self, Error> {
List { hub } let (config_dir, secret) = {
let config_dir = match common::assure_config_dir_exists("~/.cull-gmail") {
Err(e) => return Err(Error::InvalidOptionsError(e, 3)),
Ok(p) => p,
};
let secret: ApplicationSecret = Credential::load_json_file(credential).into();
(config_dir, secret)
};
let executor = TokioExecutor::new();
let connector = HttpsConnectorBuilder::new()
.with_native_roots()
.unwrap()
.https_or_http()
.enable_http1()
.build();
let client = Client::builder(executor.clone()).build(connector.clone());
let auth = InstalledFlowAuthenticator::with_client(
secret,
InstalledFlowReturnMethod::HTTPRedirect,
Client::builder(executor).build(connector),
)
.persist_tokens_to_disk(format!("{config_dir}/gmail1"))
.build()
.await
.unwrap();
Ok(List {
hub: Gmail::new(client, auth),
max_results: DEFAULT_MAX_RESULTS,
})
} }
/// Run the Gmail api as configured /// Run the Gmail api as configured
pub async fn run(&self) { pub async fn run(&self) -> Result<(), Error> {
let result = self.hub.users().messages_list("me").doit().await; let (_response, list) = self
.hub
.users()
.messages_list("me")
.max_results(self.max_results)
.doit()
.await?;
match result { // println!("{list:#?}");
Err(e) => match e { if let Some(messages) = list.messages {
// The Error enum provides details about what exactly happened. for message in messages {
// You can also just use its `Debug`, `Display` or `Error` traits if let Some(id) = message.id {
Error::HttpError(_) log::trace!("{id}");
| Error::Io(_) let (_res, m) = self
| Error::MissingAPIKey .hub
| Error::MissingToken(_) .users()
| Error::Cancelled .messages_get("me", &id)
| Error::UploadSizeLimitExceeded(_, _) .add_scope("https://www.googleapis.com/auth/gmail.metadata")
| Error::Failure(_) .format("metadata")
| Error::BadRequest(_) .add_metadata_headers("subject")
| Error::FieldClash(_) .doit()
| Error::JsonDecodeError(_, _) => println!("{e}"), .await?;
},
Ok(res) => println!("Success: {res:?}"), let mut subject = String::new();
if let Some(payload) = m.payload {
if let Some(headers) = payload.headers {
for header in headers {
if header.name.is_some()
&& header.name.unwrap() == "Subject"
&& header.value.is_some()
{
subject = header.value.unwrap();
break;
} else {
continue;
}
}
}
}
log::info!("{subject:?}");
}
}
} }
Ok(())
} }
} }