cull_gmail/
message_list.rs

1use std::fmt::Debug;
2
3use crate::{Labels, Result};
4
5use google_gmail1::{
6    Gmail,
7    api::ListMessagesResponse,
8    hyper_rustls::{HttpsConnector, HttpsConnectorBuilder},
9    hyper_util::{
10        client::legacy::{Client, connect::HttpConnector},
11        rt::TokioExecutor,
12    },
13    yup_oauth2::{ApplicationSecret, InstalledFlowAuthenticator, InstalledFlowReturnMethod},
14};
15
16mod message_summary;
17
18use message_summary::MessageSummary;
19
20use crate::{Credential, utils::Elide};
21
22/// Default for the maximum number of results to return on a page
23pub const DEFAULT_MAX_RESULTS: &str = "10";
24
25/// Struct to capture configuration for List API call.
26pub struct MessageList {
27    hub: Gmail<HttpsConnector<HttpConnector>>,
28    max_results: u32,
29    label_ids: Vec<String>,
30    messages: Vec<MessageSummary>,
31    query: String,
32}
33
34impl Debug for MessageList {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.debug_struct("MessageList")
37            .field("max_results", &self.max_results)
38            .field("label_ids", &self.label_ids)
39            .field("messages", &self.messages)
40            .field("query", &self.query)
41            .finish()
42    }
43}
44
45impl MessageList {
46    /// Create a new List struct and add the Gmail api connection.
47    pub async fn new(credential: &str) -> Result<Self> {
48        let (config_dir, secret) = {
49            let config_dir = crate::utils::assure_config_dir_exists("~/.cull-gmail")?;
50
51            let secret: ApplicationSecret = Credential::load_json_file(credential).into();
52            (config_dir, secret)
53        };
54
55        let executor = TokioExecutor::new();
56        let connector = HttpsConnectorBuilder::new()
57            .with_native_roots()
58            .unwrap()
59            .https_or_http()
60            .enable_http1()
61            .build();
62
63        let client = Client::builder(executor.clone()).build(connector.clone());
64
65        let auth = InstalledFlowAuthenticator::with_client(
66            secret,
67            InstalledFlowReturnMethod::HTTPRedirect,
68            Client::builder(executor).build(connector),
69        )
70        .persist_tokens_to_disk(format!("{config_dir}/gmail1"))
71        .build()
72        .await
73        .unwrap();
74
75        Ok(MessageList {
76            hub: Gmail::new(client, auth),
77            max_results: DEFAULT_MAX_RESULTS.parse::<u32>().unwrap(),
78            label_ids: Vec::new(),
79            messages: Vec::new(),
80            query: String::new(),
81        })
82    }
83
84    /// Set the maximum results
85    pub fn set_max_results(&mut self, value: u32) {
86        self.max_results = value;
87    }
88
89    /// Report the maximum results value
90    pub fn max_results(&self) -> u32 {
91        self.max_results
92    }
93
94    /// Add label to the labels collection
95    pub async fn add_labels(&mut self, credential_file: &str, labels: &[String]) -> Result<()> {
96        // add labels if any specified
97        let label_list = Labels::new(credential_file, false).await?;
98
99        log::trace!("labels found and setup {label_list:#?}");
100        log::debug!("labels from command line: {labels:?}");
101        let mut label_ids = Vec::new();
102        for label in labels {
103            if let Some(id) = label_list.get_label_id(label) {
104                label_ids.push(id)
105            }
106        }
107        self.add_labels_ids(label_ids.as_slice());
108        Ok(())
109    }
110
111    /// Add label to the labels collection
112    fn add_labels_ids(&mut self, label_ids: &[String]) {
113        if !label_ids.is_empty() {
114            for id in label_ids {
115                self.label_ids.push(id.to_string())
116            }
117        }
118    }
119
120    /// Set the query string
121    pub fn set_query(&mut self, query: &str) {
122        self.query = query.to_string()
123    }
124
125    /// Get the summary of the messages
126    pub(crate) fn messages(&self) -> &Vec<MessageSummary> {
127        &self.messages
128    }
129
130    /// Get a reference to the message_ids
131    pub fn message_ids(&self) -> Vec<String> {
132        self.messages
133            .iter()
134            .map(|m| m.id().to_string())
135            .collect::<Vec<_>>()
136            .clone()
137    }
138
139    /// Get a reference to the message_ids
140    pub fn label_ids(&self) -> Vec<String> {
141        self.label_ids.clone()
142    }
143
144    /// Get the hub
145    pub fn hub(&self) -> Gmail<HttpsConnector<HttpConnector>> {
146        self.hub.clone()
147    }
148
149    /// Run the Gmail api as configured
150    pub async fn run(&mut self, pages: u32) -> Result<()> {
151        let list = self.messages_list(None).await?;
152        match pages {
153            1 => {}
154            0 => {
155                let mut list = list;
156                let mut page = 1;
157                loop {
158                    page += 1;
159                    log::debug!("Processing page #{page}");
160                    if list.next_page_token.is_none() {
161                        break;
162                    }
163                    list = self.messages_list(list.next_page_token).await?;
164                    // self.log_message_subjects(&list).await?;
165                }
166            }
167            _ => {
168                let mut list = list;
169                for page in 2..=pages {
170                    log::debug!("Processing page #{page}");
171                    if list.next_page_token.is_none() {
172                        break;
173                    }
174                    list = self.messages_list(list.next_page_token).await?;
175                    // self.log_message_subjects(&list).await?;
176                }
177            }
178        }
179
180        if log::max_level() >= log::Level::Info {
181            self.log_message_subjects().await?;
182        }
183
184        Ok(())
185    }
186
187    async fn messages_list(
188        &mut self,
189        next_page_token: Option<String>,
190    ) -> Result<ListMessagesResponse> {
191        let mut call = self
192            .hub
193            .users()
194            .messages_list("me")
195            .max_results(self.max_results);
196        // Add any labels specified
197        if !self.label_ids.is_empty() {
198            log::debug!("Setting labels for list: {:#?}", self.label_ids);
199            for id in self.label_ids.as_slice() {
200                call = call.add_label_ids(id);
201            }
202        }
203        // Add query
204        if !self.query.is_empty() {
205            log::debug!("Setting query string `{}`", self.query);
206            call = call.q(&self.query);
207        }
208        // Add a page token if it exists
209        if let Some(page_token) = next_page_token {
210            log::debug!("Setting token for next page.");
211            call = call.page_token(&page_token);
212        }
213
214        let (_response, list) = call.doit().await.map_err(Box::new)?;
215        log::trace!(
216            "Estimated {} messages.",
217            list.result_size_estimate.unwrap_or(0)
218        );
219
220        if list.result_size_estimate.unwrap_or(0) == 0 {
221            log::warn!("Search returned no messages.");
222            return Ok(list);
223        }
224
225        let mut list_ids = list
226            .clone()
227            .messages
228            .unwrap()
229            .iter()
230            .flat_map(|item| item.id.as_ref().map(|id| MessageSummary::new(id)))
231            .collect();
232        self.messages.append(&mut list_ids);
233
234        Ok(list)
235    }
236
237    async fn log_message_subjects(&mut self) -> Result<()> {
238        for message in &mut self.messages {
239            log::trace!("{}", message.id());
240            let (_res, m) = self
241                .hub
242                .users()
243                .messages_get("me", message.id())
244                .add_scope("https://www.googleapis.com/auth/gmail.metadata")
245                .format("metadata")
246                .add_metadata_headers("subject")
247                .doit()
248                .await
249                .map_err(Box::new)?;
250
251            let mut subject = String::new();
252            let Some(payload) = m.payload else { continue };
253            let Some(headers) = payload.headers else {
254                continue;
255            };
256
257            for header in headers {
258                if header.name.is_some()
259                    && header.name.unwrap() == "Subject"
260                    && header.value.is_some()
261                {
262                    subject = header.value.unwrap();
263                    break;
264                } else {
265                    continue;
266                }
267            }
268
269            if subject.is_empty() {
270                log::info!("***Email with no subject***");
271            } else {
272                subject.elide(24);
273                message.set_subject(&subject);
274                log::info!("{subject:?}");
275            }
276        }
277
278        Ok(())
279    }
280}