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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! # Email client
//!
//! The cross-protocol client every shared subcommand runs over: one
//! storage backend, plus an SMTP transport for the backends that cannot
//! send.
//!
//! The storage backend is the first configured one `--backend` allows,
//! local before network. Each method matches on it and calls that
//! protocol's adapter, which takes and returns the CLI's own
//! [`crate::email`] types.
//!
//! The active [`Account`] is threaded as a sibling argument through every
//! `execute` chain rather than bundled into the client.

#[cfg(feature = "smtp")]
use std::mem;

use anyhow::{Result, anyhow, bail};

#[cfg(feature = "gmail")]
use crate::gmail::client::GmailClient;
#[cfg(feature = "imap")]
use crate::imap::client::ImapClient;
#[cfg(feature = "jmap")]
use crate::jmap::client::JmapClient;
#[cfg(feature = "m2dir")]
use crate::m2dir::client::M2dirClient;
#[cfg(feature = "maildir")]
use crate::maildir::client::MaildirClient;
#[cfg(feature = "mbox")]
use crate::mbox::client::MboxClient;
#[cfg(feature = "msgraph")]
use crate::msgraph::client::MsgraphClient;
#[cfg(feature = "pimdir")]
use crate::pimdir::client::PimdirClient;
// NOTE: the mailbox types carry the same `backend` gate as the methods
// dispatching on them, where `Flag` also serves the ungated send path.
#[cfg(backend)]
use crate::email::{
    envelope::Envelope,
    flag::FlagOp,
    mailbox::{Mailbox, MailboxRole},
    search::query::SearchEmailsQuery,
};
use crate::{
    account::context::Account,
    backend::Backend,
    config::{AccountConfig, Config},
    email::flag::Flag,
};
#[cfg(feature = "smtp")]
use crate::{config::SmtpConfig, smtp::client::SmtpClient};

/// The client every shared subcommand runs over.
pub struct EmailClient {
    storage: Option<BackendClient>,
    #[cfg(feature = "smtp")]
    smtp: SmtpTransport,
}

/// The SMTP transport, connected on the first send so a read-only command
/// opens no SMTP connection.
#[cfg(feature = "smtp")]
enum SmtpTransport {
    /// No SMTP configured, or `--backend` excluded it.
    Absent,
    /// Configured but not connected yet.
    Pending(Box<SmtpConfig>),
    /// Connected.
    Ready(SmtpClient),
}

/// The active storage backend, one of the compiled-in per-protocol
/// clients.
enum BackendClient {
    #[cfg(feature = "imap")]
    Imap(Box<ImapClient>),
    #[cfg(feature = "jmap")]
    Jmap(Box<JmapClient>),
    #[cfg(feature = "gmail")]
    Gmail(Box<GmailClient>),
    #[cfg(feature = "msgraph")]
    Msgraph(Box<MsgraphClient>),
    #[cfg(feature = "maildir")]
    Maildir(Box<MaildirClient>),
    #[cfg(feature = "m2dir")]
    M2dir(Box<M2dirClient>),
    #[cfg(feature = "mbox")]
    Mbox(Box<MboxClient>),
    #[cfg(feature = "pimdir")]
    Pimdir(Box<PimdirClient>),
}

impl EmailClient {
    /// Opens the connections of the active account, bailing when nothing
    /// usable is configured.
    pub fn new(
        config: Config,
        name: &str,
        #[allow(unused_mut)] mut account_config: AccountConfig,
        backend: Backend,
    ) -> Result<(Account, Self)> {
        let storage = select_storage(&mut account_config, backend)?;

        // NOTE: left unconnected, so a read-only command opens no SMTP
        // connection and a single-session proxy serves storage alone.
        #[cfg(feature = "smtp")]
        let smtp = match (backend.allows_smtp(), account_config.smtp.take()) {
            (true, Some(config)) => SmtpTransport::Pending(Box::new(config)),
            _ => SmtpTransport::Absent,
        };

        #[cfg(feature = "smtp")]
        let has_transport = storage.is_some() || !matches!(smtp, SmtpTransport::Absent);
        #[cfg(not(feature = "smtp"))]
        let has_transport = storage.is_some();
        if !has_transport {
            // NOTE: ManageSieve holds no mailbox, so no shared command runs on it.
            let supported: Vec<Backend> = Backend::COMPILED
                .iter()
                .copied()
                .filter(|b| *b != Backend::Sieve)
                .collect();

            return Err(account_config.no_backend_error(name, backend, &supported));
        }

        let account = Account::from(config).merge(Account::from(account_config));

        Ok((
            account,
            Self {
                storage,
                #[cfg(feature = "smtp")]
                smtp,
            },
        ))
    }

