himalaya 2.2.1

CLI to manage emails
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! # Microsoft Graph backend
//!
//! The Graph adapter of the shared cross-protocol client, glue over the
//! io-msgraph client [`MsgraphClient`] wraps.
//!
//! Graph is folder-based, and a shared flag maps onto a scalar field of
//! the message, `isRead` or the follow-up flag, or onto its categories.
//! There is no `add_message`: a MIME message Graph creates stays a draft.

use std::collections::BTreeSet;

use anyhow::{Context, Result};
use chrono::{DateTime, FixedOffset};
use io_msgraph::v1::{
    rest::{
        batch::MsgraphBatchRequest,
        users::{
            mail_folders::{MsgraphMailFolder, list::MsgraphMailFoldersListParams},
            messages::{
                MsgraphFlagStatus, MsgraphFollowupFlag, MsgraphImportance, MsgraphMessage,
                MsgraphRecipient,
                list::{MsgraphMessagesListParams, MsgraphMessagesListResponse},
            },
        },
    },
    send::{MsgraphSend, user_path},
};
use url::Url;

use crate::{
    email::{
        address::Address,
        envelope::{Envelope, normalize_message_id},
        flag::{Flag, FlagOp, IanaFlag},
        mailbox::{Mailbox, MailboxRole},
        search::{eval::sort_envelopes, query::SearchEmailsQuery},
    },
    msgraph::{client::MsgraphClient, search},
};

/// OData `$select` for envelope listing: the message fields backing the
/// shared [`Envelope`], returned in one round-trip.
const ENVELOPE_SELECT: &str = "id,subject,from,toRecipients,receivedDateTime,isRead,isDraft,hasAttachments,internetMessageId,importance,flag,categories";

/// The well-known folder names carrying a special-use role, a stable Graph
/// contract accepted in place of a folder id.
const WELL_KNOWN_FOLDERS: [(&str, MailboxRole); 6] = [
    ("inbox", MailboxRole::Inbox),
    ("sentitems", MailboxRole::Sent),
    ("drafts", MailboxRole::Drafts),
    ("deleteditems", MailboxRole::Trash),
    ("junkemail", MailboxRole::Junk),
    ("archive", MailboxRole::Archive),
];

impl MsgraphClient {
    /// Lists every Graph mail folder as a mailbox. Graph carries counts
    /// inline, so `with_counts` is ignored.
    pub fn list_mailboxes(&mut self, _with_counts: bool) -> Result<Vec<Mailbox>> {
        let params = MsgraphMailFoldersListParams {
            top: Some(100),
            ..Default::default()
        };
        let folders = self.mail_folders_list(&params)?.response.value;
        let roles = self.folder_roles()?;

        Ok(folders
            .into_iter()
            .map(|folder| {
                let role = roles
                    .iter()
                    .find(|(id, _)| *id == folder.id)
                    .map(|(_, role)| role.clone());
                mailbox_from(folder, role)
            })
            .collect())
    }

    /// Resolves the well-known folder names to folder ids in one `$batch`,
    /// since Graph v1.0 lists folders without them. A name the mailbox
    /// lacks, such as `archive`, is skipped.
    fn folder_roles(&mut self) -> Result<Vec<(String, MailboxRole)>> {
        let user = user_path(&self.user_id);
        let requests: Vec<_> = WELL_KNOWN_FOLDERS
            .iter()
            .map(|(name, _)| MsgraphBatchRequest {
                id: name.to_string(),
                method: "GET".into(),
                url: format!("/{user}/mailFolders/{name}?$select=id"),
                ..Default::default()
            })
            .collect();

        let mut roles = Vec::new();

        for response in self.batch(&requests)?.response.responses {
            let Some((_, role)) = WELL_KNOWN_FOLDERS
                .iter()
                .find(|(name, _)| *name == response.id)
            else {
                continue;
            };

            if let Ok(folder) = response.parse::<MsgraphMailFolder>() {
                roles.push((folder.id, role.clone()));
            }
        }

        Ok(roles)
    }

    /// Lists envelopes from the `mailbox` folder (id or well-known name
    /// such as `inbox`). Page 1 is the most recent window; the offset is
    /// `(page - 1) * page_size` via OData `$skip`.
    pub fn list_envelopes(
        &mut self,
        mailbox: &str,
        page: Option<u32>,
        page_size: Option<u32>,
        _with_attachment: bool,
    ) -> Result<Vec<Envelope>> {
        let page = page.unwrap_or(1).max(1);
        let (top, skip) = match page_size {
            Some(size) => (Some(size), Some((page - 1) * size)),
            None => (None, None),
        };

        let params = MsgraphMessagesListParams {
            top,
            skip,
            select: Some(ENVELOPE_SELECT),
            ..Default::default()
        };
        let messages = self.messages_list(Some(mailbox), &params)?.response.value;

        Ok(messages.into_iter().map(envelope_from).collect())
    }

