Skip to main content

pidge_gmail/
provider.rs

1//! [`GmailProvider`]: pidge's [`Provider`] for Gmail and Google Calendar.
2
3use std::collections::{HashMap, HashSet};
4
5use async_trait::async_trait;
6use chrono::{DateTime, Utc};
7use futures::stream::{self, StreamExt};
8use pidge_client::auth::browser_flow::make_random;
9use pidge_core::provider::{
10    BusyBlock, Draft, DraftKind, DraftSpec, EventPatch, EventSpec, Folder, FolderInfo, MailChange,
11    MailItem, MailSync, Provider, ProviderError, ProviderKind, ProviderResult, Rsvp, SearchQuery,
12    UnsubscribeHeaders,
13};
14use pidge_core::{Attachment, Event, FullMessage};
15use reqwest::{Method, Response};
16use serde::de::DeserializeOwned;
17use serde::{Deserialize, Serialize};
18use serde_json::{Value, json};
19
20use crate::auth::GoogleAuth;
21use crate::calendar::{self, EventList, FreeBusyResponse, GEvent, PRIMARY};
22use crate::http::{check, check_id, send_with_retry};
23use crate::mime;
24use crate::model::{
25    GmailMessage, HistoryList, Label, METADATA_HEADERS, MessageList, Part, Profile, mail_item,
26};
27use crate::query;
28
29/// Gmail API base for the signed-in user.
30pub const GMAIL_BASE: &str = "https://gmail.googleapis.com/gmail/v1/users/me";
31/// Google Calendar API base.
32pub const CALENDAR_BASE: &str = "https://www.googleapis.com/calendar/v3";
33
34/// Messages fetched at once (metadata or raw).
35const FETCH_CONCURRENCY: usize = 8;
36/// Page size of a sync bootstrap.
37const SYNC_PAGE: u32 = 100;
38/// `messages.batchModify` takes at most this many ids.
39const BATCH_MODIFY_MAX: usize = 1000;
40
41/// The sync cursor, serialized as JSON. Versioned so a format change
42/// re-bootstraps instead of misreading an old cursor.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44struct SyncCursor {
45    v: u32,
46    #[serde(flatten)]
47    state: CursorState,
48}
49
50const CURSOR_VERSION: u32 = 1;
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(tag = "mode", rename_all = "snake_case")]
54enum CursorState {
55    /// Mid-bootstrap: the next `messages.list` page, and the mailbox's
56    /// history id from before the listing began (changes made during the
57    /// bootstrap are picked up by the first incremental round).
58    Bootstrap {
59        history_id: String,
60        page_token: String,
61    },
62    /// Incremental: `history.list` from `history_id`, continuing at
63    /// `page_token` when a round was cut into pages.
64    History {
65        history_id: String,
66        #[serde(default, skip_serializing_if = "Option::is_none")]
67        page_token: Option<String>,
68    },
69}
70
71impl SyncCursor {
72    fn encode(state: CursorState) -> String {
73        serde_json::to_string(&SyncCursor {
74            v: CURSOR_VERSION,
75            state,
76        })
77        .expect("cursor serializes")
78    }
79
80    fn decode(s: &str) -> ProviderResult<CursorState> {
81        match serde_json::from_str::<SyncCursor>(s) {
82            Ok(c) if c.v == CURSOR_VERSION => Ok(c.state),
83            _ => Err(ProviderError::CursorExpired),
84        }
85    }
86}
87
88#[derive(Deserialize)]
89struct DraftResource {
90    id: String,
91    #[serde(default)]
92    message: Option<GmailMessage>,
93}
94
95#[derive(Deserialize, Default)]
96struct LabelList {
97    #[serde(default)]
98    labels: Vec<Label>,
99}
100
101#[derive(Deserialize)]
102struct AttachmentData {
103    #[serde(default)]
104    data: String,
105}
106
107#[derive(Deserialize, Default)]
108struct ThreadResource {
109    #[serde(default)]
110    messages: Vec<GmailMessage>,
111}
112
113/// One Gmail mailbox with its primary Google calendar.
114pub struct GmailProvider {
115    auth: GoogleAuth,
116    gmail_base: String,
117    calendar_base: String,
118    /// Label id to label, loaded on first use and refreshed when a message
119    /// carries a label id pidge has not seen.
120    labels: tokio::sync::Mutex<Option<HashMap<String, Label>>>,
121    /// The primary calendar's time zone (all-day events start at its
122    /// midnight).
123    calendar_tz: tokio::sync::Mutex<Option<String>>,
124}
125
126impl GmailProvider {
127    pub fn new(auth: GoogleAuth) -> Self {
128        Self::for_test(auth, GMAIL_BASE, CALENDAR_BASE)
129    }
130
131    /// A provider with other API bases (a mock server in tests).
132    pub fn for_test(
133        auth: GoogleAuth,
134        gmail_base: impl Into<String>,
135        calendar_base: impl Into<String>,
136    ) -> Self {
137        Self {
138            auth,
139            gmail_base: gmail_base.into().trim_end_matches('/').to_string(),
140            calendar_base: calendar_base.into().trim_end_matches('/').to_string(),
141            labels: tokio::sync::Mutex::new(None),
142            calendar_tz: tokio::sync::Mutex::new(None),
143        }
144    }
145
146    fn account(&self) -> &str {
147        self.auth.email()
148    }
149
150    fn gmail(&self, path: &str) -> String {
151        format!("{}/{path}", self.gmail_base)
152    }
153
154    fn cal(&self, path: &str) -> String {
155        format!("{}/{path}", self.calendar_base)
156    }
157
158    /// Authenticate and send, retrying throttling; the status is not checked.
159    async fn send(
160        &self,
161        method: Method,
162        url: &str,
163        query: &[(&str, String)],
164        body: Option<&Value>,
165    ) -> ProviderResult<Response> {
166        let token = self.auth.access_token().await?;
167        let mut req = self
168            .auth
169            .http()
170            .request(method.clone(), url)
171            .bearer_auth(token);
172        if !query.is_empty() {
173            req = req.query(query);
174        }
175        req = match body {
176            Some(b) => req.json(b),
177            // Google's front end wants a length on every POST/PUT/PATCH.
178            None if method != Method::GET && method != Method::DELETE => req.body(Vec::new()),
179            None => req,
180        };
181        send_with_retry(req).await
182    }
183
184    async fn call<T: DeserializeOwned>(
185        &self,
186        method: Method,
187        url: &str,
188        query: &[(&str, String)],
189        body: Option<&Value>,
190        what: &str,
191    ) -> ProviderResult<T> {
192        let resp = self.send(method, url, query, body).await?;
193        let resp = check(resp, self.account(), what).await?;
194        resp.json::<T>()
195            .await
196            .map_err(|e| ProviderError::Other(format!("unreadable answer from Google: {e}")))
197    }
198
199    async fn call_empty(
200        &self,
201        method: Method,
202        url: &str,
203        query: &[(&str, String)],
204        body: Option<&Value>,
205        what: &str,
206    ) -> ProviderResult<()> {
207        let resp = self.send(method, url, query, body).await?;
208        check(resp, self.account(), what).await.map(|_| ())
209    }
210
211    // ---- labels -----------------------------------------------------------
212
213    async fn load_labels(&self) -> ProviderResult<HashMap<String, Label>> {
214        let list: LabelList = self
215            .call(Method::GET, &self.gmail("labels"), &[], None, "labels")
216            .await?;
217        let map: HashMap<String, Label> =
218            list.labels.into_iter().map(|l| (l.id.clone(), l)).collect();
219        *self.labels.lock().await = Some(map.clone());
220        Ok(map)
221    }
222
223    async fn label_map(&self) -> ProviderResult<HashMap<String, Label>> {
224        if let Some(m) = self.labels.lock().await.as_ref() {
225            return Ok(m.clone());
226        }
227        self.load_labels().await
228    }
229
230    /// The user label named `name` (case-insensitive), created if missing.
231    async fn find_or_create_label(&self, name: &str) -> ProviderResult<Label> {
232        let name = name.trim().trim_matches('/').trim();
233        if name.is_empty() {
234            return Err(ProviderError::Invalid("a label needs a name".into()));
235        }
236        let find = |m: &HashMap<String, Label>| {
237            m.values()
238                .find(|l| l.is_user() && l.name.eq_ignore_ascii_case(name))
239                .cloned()
240        };
241        if let Some(l) = find(&self.label_map().await?) {
242            return Ok(l);
243        }
244        let body = json!({
245            "name": name,
246            "labelListVisibility": "labelShow",
247            "messageListVisibility": "show",
248        });
249        let resp = self
250            .send(Method::POST, &self.gmail("labels"), &[], Some(&body))
251            .await?;
252        if resp.status().as_u16() == 409 {
253            // Created elsewhere since the cache was loaded.
254            return find(&self.load_labels().await?).ok_or_else(|| {
255                ProviderError::Invalid(format!("Gmail refused the label name {name:?}"))
256            });
257        }
258        let resp = check(resp, self.account(), "label").await?;
259        let mut label: Label = resp
260            .json()
261            .await
262            .map_err(|e| ProviderError::Other(format!("unreadable answer from Google: {e}")))?;
263        if label.kind.is_empty() {
264            label.kind = "user".into();
265        }
266        if let Some(m) = self.labels.lock().await.as_mut() {
267            m.insert(label.id.clone(), label.clone());
268        }
269        Ok(label)
270    }
271
272    // ---- messages ---------------------------------------------------------
273
274    async fn get_metadata(&self, id: &str, headers: &[&str]) -> ProviderResult<GmailMessage> {
275        let id = check_id(id, "message")?;
276        let mut q: Vec<(&str, String)> = vec![("format", "metadata".into())];
277        q.extend(headers.iter().map(|h| ("metadataHeaders", h.to_string())));
278        self.call(
279            Method::GET,
280            &self.gmail(&format!("messages/{id}")),
281            &q,
282            None,
283            "message",
284        )
285        .await
286    }
287
288    async fn get_raw(&self, id: &str) -> ProviderResult<GmailMessage> {
289        let id = check_id(id, "message")?;
290        self.call(
291            Method::GET,
292            &self.gmail(&format!("messages/{id}")),
293            &[("format", "raw".into())],
294            None,
295            "message",
296        )
297        .await
298    }
299
300    async fn get_labels_of(&self, id: &str) -> ProviderResult<GmailMessage> {
301        let id = check_id(id, "message")?;
302        self.call(
303            Method::GET,
304            &self.gmail(&format!("messages/{id}")),
305            &[("format", "minimal".into())],
306            None,
307            "message",
308        )
309        .await
310    }
311
312    /// Metadata for `ids`, at most [`FETCH_CONCURRENCY`] at a time, in order.
313    async fn fetch_metadata(&self, ids: &[String]) -> Vec<(String, ProviderResult<GmailMessage>)> {
314        stream::iter(ids.iter().cloned())
315            .map(|id| async move {
316                let r = self.get_metadata(&id, METADATA_HEADERS).await;
317                (id, r)
318            })
319            .buffered(FETCH_CONCURRENCY)
320            .collect()
321            .await
322    }
323
324    /// Labels for mapping `msgs`, reloaded once if one carries an unknown
325    /// user label.
326    async fn labels_for(&self, msgs: &[&GmailMessage]) -> ProviderResult<HashMap<String, Label>> {
327        let map = self.label_map().await?;
328        let unknown = msgs
329            .iter()
330            .flat_map(|m| m.label_ids.iter())
331            .any(|l| l.starts_with("Label_") && !map.contains_key(l));
332        if unknown {
333            self.load_labels().await
334        } else {
335            Ok(map)
336        }
337    }
338
339    /// [`MailItem`]s for `ids`; messages that no longer exist are skipped.
340    async fn items(&self, ids: &[String]) -> ProviderResult<Vec<MailItem>> {
341        let mut msgs = Vec::with_capacity(ids.len());
342        for (_, r) in self.fetch_metadata(ids).await {
343            match r {
344                Ok(m) => msgs.push(m),
345                Err(ProviderError::NotFound(_)) => {}
346                Err(e) => return Err(e),
347            }
348        }
349        let labels = self.labels_for(&msgs.iter().collect::<Vec<_>>()).await?;
350        Ok(msgs
351            .iter()
352            .map(|m| mail_item(self.account(), m, &labels))
353            .collect())
354    }
355
356    async fn list_messages(
357        &self,
358        q: &str,
359        page_token: Option<&str>,
360        max: u32,
361        label_id: Option<&str>,
362        include_spam_trash: bool,
363    ) -> ProviderResult<MessageList> {
364        let mut query: Vec<(&str, String)> = vec![("maxResults", max.to_string())];
365        if !q.is_empty() {
366            query.push(("q", q.to_string()));
367        }
368        if let Some(t) = page_token {
369            query.push(("pageToken", t.to_string()));
370        }
371        if let Some(l) = label_id {
372            query.push(("labelIds", check_id(l, "label")?.to_string()));
373        }
374        if include_spam_trash {
375            query.push(("includeSpamTrash", "true".into()));
376        }
377        self.call(
378            Method::GET,
379            &self.gmail("messages"),
380            &query,
381            None,
382            "messages",
383        )
384        .await
385    }
386
387    async fn bootstrap_page(
388        &self,
389        since: DateTime<Utc>,
390        history_id: String,
391        page_token: Option<String>,
392    ) -> ProviderResult<MailSync> {
393        let list = self
394            .list_messages(
395                &query::sync_q(since),
396                page_token.as_deref(),
397                SYNC_PAGE,
398                None,
399                false,
400            )
401            .await?;
402        let ids: Vec<String> = list.messages.into_iter().map(|m| m.id).collect();
403        let upserts = self.items(&ids).await?;
404        let (cursor, more) = match list.next_page_token {
405            Some(t) => (
406                SyncCursor::encode(CursorState::Bootstrap {
407                    history_id,
408                    page_token: t,
409                }),
410                true,
411            ),
412            None => (
413                SyncCursor::encode(CursorState::History {
414                    history_id,
415                    page_token: None,
416                }),
417                false,
418            ),
419        };
420        Ok(MailSync {
421            upserts,
422            removed: Vec::new(),
423            cursor,
424            more,
425        })
426    }
427
428    async fn history_page(
429        &self,
430        since: DateTime<Utc>,
431        history_id: String,
432        page_token: Option<String>,
433    ) -> ProviderResult<MailSync> {
434        check_id(&history_id, "history")?;
435        let mut q: Vec<(&str, String)> = vec![
436            ("startHistoryId", history_id.clone()),
437            ("maxResults", "500".into()),
438        ];
439        for t in [
440            "messageAdded",
441            "messageDeleted",
442            "labelAdded",
443            "labelRemoved",
444        ] {
445            q.push(("historyTypes", t.into()));
446        }
447        if let Some(t) = &page_token {
448            q.push(("pageToken", t.clone()));
449        }
450        let resp = self
451            .send(Method::GET, &self.gmail("history"), &q, None)
452            .await?;
453        if resp.status().as_u16() == 404 {
454            return Err(ProviderError::CursorExpired);
455        }
456        let resp = check(resp, self.account(), "history").await?;
457        let list: HistoryList = resp
458            .json()
459            .await
460            .map_err(|e| ProviderError::Other(format!("unreadable answer from Google: {e}")))?;
461
462        let mut deleted: Vec<String> = Vec::new();
463        let mut deleted_set: HashSet<String> = HashSet::new();
464        let mut changed: Vec<String> = Vec::new();
465        let mut changed_set: HashSet<String> = HashSet::new();
466        for h in &list.history {
467            for d in &h.messages_deleted {
468                if deleted_set.insert(d.message.id.clone()) {
469                    deleted.push(d.message.id.clone());
470                }
471            }
472            for m in h
473                .messages_added
474                .iter()
475                .chain(&h.labels_added)
476                .chain(&h.labels_removed)
477            {
478                if changed_set.insert(m.message.id.clone()) {
479                    changed.push(m.message.id.clone());
480                }
481            }
482        }
483        changed.retain(|id| !deleted_set.contains(id));
484
485        let mut removed = deleted;
486        let mut kept: Vec<GmailMessage> = Vec::new();
487        for (id, r) in self.fetch_metadata(&changed).await {
488            match r {
489                Ok(m) => {
490                    let outside = ["TRASH", "SPAM", "DRAFT"].iter().any(|l| m.has_label(l))
491                        || m.received_at() < since;
492                    if outside {
493                        removed.push(id);
494                    } else {
495                        kept.push(m);
496                    }
497                }
498                // Gone between the history record and now; an id that is
499                // not a message id is not ours to keep either.
500                Err(ProviderError::NotFound(_)) | Err(ProviderError::Invalid(_)) => {
501                    removed.push(id)
502                }
503                Err(e) => return Err(e),
504            }
505        }
506        let labels = self.labels_for(&kept.iter().collect::<Vec<_>>()).await?;
507        let upserts = kept
508            .iter()
509            .map(|m| mail_item(self.account(), m, &labels))
510            .collect();
511
512        let (state, more) = match list.next_page_token {
513            Some(t) => (
514                CursorState::History {
515                    history_id,
516                    page_token: Some(t),
517                },
518                true,
519            ),
520            None => (
521                CursorState::History {
522                    history_id: list.history_id.unwrap_or(history_id),
523                    page_token: None,
524                },
525                false,
526            ),
527        };
528        Ok(MailSync {
529            upserts,
530            removed,
531            cursor: SyncCursor::encode(state),
532            more,
533        })
534    }
535
536    /// `messages.batchModify` for `ids` (already checked), in chunks.
537    async fn batch_modify(
538        &self,
539        ids: &[String],
540        add: &[&str],
541        remove: &[&str],
542    ) -> Vec<ProviderResult<()>> {
543        let mut out = Vec::with_capacity(ids.len());
544        for chunk in ids.chunks(BATCH_MODIFY_MAX) {
545            let body = json!({
546                "ids": chunk,
547                "addLabelIds": add,
548                "removeLabelIds": remove,
549            });
550            let r = self
551                .call_empty(
552                    Method::POST,
553                    &self.gmail("messages/batchModify"),
554                    &[],
555                    Some(&body),
556                    "message",
557                )
558                .await;
559            out.extend(std::iter::repeat_n(r, chunk.len()));
560        }
561        out
562    }
563
564    async fn trash(&self, id: &str) -> ProviderResult<()> {
565        let id = check_id(id, "message")?;
566        self.call_empty(
567            Method::POST,
568            &self.gmail(&format!("messages/{id}/trash")),
569            &[],
570            None,
571            "message",
572        )
573        .await
574    }
575
576    async fn trash_all(&self, ids: &[String]) -> Vec<ProviderResult<()>> {
577        stream::iter(ids.to_vec())
578            .map(|id| async move { self.trash(&id).await })
579            .buffered(FETCH_CONCURRENCY)
580            .collect()
581            .await
582    }
583
584    async fn set_categories_all(
585        &self,
586        ids: &[String],
587        wanted: HashSet<String>,
588    ) -> Vec<ProviderResult<()>> {
589        let wanted = &wanted;
590        stream::iter(ids.to_vec())
591            .map(|id| async move { self.set_categories(&id, wanted).await })
592            .buffered(FETCH_CONCURRENCY)
593            .collect()
594            .await
595    }
596
597    async fn set_categories(&self, id: &str, wanted: &HashSet<String>) -> ProviderResult<()> {
598        let m = self.get_labels_of(id).await?;
599        let labels = self.labels_for(&[&m]).await?;
600        let current: HashSet<String> = m
601            .label_ids
602            .iter()
603            .filter(|l| labels.get(*l).is_some_and(Label::is_user))
604            .cloned()
605            .collect();
606        let add: Vec<&String> = wanted.difference(&current).collect();
607        let remove: Vec<&String> = current.difference(wanted).collect();
608        if add.is_empty() && remove.is_empty() {
609            return Ok(());
610        }
611        self.call_empty(
612            Method::POST,
613            &self.gmail(&format!("messages/{}/modify", check_id(id, "message")?)),
614            &[],
615            Some(&json!({ "addLabelIds": add, "removeLabelIds": remove })),
616            "message",
617        )
618        .await
619    }
620
621    // ---- drafts -----------------------------------------------------------
622
623    async fn build(&self, spec: &DraftSpec) -> ProviderResult<mime::BuiltDraft> {
624        let orig = match &spec.kind {
625            DraftKind::New => None,
626            DraftKind::Reply { to_id }
627            | DraftKind::ReplyAll { to_id }
628            | DraftKind::Forward { to_id } => Some(mime::original(&self.get_raw(to_id).await?)?),
629        };
630        mime::build_draft(self.account(), spec, orig.as_ref())
631    }
632
633    fn draft_of(&self, res: DraftResource, built: mime::BuiltDraft) -> Draft {
634        Draft {
635            account: self.account().to_string(),
636            id: res.id,
637            thread_id: res
638                .message
639                .map(|m| m.thread_id)
640                .filter(|t| !t.is_empty())
641                .or(built.thread_id),
642            to: built.to,
643            cc: built.cc,
644            bcc: built.bcc,
645            subject: built.subject,
646            body_text: built.body_text,
647            has_attachments: false,
648        }
649    }
650
651    fn draft_body(built: &mime::BuiltDraft, id: Option<&str>) -> Value {
652        let mut message = json!({ "raw": mime::encode_b64url(built.raw.as_bytes()) });
653        if let Some(t) = &built.thread_id {
654            message["threadId"] = json!(t);
655        }
656        let mut body = json!({ "message": message });
657        if let Some(id) = id {
658            body["id"] = json!(id);
659        }
660        body
661    }
662
663    // ---- calendar ---------------------------------------------------------
664
665    fn event_url(&self, id: &str) -> ProviderResult<String> {
666        let id = check_id(id, "event")?;
667        Ok(self.cal(&format!("calendars/{PRIMARY}/events/{id}")))
668    }
669
670    async fn calendar_tz(&self) -> ProviderResult<String> {
671        if let Some(tz) = self.calendar_tz.lock().await.clone() {
672            return Ok(tz);
673        }
674        let list: EventList = self
675            .call(
676                Method::GET,
677                &self.cal(&format!("calendars/{PRIMARY}/events")),
678                &[("maxResults", "1".into())],
679                None,
680                "calendar",
681            )
682            .await?;
683        let tz = list.time_zone.unwrap_or_else(|| "UTC".into());
684        *self.calendar_tz.lock().await = Some(tz.clone());
685        Ok(tz)
686    }
687
688    async fn get_gevent(&self, id: &str) -> ProviderResult<GEvent> {
689        let url = self.event_url(id)?;
690        self.call(Method::GET, &url, &[], None, "event").await
691    }
692}
693
694fn all_ok_or(r: &ProviderResult<()>, n: usize) -> Vec<ProviderResult<()>> {
695    vec![r.clone(); n]
696}
697
698#[async_trait]
699impl Provider for GmailProvider {
700    fn kind(&self) -> ProviderKind {
701        ProviderKind::Google
702    }
703
704    fn address(&self) -> &str {
705        self.account()
706    }
707
708    async fn sync_mail(
709        &self,
710        since: DateTime<Utc>,
711        cursor: Option<&str>,
712    ) -> ProviderResult<MailSync> {
713        match cursor.map(SyncCursor::decode).transpose()? {
714            None => {
715                let profile: Profile = self
716                    .call(Method::GET, &self.gmail("profile"), &[], None, "profile")
717                    .await?;
718                self.bootstrap_page(since, profile.history_id, None).await
719            }
720            Some(CursorState::Bootstrap {
721                history_id,
722                page_token,
723            }) => {
724                self.bootstrap_page(since, history_id, Some(page_token))
725                    .await
726            }
727            Some(CursorState::History {
728                history_id,
729                page_token,
730            }) => self.history_page(since, history_id, page_token).await,
731        }
732    }
733
734    async fn search(&self, query: &SearchQuery) -> ProviderResult<Vec<MailItem>> {
735        let s = query::build(query);
736        let limit = if query.limit == 0 { 50 } else { query.limit };
737        let mut ids: Vec<String> = Vec::new();
738        let mut page: Option<String> = None;
739        loop {
740            let want = (limit - ids.len()).min(500) as u32;
741            let list = self
742                .list_messages(
743                    &s.q,
744                    page.as_deref(),
745                    want,
746                    s.label_id.as_deref(),
747                    s.include_spam_trash,
748                )
749                .await?;
750            ids.extend(list.messages.into_iter().map(|m| m.id));
751            match list.next_page_token {
752                Some(t) if ids.len() < limit => page = Some(t),
753                _ => break,
754            }
755        }
756        ids.truncate(limit);
757        self.items(&ids).await
758    }
759
760    async fn get_items(&self, ids: &[String]) -> ProviderResult<Vec<MailItem>> {
761        for id in ids {
762            check_id(id, "message")?;
763        }
764        self.items(ids).await
765    }
766
767    async fn get_message(&self, id: &str) -> ProviderResult<FullMessage> {
768        mime::full_message(self.account(), &self.get_raw(id).await?)
769    }
770
771    async fn get_thread(&self, thread_id: &str) -> ProviderResult<Vec<FullMessage>> {
772        let tid = check_id(thread_id, "thread")?;
773        let thread: ThreadResource = self
774            .call(
775                Method::GET,
776                &self.gmail(&format!("threads/{tid}")),
777                &[("format", "minimal".into())],
778                None,
779                "thread",
780            )
781            .await?;
782        let mut refs = thread.messages;
783        refs.sort_by_key(|m| m.received_at());
784        let fetched: Vec<ProviderResult<GmailMessage>> = stream::iter(refs)
785            .map(|m| async move { self.get_raw(&m.id).await })
786            .buffered(FETCH_CONCURRENCY)
787            .collect()
788            .await;
789        fetched
790            .into_iter()
791            .map(|r| r.and_then(|m| mime::full_message(self.account(), &m)))
792            .collect()
793    }
794
795    async fn message_headers(&self, id: &str) -> ProviderResult<Vec<(String, String)>> {
796        // Naming no header asks Gmail for all of them.
797        let m = self.get_metadata(id, &[]).await?;
798        Ok(m.payload
799            .map(|p| p.headers.into_iter().map(|h| (h.name, h.value)).collect())
800            .unwrap_or_default())
801    }
802
803    async fn unsubscribe_headers(&self, id: &str) -> ProviderResult<UnsubscribeHeaders> {
804        let m = self
805            .get_metadata(id, &["List-Unsubscribe", "List-Unsubscribe-Post"])
806            .await?;
807        Ok(UnsubscribeHeaders {
808            list_unsubscribe: m.header("List-Unsubscribe").map(str::to_string),
809            list_unsubscribe_post: m.header("List-Unsubscribe-Post").map(str::to_string),
810        })
811    }
812
813    async fn apply(&self, ids: &[String], change: &MailChange) -> Vec<ProviderResult<()>> {
814        let mut results: Vec<Option<ProviderResult<()>>> = ids
815            .iter()
816            .map(|id| check_id(id, "message").err().map(Err))
817            .collect();
818        let valid: Vec<(usize, String)> = ids
819            .iter()
820            .enumerate()
821            .filter(|(i, _)| results[*i].is_none())
822            .map(|(i, id)| (i, id.clone()))
823            .collect();
824        let valid_ids: Vec<String> = valid.iter().map(|(_, id)| id.clone()).collect();
825
826        let n = valid_ids.len();
827        let ids = &valid_ids;
828        let outcome: Vec<ProviderResult<()>> = match change {
829            MailChange::MarkRead => self.batch_modify(ids, &[], &["UNREAD"]).await,
830            MailChange::MarkUnread => self.batch_modify(ids, &["UNREAD"], &[]).await,
831            // Gmail stars have no due date.
832            MailChange::Flag { .. } => self.batch_modify(ids, &["STARRED"], &[]).await,
833            MailChange::Unflag => self.batch_modify(ids, &[], &["STARRED"]).await,
834            MailChange::Move { to } => match to {
835                Folder::Inbox => self.batch_modify(ids, &["INBOX"], &["SPAM", "TRASH"]).await,
836                Folder::Archive => {
837                    self.batch_modify(ids, &[], &["INBOX", "SPAM", "TRASH"])
838                        .await
839                }
840                Folder::Junk => self.batch_modify(ids, &["SPAM"], &["INBOX"]).await,
841                Folder::Other(label) => match check_id(label, "label") {
842                    Ok(l) => {
843                        self.batch_modify(ids, &[l], &["INBOX", "SPAM", "TRASH"])
844                            .await
845                    }
846                    Err(e) => all_ok_or(&Err(e), n),
847                },
848                Folder::Deleted => self.trash_all(ids).await,
849                Folder::Sent | Folder::Drafts => all_ok_or(
850                    &Err(ProviderError::Invalid(
851                        "Gmail cannot move mail into Sent or Drafts".into(),
852                    )),
853                    n,
854                ),
855            },
856            MailChange::Delete => self.trash_all(ids).await,
857            MailChange::SetCategories { categories } => {
858                let mut wanted: HashSet<String> = HashSet::new();
859                let mut failed = None;
860                for name in categories {
861                    match self.find_or_create_label(name).await {
862                        Ok(l) => {
863                            wanted.insert(l.id);
864                        }
865                        Err(e) => {
866                            failed = Some(e);
867                            break;
868                        }
869                    }
870                }
871                match failed {
872                    Some(e) => all_ok_or(&Err(e), n),
873                    None => self.set_categories_all(ids, wanted).await,
874                }
875            }
876        };
877
878        for ((i, _), r) in valid.iter().zip(outcome) {
879            results[*i] = Some(r);
880        }
881        results
882            .into_iter()
883            .map(|r| r.unwrap_or_else(|| Err(ProviderError::Other("no result".into()))))
884            .collect()
885    }
886
887    async fn list_folders(&self) -> ProviderResult<Vec<FolderInfo>> {
888        let labels = self.load_labels().await?;
889        let system = [
890            ("INBOX", Folder::Inbox, "Inbox"),
891            ("SENT", Folder::Sent, "Sent"),
892            ("DRAFT", Folder::Drafts, "Drafts"),
893            ("TRASH", Folder::Deleted, "Trash"),
894            ("SPAM", Folder::Junk, "Spam"),
895        ];
896        let mut wanted: Vec<(String, Folder, String)> = system
897            .iter()
898            .filter(|(id, _, _)| labels.contains_key(*id))
899            .map(|(id, f, name)| (id.to_string(), f.clone(), name.to_string()))
900            .collect();
901        let mut user: Vec<&Label> = labels.values().filter(|l| l.is_user()).collect();
902        user.sort_by_key(|l| l.name.to_lowercase());
903        wanted.extend(
904            user.into_iter()
905                .map(|l| (l.id.clone(), Folder::Other(l.id.clone()), l.name.clone())),
906        );
907        let fetched: Vec<ProviderResult<FolderInfo>> = stream::iter(wanted)
908            .map(|(id, folder, path)| async move {
909                let id = check_id(&id, "label")?.to_string();
910                let l: Label = self
911                    .call(
912                        Method::GET,
913                        &self.gmail(&format!("labels/{id}")),
914                        &[],
915                        None,
916                        "label",
917                    )
918                    .await?;
919                Ok(FolderInfo {
920                    folder,
921                    path,
922                    unread: l.messages_unread.unwrap_or(0),
923                    total: l.messages_total.unwrap_or(0),
924                })
925            })
926            .buffered(FETCH_CONCURRENCY)
927            .collect()
928            .await;
929        fetched.into_iter().collect()
930    }
931
932    async fn ensure_folder(&self, path: &str) -> ProviderResult<Folder> {
933        match Folder::from_key(path.trim()) {
934            Folder::Other(_) => {}
935            known => return Ok(known),
936        }
937        // Gmail label names nest with `/` natively.
938        Ok(Folder::Other(self.find_or_create_label(path).await?.id))
939    }
940
941    async fn list_categories(&self) -> ProviderResult<Vec<String>> {
942        let labels = self.load_labels().await?;
943        let mut names: Vec<String> = labels
944            .values()
945            .filter(|l| l.is_user())
946            .map(|l| l.name.clone())
947            .collect();
948        names.sort_by_key(|n| n.to_lowercase());
949        Ok(names)
950    }
951
952    async fn ensure_category(&self, name: &str) -> ProviderResult<()> {
953        self.find_or_create_label(name).await.map(|_| ())
954    }
955
956    async fn list_attachments(&self, id: &str) -> ProviderResult<Vec<Attachment>> {
957        let id = check_id(id, "message")?;
958        let m: GmailMessage = self
959            .call(
960                Method::GET,
961                &self.gmail(&format!("messages/{id}")),
962                &[("format", "full".into())],
963                None,
964                "message",
965            )
966            .await?;
967        let mut out = Vec::new();
968        if let Some(p) = &m.payload {
969            collect_attachments(p, &mut out);
970        }
971        Ok(out)
972    }
973
974    async fn attachment_bytes(&self, id: &str, attachment_id: &str) -> ProviderResult<Vec<u8>> {
975        let id = check_id(id, "message")?;
976        let att = check_id(attachment_id, "attachment")?;
977        let a: AttachmentData = self
978            .call(
979                Method::GET,
980                &self.gmail(&format!("messages/{id}/attachments/{att}")),
981                &[],
982                None,
983                "attachment",
984            )
985            .await?;
986        mime::decode_b64url(&a.data)
987    }
988
989    async fn create_draft(&self, spec: &DraftSpec) -> ProviderResult<Draft> {
990        let built = self.build(spec).await?;
991        let res: DraftResource = self
992            .call(
993                Method::POST,
994                &self.gmail("drafts"),
995                &[],
996                Some(&Self::draft_body(&built, None)),
997                "draft",
998            )
999            .await?;
1000        Ok(self.draft_of(res, built))
1001    }
1002
1003    async fn update_draft(&self, id: &str, spec: &DraftSpec) -> ProviderResult<Draft> {
1004        let id = check_id(id, "draft")?;
1005        let built = self.build(spec).await?;
1006        let res: DraftResource = self
1007            .call(
1008                Method::PUT,
1009                &self.gmail(&format!("drafts/{id}")),
1010                &[],
1011                Some(&Self::draft_body(&built, Some(id))),
1012                "draft",
1013            )
1014            .await?;
1015        Ok(self.draft_of(res, built))
1016    }
1017
1018    async fn get_draft(&self, id: &str) -> ProviderResult<Draft> {
1019        let id = check_id(id, "draft")?;
1020        let res: DraftResource = self
1021            .call(
1022                Method::GET,
1023                &self.gmail(&format!("drafts/{id}")),
1024                &[("format", "raw".into())],
1025                None,
1026                "draft",
1027            )
1028            .await?;
1029        let msg = res.message.unwrap_or_default();
1030        let p = mime::parse_draft(msg.raw.as_deref().unwrap_or(""))?;
1031        Ok(Draft {
1032            account: self.account().to_string(),
1033            id: res.id,
1034            thread_id: Some(msg.thread_id).filter(|t| !t.is_empty()),
1035            to: p.to,
1036            cc: p.cc,
1037            bcc: p.bcc,
1038            subject: p.subject,
1039            body_text: p.body_text,
1040            has_attachments: p.has_attachments,
1041        })
1042    }
1043
1044    async fn delete_draft(&self, id: &str) -> ProviderResult<()> {
1045        let id = check_id(id, "draft")?;
1046        self.call_empty(
1047            Method::DELETE,
1048            &self.gmail(&format!("drafts/{id}")),
1049            &[],
1050            None,
1051            "draft",
1052        )
1053        .await
1054    }
1055
1056    async fn send_draft(&self, id: &str) -> ProviderResult<()> {
1057        let id = check_id(id, "draft")?;
1058        self.call_empty(
1059            Method::POST,
1060            &self.gmail("drafts/send"),
1061            &[],
1062            Some(&json!({ "id": id })),
1063            "draft",
1064        )
1065        .await
1066    }
1067
1068    async fn list_events(
1069        &self,
1070        from: DateTime<Utc>,
1071        to: DateTime<Utc>,
1072    ) -> ProviderResult<Vec<Event>> {
1073        let mut out = Vec::new();
1074        let mut page: Option<String> = None;
1075        let mut tz: Option<String> = None;
1076        loop {
1077            let mut q: Vec<(&str, String)> = vec![
1078                ("singleEvents", "true".into()),
1079                ("orderBy", "startTime".into()),
1080                (
1081                    "timeMin",
1082                    from.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
1083                ),
1084                (
1085                    "timeMax",
1086                    to.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
1087                ),
1088                ("maxResults", "250".into()),
1089            ];
1090            if let Some(t) = &page {
1091                q.push(("pageToken", t.clone()));
1092            }
1093            let list: EventList = self
1094                .call(
1095                    Method::GET,
1096                    &self.cal(&format!("calendars/{PRIMARY}/events")),
1097                    &q,
1098                    None,
1099                    "calendar",
1100                )
1101                .await?;
1102            if tz.is_none() {
1103                tz = list.time_zone.clone();
1104                if let Some(z) = &tz {
1105                    *self.calendar_tz.lock().await = Some(z.clone());
1106                }
1107            }
1108            let zone = tz.clone().unwrap_or_else(|| "UTC".into());
1109            out.extend(
1110                list.items
1111                    .iter()
1112                    .filter(|e| e.status.as_deref() != Some("cancelled"))
1113                    .map(|e| calendar::to_event(self.account(), e, &zone)),
1114            );
1115            match list.next_page_token {
1116                Some(t) => page = Some(t),
1117                None => break,
1118            }
1119        }
1120        Ok(out)
1121    }
1122
1123    async fn get_event(&self, id: &str) -> ProviderResult<Event> {
1124        let g = self.get_gevent(id).await?;
1125        let tz = self.calendar_tz().await?;
1126        Ok(calendar::to_event(self.account(), &g, &tz))
1127    }
1128
1129    async fn create_event(&self, spec: &EventSpec) -> ProviderResult<Event> {
1130        let body = calendar::create_body(spec, &make_random(16));
1131        let mut q: Vec<(&str, String)> = vec![("sendUpdates", "all".into())];
1132        if spec.online_meeting {
1133            q.push(("conferenceDataVersion", "1".into()));
1134        }
1135        let g: GEvent = self
1136            .call(
1137                Method::POST,
1138                &self.cal(&format!("calendars/{PRIMARY}/events")),
1139                &q,
1140                Some(&body),
1141                "calendar",
1142            )
1143            .await?;
1144        let tz = self.calendar_tz().await?;
1145        Ok(calendar::to_event(self.account(), &g, &tz))
1146    }
1147
1148    async fn update_event(&self, id: &str, patch: &EventPatch) -> ProviderResult<Event> {
1149        let url = self.event_url(id)?;
1150        let current = if patch.attendees.is_some() {
1151            self.get_gevent(id).await?.attendees
1152        } else {
1153            Vec::new()
1154        };
1155        let body = calendar::patch_body(patch, &current, &make_random(16));
1156        let mut q: Vec<(&str, String)> = vec![("sendUpdates", "all".into())];
1157        if calendar::touches_conference(patch) {
1158            q.push(("conferenceDataVersion", "1".into()));
1159        }
1160        let g: GEvent = self
1161            .call(Method::PATCH, &url, &q, Some(&body), "event")
1162            .await?;
1163        let tz = self.calendar_tz().await?;
1164        Ok(calendar::to_event(self.account(), &g, &tz))
1165    }
1166
1167    /// Google has no cancellation message: attendees get Google's own
1168    /// cancellation notice and `message` is not sent.
1169    async fn cancel_event(&self, id: &str, _message: Option<&str>) -> ProviderResult<()> {
1170        let url = self.event_url(id)?;
1171        self.call_empty(
1172            Method::DELETE,
1173            &url,
1174            &[("sendUpdates", "all".into())],
1175            None,
1176            "event",
1177        )
1178        .await
1179    }
1180
1181    async fn delete_event(&self, id: &str) -> ProviderResult<()> {
1182        let url = self.event_url(id)?;
1183        self.call_empty(
1184            Method::DELETE,
1185            &url,
1186            &[("sendUpdates", "none".into())],
1187            None,
1188            "event",
1189        )
1190        .await
1191    }
1192
1193    async fn respond(
1194        &self,
1195        id: &str,
1196        response: Rsvp,
1197        message: Option<&str>,
1198        notify: bool,
1199    ) -> ProviderResult<()> {
1200        let url = self.event_url(id)?;
1201        let g = self.get_gevent(id).await?;
1202        let attendees = calendar::rsvp_attendees(&g.attendees, response, message)
1203            .ok_or_else(|| ProviderError::Invalid("you are not invited to this event".into()))?;
1204        let send = if notify { "all" } else { "none" };
1205        self.call_empty(
1206            Method::PATCH,
1207            &url,
1208            &[("sendUpdates", send.into())],
1209            Some(&json!({ "attendees": attendees })),
1210            "event",
1211        )
1212        .await
1213    }
1214
1215    async fn free_busy(
1216        &self,
1217        people: &[String],
1218        from: DateTime<Utc>,
1219        to: DateTime<Utc>,
1220    ) -> ProviderResult<Vec<(String, Vec<BusyBlock>)>> {
1221        if people.is_empty() {
1222            return Ok(Vec::new());
1223        }
1224        let body = json!({
1225            "timeMin": from.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
1226            "timeMax": to.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
1227            "items": people.iter().map(|p| json!({ "id": p })).collect::<Vec<_>>(),
1228        });
1229        let r: FreeBusyResponse = self
1230            .call(
1231                Method::POST,
1232                &self.cal("freeBusy"),
1233                &[],
1234                Some(&body),
1235                "free/busy",
1236            )
1237            .await?;
1238        let mut failed = 0;
1239        let out: Vec<(String, Vec<BusyBlock>)> = people
1240            .iter()
1241            .map(|p| {
1242                let cal = r
1243                    .calendars
1244                    .iter()
1245                    .find(|(k, _)| k.eq_ignore_ascii_case(p))
1246                    .map(|(_, v)| v);
1247                let blocks = match cal {
1248                    Some(c) if c.errors.is_empty() => c
1249                        .busy
1250                        .iter()
1251                        .map(|b| BusyBlock {
1252                            start: b.start,
1253                            end: b.end,
1254                        })
1255                        .collect(),
1256                    _ => {
1257                        failed += 1;
1258                        Vec::new()
1259                    }
1260                };
1261                (p.clone(), blocks)
1262            })
1263            .collect();
1264        if failed == people.len() {
1265            return Err(ProviderError::Unsupported(
1266                "Google shares no free/busy for these people".into(),
1267            ));
1268        }
1269        Ok(out)
1270    }
1271}
1272
1273/// Parts that carry an `attachmentId`, depth first. Note Gmail mints a new
1274/// attachment id on every fetch of a message; any of them stays usable.
1275fn collect_attachments(p: &Part, out: &mut Vec<Attachment>) {
1276    if let Some(att_id) = p.body.as_ref().and_then(|b| b.attachment_id.clone()) {
1277        let disposition = p.header("Content-Disposition").unwrap_or("");
1278        let content_id = p
1279            .header("Content-ID")
1280            .map(|c| {
1281                c.trim()
1282                    .trim_start_matches('<')
1283                    .trim_end_matches('>')
1284                    .to_string()
1285            })
1286            .filter(|c| !c.is_empty());
1287        let name = if p.filename.is_empty() {
1288            "attachment".to_string()
1289        } else {
1290            p.filename.clone()
1291        };
1292        out.push(Attachment {
1293            id: att_id,
1294            name,
1295            content_type: p.mime_type.clone(),
1296            size_bytes: p.body.as_ref().map(|b| b.size).unwrap_or(0),
1297            is_inline: disposition
1298                .trim_start()
1299                .to_ascii_lowercase()
1300                .starts_with("inline"),
1301            content_id,
1302        });
1303    }
1304    for c in &p.parts {
1305        collect_attachments(c, out);
1306    }
1307}