    /// Lists every mailbox available to the active account.
    #[cfg(backend)]
    pub fn list_mailboxes(&mut self, with_counts: bool) -> Result<Vec<Mailbox>> {
        match self.storage_mut()? {
            #[cfg(feature = "imap")]
            BackendClient::Imap(client) => client.list_mailboxes(with_counts),
            #[cfg(feature = "jmap")]
            BackendClient::Jmap(client) => client.list_mailboxes(with_counts),
            #[cfg(feature = "gmail")]
            BackendClient::Gmail(client) => client.list_mailboxes(with_counts),
            #[cfg(feature = "msgraph")]
            BackendClient::Msgraph(client) => client.list_mailboxes(with_counts),
            #[cfg(feature = "maildir")]
            BackendClient::Maildir(client) => client.list_mailboxes(with_counts),
            #[cfg(feature = "m2dir")]
            BackendClient::M2dir(client) => client.list_mailboxes(with_counts),
            #[cfg(feature = "mbox")]
            BackendClient::Mbox(client) => client.list_mailboxes(with_counts),
            #[cfg(feature = "pimdir")]
            BackendClient::Pimdir(client) => client.list_mailboxes(with_counts),
        }
    }

    /// Lists envelopes from `mailbox`.
    #[cfg(backend)]
    pub fn list_envelopes(
        &mut self,
        mailbox: &str,
        page: Option<u32>,
        page_size: Option<u32>,
        with_attachment: bool,
    ) -> Result<Vec<Envelope>> {
        let mailbox = self.resolve_mailbox_id(mailbox)?;
        let mailbox = mailbox.as_str();
        match self.storage_mut()? {
            #[cfg(feature = "imap")]
            BackendClient::Imap(client) => {
                client.list_envelopes(mailbox, page, page_size, with_attachment)
            }
            #[cfg(feature = "jmap")]
            BackendClient::Jmap(client) => {
                client.list_envelopes(mailbox, page, page_size, with_attachment)
            }
            #[cfg(feature = "gmail")]
            BackendClient::Gmail(client) => {
                client.list_envelopes(mailbox, page, page_size, with_attachment)
            }
            #[cfg(feature = "msgraph")]
            BackendClient::Msgraph(client) => {
                client.list_envelopes(mailbox, page, page_size, with_attachment)
            }
            #[cfg(feature = "maildir")]
            BackendClient::Maildir(client) => {
                client.list_envelopes(mailbox, page, page_size, with_attachment)
            }
            #[cfg(feature = "m2dir")]
            BackendClient::M2dir(client) => {
                client.list_envelopes(mailbox, page, page_size, with_attachment)
            }
            #[cfg(feature = "mbox")]
            BackendClient::Mbox(client) => {
                client.list_envelopes(mailbox, page, page_size, with_attachment)
            }
            #[cfg(feature = "pimdir")]
            BackendClient::Pimdir(client) => {
                client.list_envelopes(mailbox, page, page_size, with_attachment)
            }
        }
    }

    /// How many messages the mailbox has staged for creation and not
    /// pushed yet.
    ///
    /// Zero for every backend whose writes reach the server as they are
    /// made. A pimdir store is a replica a sync engine owns, so a saved
    /// message waits in its queue with no id and therefore no envelope,
    /// and the count is what keeps it from reading as lost.
    #[cfg(feature = "pimdir")]
    pub fn queued_messages(&mut self, mailbox: &str) -> Result<usize> {
        let mailbox = self.resolve_mailbox_id(mailbox)?;
        let mailbox = mailbox.as_str();
        match self.storage_mut()? {
            BackendClient::Pimdir(client) => client.queued_messages(mailbox),
            #[allow(unreachable_patterns)]
            _ => Ok(0),
        }
    }

    /// How many messages the mailbox has staged for creation and not
    /// pushed yet, always zero without the pimdir backend.
    #[cfg(all(backend, not(feature = "pimdir")))]
    pub fn queued_messages(&mut self, _mailbox: &str) -> Result<usize> {
        Ok(0)
    }