    /// Searches the `mailbox` folder with the shared query, its filter
    /// translated to a KQL `$search`.
    ///
    /// Graph refuses `$skip` and `$orderby` beside `$search`, so a page is
    /// reached through the paging links and sorted locally, newest first
    /// by default since Graph answers in relevance order.
    pub fn search_envelopes(
        &mut self,
        mailbox: &str,
        query: Option<&SearchEmailsQuery>,
        page: Option<u32>,
        page_size: Option<u32>,
        with_attachment: bool,
    ) -> Result<Vec<Envelope>> {
        let sort = query.and_then(|query| query.sort.as_deref());

        let Some(filter) = query.and_then(|query| query.filter.as_ref()) else {
            let mut envelopes = self.list_envelopes(mailbox, page, page_size, with_attachment)?;
            sort_envelopes(&mut envelopes, sort);
            return Ok(envelopes);
        };

        let search = search::filter_to_search(filter)?;
        let params = MsgraphMessagesListParams {
            top: page_size,
            select: Some(ENVELOPE_SELECT),
            search: Some(&search),
            ..Default::default()
        };
        let mut response = self.messages_list(Some(mailbox), &params)?.response;

        for _ in 1..page.unwrap_or(1).max(1) {
            let Some(next) = response.next_link else {
                return Ok(Vec::new());
            };
            let url = Url::parse(&next).context("Cannot parse the message paging link")?;
            let coroutine = MsgraphSend::<MsgraphMessagesListResponse>::get(&self.auth, url);
            response = self.run(coroutine)?.response;
        }

        let mut envelopes: Vec<Envelope> = response.value.into_iter().map(envelope_from).collect();
        sort_envelopes(&mut envelopes, sort);

        Ok(envelopes)
    }

    /// Adds, sets, or removes `flags` on a message id set via one
    /// `PATCH /messages/{id}` per id. `mailbox` is unused.
    pub fn store_flags(
        &mut self,
        _mailbox: &str,
        ids: &[&str],
        flags: &[Flag],
        op: FlagOp,
    ) -> Result<()> {
        let patch = flag_patch(flags, op);
        for id in ids {
            self.message_update(id, &patch)?;
        }
        Ok(())
    }

    /// Fetches one message's raw RFC 5322 bytes via
    /// `GET /messages/{id}/$value`. `mailbox` is unused.
    pub fn get_message(&mut self, mailbox: &str, id: &str, seen: bool) -> Result<Vec<u8>> {
        let raw = self.message_get_raw(id)?.response;

        // NOTE: fetching `$value` never changes read state, so `--seen`
        // costs a separate PATCH setting `isRead`.
        if seen {
            let seen = Flag::from_iana(IanaFlag::Seen);
            self.store_flags(mailbox, &[id], &[seen], FlagOp::Add)?;
        }

        Ok(raw)
    }

    /// Copies a message id set into `to`. `from` is unused.
    pub fn copy_messages(&mut self, _from: &str, to: &str, ids: &[&str]) -> Result<usize> {
        for id in ids {
            self.message_copy(id, to)?;
        }
        Ok(ids.len())
    }

    /// Moves a message id set into `to`. `from` is unused.
    pub fn move_messages(&mut self, _from: &str, to: &str, ids: &[&str]) -> Result<usize> {
        for id in ids {
            self.message_move(id, to)?;
        }
        Ok(ids.len())
    }

    /// Permanently deletes `ids` (`DELETE /messages/{id}`; from Deleted
    /// Items this is a hard delete).
    pub fn delete_messages(&mut self, ids: &[&str]) -> Result<()> {
        for id in ids {
            self.message_delete(id)?;
        }
        Ok(())
    }

    /// Sends a raw RFC 5322 message via `POST /sendMail` (MIME form);
    /// Graph saves it to Sent Items.
    pub fn send_message(&mut self, raw: Vec<u8>) -> Result<()> {
        self.mail_send_mime(&raw)?;
        Ok(())
    }
}

/// Converts one Graph mail folder into the shared [`Mailbox`] shape;
/// Graph folders carry their counts inline.
fn mailbox_from(folder: MsgraphMailFolder, role: Option<MailboxRole>) -> Mailbox {
    Mailbox {
        id: folder.id,
        name: folder.display_name,
        role,
        total: folder.total_item_count,
        unread: folder.unread_item_count,
    }
}

