cull_gmail/
labels.rs

1use std::collections::HashMap;
2
3use google_gmail1::{
4    Gmail,
5    api::Label,
6    hyper_rustls::{HttpsConnector, HttpsConnectorBuilder},
7    hyper_util::{
8        client::legacy::{Client, connect::HttpConnector},
9        rt::TokioExecutor,
10    },
11    yup_oauth2::{ApplicationSecret, InstalledFlowAuthenticator, InstalledFlowReturnMethod},
12};
13
14use crate::{Credential, Result};
15
16/// Default for the maximum number of results to return on a page
17pub const DEFAULT_MAX_RESULTS: &str = "10";
18
19/// Struct to capture configuration for List API call.
20pub struct Labels {
21    hub: Gmail<HttpsConnector<HttpConnector>>,
22    label_list: Vec<Label>,
23    label_map: HashMap<String, String>,
24}
25
26impl std::fmt::Debug for Labels {
27    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        f.debug_struct("Labels")
29            .field("label_list", &self.label_list)
30            .field("label_map", &self.label_map)
31            .finish()
32    }
33}
34
35impl Labels {
36    /// Create a new List struct and add the Gmail api connection.
37    pub async fn new(credential: &str, show: bool) -> Result<Self> {
38        let (config_dir, secret) = {
39            let config_dir = crate::utils::assure_config_dir_exists("~/.cull-gmail")?;
40
41            let secret: ApplicationSecret = Credential::load_json_file(credential).into();
42            (config_dir, secret)
43        };
44
45        let executor = TokioExecutor::new();
46        let connector = HttpsConnectorBuilder::new()
47            .with_native_roots()
48            .unwrap()
49            .https_or_http()
50            .enable_http1()
51            .build();
52
53        let client = Client::builder(executor.clone()).build(connector.clone());
54
55        let auth = InstalledFlowAuthenticator::with_client(
56            secret,
57            InstalledFlowReturnMethod::HTTPRedirect,
58            Client::builder(executor).build(connector),
59        )
60        .persist_tokens_to_disk(format!("{config_dir}/gmail1"))
61        .build()
62        .await
63        .unwrap();
64
65        let hub = Gmail::new(client, auth);
66
67        let call = hub.users().labels_list("me");
68        let (_response, list) = call.doit().await.map_err(Box::new)?;
69
70        let Some(label_list) = list.labels else {
71            return Ok(Labels {
72                hub,
73                label_list: Vec::new(),
74                label_map: HashMap::new(),
75            });
76        };
77
78        let mut label_map = HashMap::new();
79        for label in &label_list {
80            if label.id.is_some() && label.name.is_some() {
81                let name = label.name.clone().unwrap();
82                let id = label.id.clone().unwrap();
83                if show {
84                    log::info!("{name}: {id}")
85                }
86                label_map.insert(name, id);
87            }
88        }
89
90        Ok(Labels {
91            hub,
92            label_list,
93            label_map,
94        })
95    }
96
97    /// Return the id for the name from the labels map.
98    /// Returns `None` if the name is not found in the map.
99    pub fn get_label_id(&self, name: &str) -> Option<String> {
100        self.label_map.get(name).cloned()
101    }
102}