    /// Searches a mailbox with the shared query.
    #[cfg(backend)]
    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 mailbox = self.resolve_mailbox_id(mailbox)?;
        let mailbox = mailbox.as_str();
        match self.storage_mut()? {
            #[cfg(feature = "imap")]
            BackendClient::Imap(client) => {
                client.search_envelopes(mailbox, query, page, page_size, with_attachment)
            }
            #[cfg(feature = "jmap")]
            BackendClient::Jmap(client) => {
                client.search_envelopes(mailbox, query, page, page_size, with_attachment)
            }
            #[cfg(feature = "maildir")]
            BackendClient::Maildir(client) => {
                client.search_envelopes(mailbox, query, page, page_size, with_attachment)
            }
            #[cfg(feature = "m2dir")]
            BackendClient::M2dir(client) => {
                client.search_envelopes(mailbox, query, page, page_size, with_attachment)
            }
            #[cfg(feature = "mbox")]
            BackendClient::Mbox(client) => {
                client.search_envelopes(mailbox, query, page, page_size, with_attachment)
            }
            #[cfg(feature = "pimdir")]
            BackendClient::Pimdir(client) => {
                client.search_envelopes(mailbox, query, page, page_size, with_attachment)
            }
            #[cfg(feature = "gmail")]
            BackendClient::Gmail(client) => {
                client.search_envelopes(mailbox, query, page, page_size, with_attachment)
            }
            #[cfg(feature = "msgraph")]
            BackendClient::Msgraph(client) => {
                client.search_envelopes(mailbox, query, page, page_size, with_attachment)
            }
        }
    }

    /// Adds, sets or removes flags on a set of messages.
    #[cfg(backend)]
    pub fn store_flags(
        &mut self,
        mailbox: &str,
        ids: &[&str],
        flags: &[Flag],
        op: FlagOp,
    ) -> Result<()> {
        let mailbox = self.resolve_mailbox_id(mailbox)?;
        let mailbox = mailbox.as_str();
        match self.storage_mut()? {
            #[cfg(feature = "imap")]
            BackendClient::Imap(client) => client.store_flags(mailbox, ids, flags, op),
            #[cfg(feature = "jmap")]
            BackendClient::Jmap(client) => client.store_flags(mailbox, ids, flags, op),
            #[cfg(feature = "gmail")]
            BackendClient::Gmail(client) => client.store_flags(mailbox, ids, flags, op),
            #[cfg(feature = "msgraph")]
            BackendClient::Msgraph(client) => client.store_flags(mailbox, ids, flags, op),
            #[cfg(feature = "maildir")]
            BackendClient::Maildir(client) => client.store_flags(mailbox, ids, flags, op),
            #[cfg(feature = "m2dir")]
            BackendClient::M2dir(client) => client.store_flags(mailbox, ids, flags, op),
            #[cfg(feature = "mbox")]
            BackendClient::Mbox(client) => client.store_flags(mailbox, ids, flags, op),
            #[cfg(feature = "pimdir")]
            BackendClient::Pimdir(client) => client.store_flags(mailbox, ids, flags, op),
        }
    }

    /// Fetches one message's raw RFC 5322 bytes, marking it seen when
    /// asked.
    ///
    /// IMAP folds the flag into the fetch itself, where the other
    /// backends issue a separate update.
    #[cfg(backend)]
    pub fn get_message(&mut self, mailbox: &str, id: &str, seen: bool) -> Result<Vec<u8>> {
        match self.storage_mut()? {
            #[cfg(feature = "imap")]
            BackendClient::Imap(client) => client.get_message(mailbox, id, seen),
            #[cfg(feature = "jmap")]
            BackendClient::Jmap(client) => client.get_message(mailbox, id, seen),
            #[cfg(feature = "gmail")]
            BackendClient::Gmail(client) => client.get_message(mailbox, id, seen),
            #[cfg(feature = "msgraph")]
            BackendClient::Msgraph(client) => client.get_message(mailbox, id, seen),
            #[cfg(feature = "maildir")]
            BackendClient::Maildir(client) => client.get_message(mailbox, id, seen),
            #[cfg(feature = "m2dir")]
            BackendClient::M2dir(client) => client.get_message(mailbox, id, seen),
            #[cfg(feature = "mbox")]
            BackendClient::Mbox(client) => client.get_message(mailbox, id, seen),
            #[cfg(feature = "pimdir")]
            BackendClient::Pimdir(client) => client.get_message(mailbox, id, seen),
        }
    }

    /// Adds a raw message to a mailbox with the given flags, which Gmail
    /// and Microsoft Graph do not implement. Returns the new message id,
    /// absent when an IMAP or JMAP server does not report it.
    pub fn add_message(
        &mut self,
        mailbox: &str,
        flags: &[Flag],
        raw: Vec<u8>,
    ) -> Result<Option<String>> {
        let mailbox = self.resolve_mailbox_id(mailbox)?;
        let mailbox = mailbox.as_str();
        match self.storage_mut()? {
            #[cfg(feature = "imap")]
            BackendClient::Imap(client) => client.add_message(mailbox, flags, raw),
            #[cfg(feature = "jmap")]
            BackendClient::Jmap(client) => client.add_message(mailbox, flags, raw),
            #[cfg(feature = "maildir")]
            BackendClient::Maildir(client) => client.add_message(mailbox, flags, raw).map(Some),
            #[cfg(feature = "m2dir")]
            BackendClient::M2dir(client) => client.add_message(mailbox, flags, raw).map(Some),
            #[cfg(feature = "mbox")]
            BackendClient::Mbox(client) => client.add_message(mailbox, flags, raw).map(Some),
            #[cfg(feature = "pimdir")]
            BackendClient::Pimdir(client) => client.add_message(mailbox, flags, raw).map(Some),
            #[cfg(feature = "gmail")]
            BackendClient::Gmail(client) => client.add_message(mailbox, flags, raw).map(Some),
            #[cfg(feature = "msgraph")]
            BackendClient::Msgraph(_) => bail!("Microsoft Graph does not support adding messages"),
            // NOTE: `storage_mut` bails first in a send-only build, so
            // this arm only keeps the match exhaustive over an empty enum.
            #[cfg(not(backend))]
            _ => bail!("No storage backend is configured for this account"),
        }
    }

    /// Copies messages between two mailboxes, returning how many landed.
    #[cfg(backend)]
    pub fn copy_messages(&mut self, from: &str, to: &str, ids: &[&str]) -> Result<usize> {
        let from = self.resolve_mailbox_id(from)?;
        let to = self.resolve_mailbox_id(to)?;
        let (from, to) = (from.as_str(), to.as_str());
        match self.storage_mut()? {
            #[cfg(feature = "imap")]
            BackendClient::Imap(client) => client.copy_messages(from, to, ids),
            #[cfg(feature = "jmap")]
            BackendClient::Jmap(client) => client.copy_messages(from, to, ids),
            #[cfg(feature = "gmail")]
            BackendClient::Gmail(client) => client.copy_messages(from, to, ids),
            #[cfg(feature = "msgraph")]
            BackendClient::Msgraph(client) => client.copy_messages(from, to, ids),
            #[cfg(feature = "maildir")]
            BackendClient::Maildir(client) => client.copy_messages(from, to, ids),
            #[cfg(feature = "m2dir")]
            BackendClient::M2dir(client) => client.copy_messages(from, to, ids),
            #[cfg(feature = "mbox")]
            BackendClient::Mbox(client) => client.copy_messages(from, to, ids),
            #[cfg(feature = "pimdir")]
            BackendClient::Pimdir(client) => client.copy_messages(from, to, ids),
        }
    }

    /// Moves messages between two mailboxes, returning how many landed.
    #[cfg(backend)]
    pub fn move_messages(&mut self, from: &str, to: &str, ids: &[&str]) -> Result<usize> {
        let from = self.resolve_mailbox_id(from)?;
        let to = self.resolve_mailbox_id(to)?;
        let (from, to) = (from.as_str(), to.as_str());
        match self.storage_mut()? {
            #[cfg(feature = "imap")]
            BackendClient::Imap(client) => client.move_messages(from, to, ids),
            #[cfg(feature = "jmap")]
            BackendClient::Jmap(client) => client.move_messages(from, to, ids),
            #[cfg(feature = "gmail")]
            BackendClient::Gmail(client) => client.move_messages(from, to, ids),
            #[cfg(feature = "msgraph")]
            BackendClient::Msgraph(client) => client.move_messages(from, to, ids),
            #[cfg(feature = "maildir")]
            BackendClient::Maildir(client) => client.move_messages(from, to, ids),
            #[cfg(feature = "m2dir")]
            BackendClient::M2dir(client) => client.move_messages(from, to, ids),
            #[cfg(feature = "mbox")]
            BackendClient::Mbox(client) => client.move_messages(from, to, ids),
            #[cfg(feature = "pimdir")]
            BackendClient::Pimdir(client) => client.move_messages(from, to, ids),
        }
    }

    /// The id of the mailbox the backend marks with `role`, `None` when it
    /// marks none.
    ///
    /// JMAP, Gmail and Graph carry roles, IMAP only the reserved `INBOX`
    /// until SPECIAL-USE is read, mbox the spool as `INBOX`, and Maildir,
    /// m2dir and pimdir none, the caller falling back on the
    /// `mailbox.alias.<role>` entry.
    #[cfg(backend)]
    pub fn role_mailbox_id(&mut self, role: &MailboxRole) -> Result<Option<String>> {
        match self.storage_mut()? {
            #[cfg(feature = "imap")]
            BackendClient::Imap(_) => {
                Ok((*role == MailboxRole::Inbox).then(|| String::from("INBOX")))
            }
            #[cfg(feature = "jmap")]
            BackendClient::Jmap(client) => client.role_mailbox_id(role),
            #[cfg(feature = "gmail")]
            BackendClient::Gmail(client) => client.role_mailbox_id(role),
            #[cfg(feature = "msgraph")]
            BackendClient::Msgraph(client) => client.role_mailbox_id(role),
            #[cfg(feature = "maildir")]
            BackendClient::Maildir(_) => Ok(None),
            #[cfg(feature = "m2dir")]
            BackendClient::M2dir(_) => Ok(None),
            #[cfg(feature = "mbox")]
            BackendClient::Mbox(client) => Ok(client.role_mailbox_id(role)),
            #[cfg(feature = "pimdir")]
            BackendClient::Pimdir(_) => Ok(None),
        }
    }

    /// Permanently deletes messages from the trash.
    ///
    /// Returns whether they were really removed, an IMAP server without
    /// UIDPLUS only flagging them `\Deleted`.
    #[cfg(backend)]
    pub fn delete_messages(&mut self, mailbox: &str, ids: &[&str]) -> Result<bool> {
        match self.storage_mut()? {
            #[cfg(feature = "imap")]
            BackendClient::Imap(client) => client.delete_messages(mailbox, ids),
            #[cfg(feature = "jmap")]
            BackendClient::Jmap(client) => client.delete_messages(ids).map(|()| true),
            #[cfg(feature = "gmail")]
            BackendClient::Gmail(client) => client.delete_messages(ids).map(|()| true),
            #[cfg(feature = "msgraph")]
            BackendClient::Msgraph(client) => client.delete_messages(ids).map(|()| true),
            #[cfg(feature = "maildir")]
            BackendClient::Maildir(client) => client.delete_messages(mailbox, ids).map(|()| true),
            #[cfg(feature = "m2dir")]
            BackendClient::M2dir(client) => client.delete_messages(mailbox, ids).map(|()| true),
            #[cfg(feature = "mbox")]
            BackendClient::Mbox(client) => client.delete_messages(mailbox, ids).map(|()| true),
            #[cfg(feature = "pimdir")]
            BackendClient::Pimdir(client) => client.delete_messages(mailbox, ids).map(|()| true),
        }
    }

    /// Sends a raw message through the storage backend when it can send,
    /// and through the SMTP transport otherwise.
    ///
    /// A backend that defers the send to its store's owner files it under
    /// `mailbox` and returns the queue row id; every other one sends at
    /// once, ignores `mailbox` and returns `None`.
    #[cfg_attr(not(feature = "pimdir"), allow(unused_variables))]
    pub fn send_message(&mut self, mailbox: Option<&str>, raw: Vec<u8>) -> Result<Option<i64>> {
        match &mut self.storage {
            #[cfg(feature = "jmap")]
            Some(BackendClient::Jmap(client)) => return client.send_message(raw).map(|()| None),
            #[cfg(feature = "gmail")]
            Some(BackendClient::Gmail(client)) => return client.send_message(raw).map(|()| None),
            #[cfg(feature = "msgraph")]
            Some(BackendClient::Msgraph(client)) => return client.send_message(raw).map(|()| None),
            #[cfg(feature = "pimdir")]
            Some(BackendClient::Pimdir(client)) => {
                return client.send_message(mailbox, raw).map(Some);
            }
            _ => {}
        }

        #[cfg(feature = "smtp")]
        if let Some(smtp) = self.smtp_client_mut()? {
            return smtp.send_message(raw).map(|()| None);
        }

        bail!(
            "No send-capable backend (JMAP/Gmail/Graph/pimdir) or SMTP is configured for this account"
        )
    }

    /// Connects the SMTP transport on first use, `None` when none is
    /// configured.
    #[cfg(feature = "smtp")]
    fn smtp_client_mut(&mut self) -> Result<Option<&mut SmtpClient>> {
        if let SmtpTransport::Pending(_) = &self.smtp {
            let SmtpTransport::Pending(config) =
                mem::replace(&mut self.smtp, SmtpTransport::Absent)
            else {
                unreachable!()
            };
            self.smtp = SmtpTransport::Ready(SmtpClient::new(*config)?);
        }

        Ok(match &mut self.smtp {
            SmtpTransport::Ready(client) => Some(client),
            _ => None,
        })
    }

    /// Maps a human mailbox name onto the backend-native id every
    /// operation method expects.
    ///
    /// Identity where the name already is the id, and a cached listing
    /// where the backend mints an opaque one. Every dispatching method
    /// runs it first, so an adapter only ever receives ids.
    ///
    /// Idempotent, an already-resolved id passing through unchanged,
    /// which is what lets a caller compare a mailbox against the trash.
    pub fn resolve_mailbox_id(&mut self, mailbox: &str) -> Result<String> {
        match self.storage_mut()? {
            #[cfg(feature = "jmap")]
            BackendClient::Jmap(client) => client.resolve_mailbox_id(mailbox),
            #[cfg(feature = "gmail")]
            BackendClient::Gmail(client) => client.resolve_mailbox_id(mailbox),
            #[cfg(feature = "msgraph")]
            BackendClient::Msgraph(client) => client.resolve_mailbox_id(mailbox),
            _ => Ok(mailbox.to_string()),
        }
    }

    fn storage_mut(&mut self) -> Result<&mut BackendClient> {
        self.storage
            .as_mut()
            .ok_or_else(|| anyhow!("No storage backend is configured for this account"))
    }
}