/// Folds a Graph message into the shared [`Envelope`] shape. `size` is
/// left `0`: the listing selection does not expose a raw size.
fn envelope_from(message: MsgraphMessage) -> Envelope {
    let flags = flags_from_message(&message);
    let message_id = message
        .internet_message_id
        .as_deref()
        .and_then(normalize_message_id);
    let date = message
        .received_date_time
        .as_deref()
        .and_then(parse_rfc3339);
    let from = message.from.map(address_from).into_iter().collect();
    let to = message
        .to_recipients
        .into_iter()
        .map(address_from)
        .collect();

    Envelope {
        id: message.id,
        message_id,
        // NOTE: Graph carries In-Reply-To inside `internetMessageHeaders`
        // alone, which a listing does not select, so the field stays
        // empty rather than cost one request per row.
        in_reply_to: Vec::new(),
        flags,
        subject: message.subject.unwrap_or_default(),
        from,
        to,
        date,
        size: 0,
        has_attachment: message.has_attachments,
    }
}

/// Builds the message PATCH body applying `flags` under `op`. `Set`
/// drives every scalar flag-field to its target and replaces
/// `categories`; `Add`/`Remove` only touch the scalar fields mentioned.
fn flag_patch(flags: &[Flag], op: FlagOp) -> MsgraphMessage {
    let mut patch = MsgraphMessage::default();

    match op {
        FlagOp::Set => {
            patch.is_read = Some(flags.iter().any(Flag::is_seen));
            patch.flag = Some(followup(flags.iter().any(Flag::is_flagged)));
            patch.importance = Some(importance(flags.iter().any(Flag::is_important)));
            patch.categories = flags
                .iter()
                .filter(|flag| flag.iana().is_none())
                .map(|flag| flag.raw().to_string())
                .collect();
        }
        FlagOp::Add => {
            for flag in flags {
                if flag.is_seen() {
                    patch.is_read = Some(true);
                }
                if flag.is_flagged() {
                    patch.flag = Some(followup(true));
                }
                if flag.is_important() {
                    patch.importance = Some(MsgraphImportance::High);
                }
            }
        }
        FlagOp::Remove => {
            for flag in flags {
                if flag.is_seen() {
                    patch.is_read = Some(false);
                }
                if flag.is_flagged() {
                    patch.flag = Some(followup(false));
                }
                if flag.is_important() {
                    patch.importance = Some(MsgraphImportance::Normal);
                }
            }
        }
    }

    patch
}

/// Derives the shared flag set from a Graph message's scalar fields and
/// categories.
fn flags_from_message(message: &MsgraphMessage) -> BTreeSet<Flag> {
    let mut flags = BTreeSet::new();

    if message.is_read == Some(true) {
        flags.insert(Flag::from_iana(IanaFlag::Seen));
    }
    if matches!(
        message.flag.as_ref().and_then(|flag| flag.flag_status),
        Some(MsgraphFlagStatus::Flagged)
    ) {
        flags.insert(Flag::from_iana(IanaFlag::Flagged));
    }
    if message.importance == Some(MsgraphImportance::High) {
        flags.insert(Flag::from_iana(IanaFlag::Important));
    }
    if message.is_draft == Some(true) {
        flags.insert(Flag::from_iana(IanaFlag::Draft));
    }
    for category in &message.categories {
        flags.insert(Flag::from_raw(category.clone()));
    }

    flags
}

/// Converts a Graph recipient into a shared [`Address`].
fn address_from(recipient: MsgraphRecipient) -> Address {
    Address {
        name: recipient.email_address.name,
        email: recipient.email_address.address.unwrap_or_default(),
    }
}

/// Maps the shared `\Flagged` onto a Graph follow-up flag.
fn followup(flagged: bool) -> MsgraphFollowupFlag {
    let flag_status = if flagged {
        MsgraphFlagStatus::Flagged
    } else {
        MsgraphFlagStatus::NotFlagged
    };
    MsgraphFollowupFlag {
        flag_status: Some(flag_status),
    }
}

/// Maps the shared `$Important` onto a Graph importance.
fn importance(important: bool) -> MsgraphImportance {
    if important {
        MsgraphImportance::High
    } else {
        MsgraphImportance::Normal
    }
}

/// Parses the RFC 3339 timestamp Graph reports a date with.
fn parse_rfc3339(raw: &str) -> Option<DateTime<FixedOffset>> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    DateTime::parse_from_rfc3339(trimmed).ok()
}