/// Picks the account's storage backend: the first configured one
/// `--backend` allows, local before network.
#[cfg_attr(
    not(any(
        feature = "maildir",
        feature = "m2dir",
        feature = "mbox",
        feature = "pimdir",
        feature = "jmap",
        feature = "gmail",
        feature = "msgraph",
        feature = "imap"
    )),
    allow(unused_variables)
)]
fn select_storage(
    account_config: &mut AccountConfig,
    backend: Backend,
) -> Result<Option<BackendClient>> {
    #[cfg(feature = "maildir")]
    if backend.allows_maildir()
        && let Some(config) = account_config.maildir.take()
    {
        return Ok(Some(BackendClient::Maildir(Box::new(MaildirClient::new(
            config,
        )))));
    }

    #[cfg(feature = "m2dir")]
    if backend.allows_m2dir()
        && let Some(config) = account_config.m2dir.take()
    {
        return Ok(Some(BackendClient::M2dir(Box::new(M2dirClient::new(
            config,
        )))));
    }

    #[cfg(feature = "mbox")]
    if backend.allows_mbox()
        && let Some(config) = account_config.mbox.take()
    {
        return Ok(Some(BackendClient::Mbox(Box::new(MboxClient::new(config)))));
    }

    #[cfg(feature = "pimdir")]
    if backend.allows_pimdir()
        && let Some(config) = account_config.pimdir.take()
    {
        return Ok(Some(BackendClient::Pimdir(Box::new(PimdirClient::new(
            config,
        )?))));
    }

    #[cfg(feature = "jmap")]
    if backend.allows_jmap()
        && let Some(config) = account_config.jmap.take()
    {
        return Ok(Some(BackendClient::Jmap(Box::new(JmapClient::new(
            config,
        )?))));
    }

    #[cfg(feature = "gmail")]
    if backend.allows_gmail()
        && let Some(config) = account_config.gmail.take()
    {
        return Ok(Some(BackendClient::Gmail(Box::new(GmailClient::new(
            config,
        )?))));
    }

    #[cfg(feature = "msgraph")]
    if backend.allows_msgraph()
        && let Some(config) = account_config.msgraph.take()
    {
        return Ok(Some(BackendClient::Msgraph(Box::new(MsgraphClient::new(
            config,
        )?))));
    }

    #[cfg(feature = "imap")]
    if backend.allows_imap()
        && let Some(config) = account_config.imap.take()
    {
        return Ok(Some(BackendClient::Imap(Box::new(ImapClient::new(
            config,
        )?))));
    }

    Ok(None)
}