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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
/*
 * meli - jmap module.
 *
 * Copyright 2019 Manos Pitsidianakis
 *
 * This file is part of meli.
 *
 * meli is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * meli is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with meli. If not, see <http://www.gnu.org/licenses/>.
 */

use crate::backends::*;
use crate::conf::AccountSettings;
use crate::email::*;
use crate::error::{MeliError, Result};
use futures::lock::Mutex as FutureMutex;
use isahc::config::RedirectPolicy;
use isahc::prelude::HttpClient;
use isahc::ResponseExt;
use serde_json::Value;
use std::collections::{hash_map::DefaultHasher, BTreeMap, HashMap, HashSet};
use std::convert::TryFrom;
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use std::sync::{Arc, Mutex, RwLock};
use std::time::Instant;

macro_rules! tag_hash {
    ($t:ident) => {{
        let mut hasher = DefaultHasher::default();
        $t.hash(&mut hasher);
        hasher.finish()
    }};
    ($t:literal) => {{
        let mut hasher = DefaultHasher::default();
        $t.hash(&mut hasher);
        hasher.finish()
    }};
}

#[macro_export]
macro_rules! _impl {
        ($(#[$outer:meta])*$field:ident : $t:ty) => {
            $(#[$outer])*
            pub fn $field(mut self, new_val: $t) -> Self {
                self.$field = new_val;
                self
            }
        };
        (get_mut $(#[$outer:meta])*$method:ident, $field:ident : $t:ty) => {
            $(#[$outer])*
            pub fn $method(&mut self) -> &mut $t {
                &mut self.$field
            }
        };
        (get $(#[$outer:meta])*$method:ident, $field:ident : $t:ty) => {
            $(#[$outer])*
            pub fn $method(&self) -> &$t {
                &self.$field
            }
        }
    }

pub mod operations;
use operations::*;

pub mod connection;
use connection::*;

pub mod protocol;
use protocol::*;

pub mod rfc8620;
use rfc8620::*;

pub mod objects;
use objects::*;

pub mod mailbox;
use mailbox::*;

#[derive(Debug, Default)]
pub struct EnvelopeCache {
    bytes: Option<String>,
    headers: Option<String>,
    body: Option<String>,
    flags: Option<Flag>,
}

#[derive(Debug, Clone)]
pub struct JmapServerConf {
    pub server_hostname: String,
    pub server_username: String,
    pub server_password: String,
    pub server_port: u16,
    pub danger_accept_invalid_certs: bool,
}

macro_rules! get_conf_val {
    ($s:ident[$var:literal]) => {
        $s.extra.get($var).ok_or_else(|| {
            MeliError::new(format!(
                "Configuration error ({}): JMAP connection requires the field `{}` set",
                $s.name.as_str(),
                $var
            ))
        })
    };
    ($s:ident[$var:literal], $default:expr) => {
        $s.extra
            .get($var)
            .map(|v| {
                <_>::from_str(v).map_err(|e| {
                    MeliError::new(format!(
                        "Configuration error ({}): Invalid value for field `{}`: {}\n{}",
                        $s.name.as_str(),
                        $var,
                        v,
                        e
                    ))
                })
            })
            .unwrap_or_else(|| Ok($default))
    };
}

impl JmapServerConf {
    pub fn new(s: &AccountSettings) -> Result<Self> {
        Ok(JmapServerConf {
            server_hostname: get_conf_val!(s["server_hostname"])?.to_string(),
            server_username: get_conf_val!(s["server_username"])?.to_string(),
            server_password: get_conf_val!(s["server_password"])?.to_string(),
            server_port: get_conf_val!(s["server_port"], 443)?,
            danger_accept_invalid_certs: get_conf_val!(s["danger_accept_invalid_certs"], false)?,
        })
    }
}

pub struct IsSubscribedFn(Box<dyn Fn(&str) -> bool + Send + Sync>);

impl std::fmt::Debug for IsSubscribedFn {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "IsSubscribedFn Box")
    }
}

impl std::ops::Deref for IsSubscribedFn {
    type Target = Box<dyn Fn(&str) -> bool + Send + Sync>;
    fn deref(&self) -> &Box<dyn Fn(&str) -> bool + Send + Sync> {
        &self.0
    }
}
macro_rules! get_conf_val {
    ($s:ident[$var:literal]) => {
        $s.extra.get($var).ok_or_else(|| {
            MeliError::new(format!(
                "Configuration error ({}): JMAP connection requires the field `{}` set",
                $s.name.as_str(),
                $var
            ))
        })
    };
    ($s:ident[$var:literal], $default:expr) => {
        $s.extra
            .get($var)
            .map(|v| {
                <_>::from_str(v).map_err(|e| {
                    MeliError::new(format!(
                        "Configuration error ({}): Invalid value for field `{}`: {}\n{}",
                        $s.name.as_str(),
                        $var,
                        v,
                        e
                    ))
                })
            })
            .unwrap_or_else(|| Ok($default))
    };
}

#[derive(Debug)]
pub struct Store {
    pub account_name: Arc<String>,
    pub account_hash: AccountHash,
    pub account_id: Arc<Mutex<Id<Account>>>,
    pub byte_cache: Arc<Mutex<HashMap<EnvelopeHash, EnvelopeCache>>>,
    pub id_store: Arc<Mutex<HashMap<EnvelopeHash, Id<EmailObject>>>>,
    pub reverse_id_store: Arc<Mutex<HashMap<Id<EmailObject>, EnvelopeHash>>>,
    pub blob_id_store: Arc<Mutex<HashMap<EnvelopeHash, Id<BlobObject>>>>,
    pub tag_index: Arc<RwLock<BTreeMap<u64, String>>>,
    pub mailboxes: Arc<RwLock<HashMap<MailboxHash, JmapMailbox>>>,
    pub mailboxes_index: Arc<RwLock<HashMap<MailboxHash, HashSet<EnvelopeHash>>>>,
    pub mailbox_state: Arc<Mutex<State<MailboxObject>>>,
    pub online_status: Arc<FutureMutex<(Instant, Result<()>)>>,
    pub is_subscribed: Arc<IsSubscribedFn>,
    pub event_consumer: BackendEventConsumer,
}

impl Store {
    pub fn add_envelope(&self, obj: EmailObject) -> Envelope {
        let mut tag_lck = self.tag_index.write().unwrap();
        let tags = obj
            .keywords()
            .keys()
            .map(|tag| {
                let tag_hash = {
                    let mut hasher = DefaultHasher::default();
                    tag.hash(&mut hasher);
                    hasher.finish()
                };
                if !tag_lck.contains_key(&tag_hash) {
                    tag_lck.insert(tag_hash, tag.to_string());
                }
                tag_hash
            })
            .collect::<SmallVec<[u64; 1024]>>();
        let id = obj.id.clone();
        let mailbox_ids = obj.mailbox_ids.clone();
        let blob_id = obj.blob_id.clone();
        drop(tag_lck);
        let mut ret: Envelope = obj.into();

        debug_assert_eq!(tag_hash!("$draft"), 6613915297903591176);
        debug_assert_eq!(tag_hash!("$seen"), 1683863812294339685);
        debug_assert_eq!(tag_hash!("$flagged"), 2714010747478170100);
        debug_assert_eq!(tag_hash!("$answered"), 8940855303929342213);
        debug_assert_eq!(tag_hash!("$junk"), 2656839745430720464);
        debug_assert_eq!(tag_hash!("$notjunk"), 4091323799684325059);
        let mut id_store_lck = self.id_store.lock().unwrap();
        let mut reverse_id_store_lck = self.reverse_id_store.lock().unwrap();
        let mut blob_id_store_lck = self.blob_id_store.lock().unwrap();
        let mailboxes_lck = self.mailboxes.read().unwrap();
        let mut mailboxes_index_lck = self.mailboxes_index.write().unwrap();
        for (mailbox_id, _) in mailbox_ids {
            if let Some((mailbox_hash, _)) = mailboxes_lck.iter().find(|(_, m)| m.id == mailbox_id)
            {
                mailboxes_index_lck
                    .entry(*mailbox_hash)
                    .or_default()
                    .insert(ret.hash());
            }
        }
        reverse_id_store_lck.insert(id.clone(), ret.hash());
        id_store_lck.insert(ret.hash(), id);
        blob_id_store_lck.insert(ret.hash(), blob_id);
        for t in tags {
            match t {
                6613915297903591176 => {
                    ret.set_flags(ret.flags() | Flag::DRAFT);
                }
                1683863812294339685 => {
                    ret.set_flags(ret.flags() | Flag::SEEN);
                }
                2714010747478170100 => {
                    ret.set_flags(ret.flags() | Flag::FLAGGED);
                }
                8940855303929342213 => {
                    ret.set_flags(ret.flags() | Flag::REPLIED);
                }
                2656839745430720464 | 4091323799684325059 => { /* ignore */ }
                _ => ret.labels_mut().push(t),
            }
        }
        ret
    }

    pub fn remove_envelope(
        &self,
        obj_id: Id<EmailObject>,
    ) -> Option<(EnvelopeHash, SmallVec<[MailboxHash; 8]>)> {
        let env_hash = self.reverse_id_store.lock().unwrap().remove(&obj_id)?;
        self.id_store.lock().unwrap().remove(&env_hash);
        self.blob_id_store.lock().unwrap().remove(&env_hash);
        self.byte_cache.lock().unwrap().remove(&env_hash);
        let mut mailbox_hashes = SmallVec::new();
        for (k, set) in self.mailboxes_index.write().unwrap().iter_mut() {
            if set.remove(&env_hash) {
                mailbox_hashes.push(*k);
            }
        }
        Some((env_hash, mailbox_hashes))
    }
}

#[derive(Debug)]
pub struct JmapType {
    server_conf: JmapServerConf,
    connection: Arc<FutureMutex<JmapConnection>>,
    store: Arc<Store>,
}

impl MailBackend for JmapType {
    fn capabilities(&self) -> MailBackendCapabilities {
        const CAPABILITIES: MailBackendCapabilities = MailBackendCapabilities {
            is_async: true,
            is_remote: true,
            supports_search: true,
            extensions: None,
            supports_tags: true,
            supports_submission: false,
        };
        CAPABILITIES
    }

    fn is_online(&self) -> ResultFuture<()> {
        let online = self.store.online_status.clone();
        Ok(Box::pin(async move {
            //match timeout(std::time::Duration::from_secs(3), connection.lock()).await {
            let online_lck = online.lock().await;
            if online_lck.1.is_err()
                && Instant::now().duration_since(online_lck.0) >= std::time::Duration::new(2, 0)
            {
                //let _ = self.mailboxes();
            }
            online_lck.1.clone()
        }))
    }

    fn fetch(
        &mut self,
        mailbox_hash: MailboxHash,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<Vec<Envelope>>> + Send + 'static>>> {
        let store = self.store.clone();
        let connection = self.connection.clone();
        Ok(Box::pin(async_stream::try_stream! {
            let mut conn = connection.lock().await;
            conn.connect().await?;
            let res = protocol::fetch(
                &conn,
                &store,
                mailbox_hash,
            ).await?;
            yield res;
        }))
    }

    fn refresh(&mut self, mailbox_hash: MailboxHash) -> ResultFuture<()> {
        let connection = self.connection.clone();
        Ok(Box::pin(async move {
            let mut conn = connection.lock().await;
            conn.connect().await?;
            conn.email_changes(mailbox_hash).await?;
            Ok(())
        }))
    }

    fn watch(&self) -> ResultFuture<()> {
        Err(MeliError::from("JMAP watch for updates is unimplemented"))
    }

    fn mailboxes(&self) -> ResultFuture<HashMap<MailboxHash, Mailbox>> {
        let store = self.store.clone();
        let connection = self.connection.clone();
        Ok(Box::pin(async move {
            let mut conn = connection.lock().await;
            conn.connect().await?;
            if store.mailboxes.read().unwrap().is_empty() {
                let new_mailboxes = debug!(protocol::get_mailboxes(&conn).await)?;
                *store.mailboxes.write().unwrap() = new_mailboxes;
            }

            let ret = store
                .mailboxes
                .read()
                .unwrap()
                .iter()
                .filter(|(_, f)| f.is_subscribed)
                .map(|(&h, f)| (h, BackendMailbox::clone(f) as Mailbox))
                .collect();

            Ok(ret)
        }))
    }

    fn operation(&self, hash: EnvelopeHash) -> Result<Box<dyn BackendOp>> {
        Ok(Box::new(JmapOp::new(
            hash,
            self.connection.clone(),
            self.store.clone(),
        )))
    }

    fn save(
        &self,
        bytes: Vec<u8>,
        mailbox_hash: MailboxHash,
        _flags: Option<Flag>,
    ) -> ResultFuture<()> {
        let store = self.store.clone();
        let connection = self.connection.clone();
        Ok(Box::pin(async move {
            let mut conn = connection.lock().await;
            conn.connect().await?;
            /*
             * 1. upload binary blob, get blobId
             * 2. Email/import
             */
            let mut res = conn
                .client
                .post_async(
                    &upload_request_format(&conn.session, conn.mail_account_id()),
                    bytes,
                )
                .await?;

            let mailbox_id: Id<MailboxObject> = {
                let mailboxes_lck = store.mailboxes.read().unwrap();
                if let Some(mailbox) = mailboxes_lck.get(&mailbox_hash) {
                    mailbox.id.clone()
                } else {
                    return Err(MeliError::new(format!(
                        "Mailbox with hash {} not found",
                        mailbox_hash
                    )));
                }
            };
            let res_text = res.text_async().await?;

            let upload_response: UploadResponse = serde_json::from_str(&res_text)?;
            let mut req = Request::new(conn.request_no.clone());
            let creation_id: Id<EmailObject> = "1".to_string().into();
            let mut email_imports = HashMap::default();
            let mut mailbox_ids = HashMap::default();
            mailbox_ids.insert(mailbox_id, true);
            email_imports.insert(
                creation_id.clone(),
                EmailImport::new()
                    .blob_id(upload_response.blob_id)
                    .mailbox_ids(mailbox_ids),
            );

            let import_call: ImportCall = ImportCall::new()
                .account_id(conn.mail_account_id().clone())
                .emails(email_imports);

            req.add_call(&import_call);
            let mut res = conn
                .client
                .post_async(&conn.session.api_url, serde_json::to_string(&req)?)
                .await?;
            let res_text = res.text_async().await?;

            let mut v: MethodResponse = serde_json::from_str(&res_text)?;
            let m = ImportResponse::try_from(v.method_responses.remove(0)).or_else(|err| {
                let ierr: Result<ImportError> =
                    serde_json::from_str(&res_text).map_err(|err| err.into());
                if let Ok(err) = ierr {
                    Err(MeliError::new(format!("Could not save message: {:?}", err)))
                } else {
                    Err(err.into())
                }
            })?;

            if let Some(err) = m.not_created.get(&creation_id) {
                return Err(MeliError::new(format!("Could not save message: {:?}", err)));
            }
            Ok(())
        }))
    }

    fn tags(&self) -> Option<Arc<RwLock<BTreeMap<u64, String>>>> {
        Some(self.store.tag_index.clone())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn search(
        &self,
        q: crate::search::Query,
        mailbox_hash: Option<MailboxHash>,
    ) -> ResultFuture<SmallVec<[EnvelopeHash; 512]>> {
        let store = self.store.clone();
        let connection = self.connection.clone();
        let filter = if let Some(mailbox_hash) = mailbox_hash {
            let mailbox_id = self.store.mailboxes.read().unwrap()[&mailbox_hash]
                .id
                .clone();

            let mut f = Filter::Condition(
                EmailFilterCondition::new()
                    .in_mailbox(Some(mailbox_id))
                    .into(),
            );
            f &= Filter::<EmailFilterCondition, EmailObject>::from(q);
            f
        } else {
            Filter::<EmailFilterCondition, EmailObject>::from(q)
        };

        Ok(Box::pin(async move {
            let mut conn = connection.lock().await;
            conn.connect().await?;
            let email_call: EmailQuery = EmailQuery::new(
                Query::new()
                    .account_id(conn.mail_account_id().clone())
                    .filter(Some(filter))
                    .position(0),
            )
            .collapse_threads(false);

            let mut req = Request::new(conn.request_no.clone());
            req.add_call(&email_call);

            let mut res = conn
                .client
                .post_async(&conn.session.api_url, serde_json::to_string(&req)?)
                .await?;

            let res_text = res.text_async().await?;
            let mut v: MethodResponse = serde_json::from_str(&res_text).unwrap();
            *store.online_status.lock().await = (std::time::Instant::now(), Ok(()));
            let m = QueryResponse::<EmailObject>::try_from(v.method_responses.remove(0))?;
            let QueryResponse::<EmailObject> { ids, .. } = m;
            let ret = ids.into_iter().map(|id| id.into_hash()).collect();
            Ok(ret)
        }))
    }

    fn rename_mailbox(
        &mut self,
        _mailbox_hash: MailboxHash,
        _new_path: String,
    ) -> ResultFuture<Mailbox> {
        Err(MeliError::new("Unimplemented."))
    }

    fn create_mailbox(
        &mut self,
        _path: String,
    ) -> ResultFuture<(MailboxHash, HashMap<MailboxHash, Mailbox>)> {
        Err(MeliError::new("Unimplemented."))
    }

    fn copy_messages(
        &mut self,
        env_hashes: EnvelopeHashBatch,
        source_mailbox_hash: MailboxHash,
        destination_mailbox_hash: MailboxHash,
        move_: bool,
    ) -> ResultFuture<()> {
        let store = self.store.clone();
        let connection = self.connection.clone();
        Ok(Box::pin(async move {
            let (source_mailbox_id, destination_mailbox_id) = {
                let mailboxes_lck = store.mailboxes.read().unwrap();
                if !mailboxes_lck.contains_key(&source_mailbox_hash) {
                    return Err(MeliError::new(format!(
                        "Could not find source mailbox with hash {}",
                        source_mailbox_hash
                    )));
                }
                if !mailboxes_lck.contains_key(&destination_mailbox_hash) {
                    return Err(MeliError::new(format!(
                        "Could not find destination mailbox with hash {}",
                        destination_mailbox_hash
                    )));
                }

                (
                    mailboxes_lck[&source_mailbox_hash].id.clone(),
                    mailboxes_lck[&destination_mailbox_hash].id.clone(),
                )
            };
            let mut update_map: HashMap<Id<EmailObject>, Value> = HashMap::default();
            let mut ids: Vec<Id<EmailObject>> = Vec::with_capacity(env_hashes.rest.len() + 1);
            let mut id_map: HashMap<Id<EmailObject>, EnvelopeHash> = HashMap::default();
            let mut update_keywords: HashMap<String, Value> = HashMap::default();
            update_keywords.insert(
                format!("mailboxIds/{}", &destination_mailbox_id),
                serde_json::json!(true),
            );
            if move_ {
                update_keywords.insert(
                    format!("mailboxIds/{}", &source_mailbox_id),
                    serde_json::json!(null),
                );
            }
            {
                for env_hash in env_hashes.iter() {
                    if let Some(id) = store.id_store.lock().unwrap().get(&env_hash) {
                        ids.push(id.clone());
                        id_map.insert(id.clone(), env_hash);
                        update_map.insert(id.clone(), serde_json::json!(update_keywords.clone()));
                    }
                }
            }
            let conn = connection.lock().await;

            let email_set_call: EmailSet = EmailSet::new(
                Set::<EmailObject>::new()
                    .account_id(conn.mail_account_id().clone())
                    .update(Some(update_map)),
            );

            let mut req = Request::new(conn.request_no.clone());
            let _prev_seq = req.add_call(&email_set_call);

            let mut res = conn
                .client
                .post_async(&conn.session.api_url, serde_json::to_string(&req)?)
                .await?;

            let res_text = res.text_async().await?;

            let mut v: MethodResponse = serde_json::from_str(&res_text).unwrap();
            *store.online_status.lock().await = (std::time::Instant::now(), Ok(()));
            let m = SetResponse::<EmailObject>::try_from(v.method_responses.remove(0))?;
            if let Some(ids) = m.not_updated {
                if !ids.is_empty() {
                    return Err(MeliError::new(format!(
                        "Could not update ids: {}",
                        ids.into_iter()
                            .map(|err| err.to_string())
                            .collect::<Vec<String>>()
                            .join(",")
                    )));
                }
            }
            Ok(())
        }))
    }

    fn set_flags(
        &mut self,
        env_hashes: EnvelopeHashBatch,
        mailbox_hash: MailboxHash,
        flags: SmallVec<[(std::result::Result<Flag, String>, bool); 8]>,
    ) -> ResultFuture<()> {
        let store = self.store.clone();
        let connection = self.connection.clone();
        Ok(Box::pin(async move {
            let mut update_map: HashMap<Id<EmailObject>, Value> = HashMap::default();
            let mut ids: Vec<Id<EmailObject>> = Vec::with_capacity(env_hashes.rest.len() + 1);
            let mut id_map: HashMap<Id<EmailObject>, EnvelopeHash> = HashMap::default();
            let mut update_keywords: HashMap<String, Value> = HashMap::default();
            for (flag, value) in flags.iter() {
                match flag {
                    Ok(f) => {
                        update_keywords.insert(
                            format!(
                                "keywords/{}",
                                match *f {
                                    Flag::DRAFT => "$draft",
                                    Flag::FLAGGED => "$flagged",
                                    Flag::SEEN => "$seen",
                                    Flag::REPLIED => "$answered",
                                    Flag::TRASHED => "$junk",
                                    Flag::PASSED => "$passed",
                                    _ => continue, //FIXME
                                }
                            ),
                            if *value {
                                serde_json::json!(true)
                            } else {
                                serde_json::json!(null)
                            },
                        );
                    }
                    Err(t) => {
                        update_keywords.insert(
                            format!("keywords/{}", t),
                            if *value {
                                serde_json::json!(true)
                            } else {
                                serde_json::json!(null)
                            },
                        );
                    }
                }
            }
            {
                for hash in env_hashes.iter() {
                    if let Some(id) = store.id_store.lock().unwrap().get(&hash) {
                        ids.push(id.clone());
                        id_map.insert(id.clone(), hash);
                        update_map.insert(id.clone(), serde_json::json!(update_keywords.clone()));
                    }
                }
            }
            let conn = connection.lock().await;

            let email_set_call: EmailSet = EmailSet::new(
                Set::<EmailObject>::new()
                    .account_id(conn.mail_account_id().clone())
                    .update(Some(update_map)),
            );

            let mut req = Request::new(conn.request_no.clone());
            req.add_call(&email_set_call);
            let email_call: EmailGet = EmailGet::new(
                Get::new()
                    .ids(Some(JmapArgument::Value(ids)))
                    .account_id(conn.mail_account_id().clone())
                    .properties(Some(vec!["keywords".to_string()])),
            );

            req.add_call(&email_call);
            //debug!(serde_json::to_string(&req)?);
            let mut res = conn
                .client
                .post_async(&conn.session.api_url, serde_json::to_string(&req)?)
                .await?;

            let res_text = res.text_async().await?;
            /*
             *{"methodResponses":[["Email/set",{"notUpdated":null,"notDestroyed":null,"oldState":"86","newState":"87","accountId":"u148940c7","updated":{"M045926eed54b11423918f392":{"id":"M045926eed54b11423918f392"}},"created":null,"destroyed":null,"notCreated":null},"m3"]],"sessionState":"cyrus-0;p-5;vfs-0"}
             */
            //debug!("res_text = {}", &res_text);
            let mut v: MethodResponse = serde_json::from_str(&res_text).unwrap();
            *store.online_status.lock().await = (std::time::Instant::now(), Ok(()));
            let m = SetResponse::<EmailObject>::try_from(v.method_responses.remove(0))?;
            if let Some(ids) = m.not_updated {
                return Err(MeliError::new(
                    ids.into_iter()
                        .map(|err| err.to_string())
                        .collect::<Vec<String>>()
                        .join(","),
                ));
            }

            {
                let mut tag_index_lck = store.tag_index.write().unwrap();
                for (flag, value) in flags.iter() {
                    match flag {
                        Ok(_) => {}
                        Err(t) => {
                            if *value {
                                tag_index_lck.insert(tag_hash!(t), t.clone());
                            }
                        }
                    }
                }
                drop(tag_index_lck);
            }
            let e = GetResponse::<EmailObject>::try_from(v.method_responses.pop().unwrap())?;
            let GetResponse::<EmailObject> { list, state, .. } = e;
            {
                let (is_empty, is_equal) = {
                    let mailboxes_lck = conn.store.mailboxes.read().unwrap();
                    mailboxes_lck
                        .get(&mailbox_hash)
                        .map(|mbox| {
                            let current_state_lck = mbox.email_state.lock().unwrap();
                            (
                                current_state_lck.is_some(),
                                current_state_lck.as_ref() != Some(&state),
                            )
                        })
                        .unwrap_or((true, true))
                };
                if is_empty {
                    let mut mailboxes_lck = conn.store.mailboxes.write().unwrap();
                    debug!("{:?}: inserting state {}", EmailObject::NAME, &state);
                    mailboxes_lck.entry(mailbox_hash).and_modify(|mbox| {
                        *mbox.email_state.lock().unwrap() = Some(state);
                    });
                } else if !is_equal {
                    conn.email_changes(mailbox_hash).await?;
                }
            }
            debug!(&list);
            for envobj in list {
                let env_hash = id_map[&envobj.id];
                conn.add_refresh_event(RefreshEvent {
                    account_hash: store.account_hash,
                    mailbox_hash,
                    kind: RefreshEventKind::NewFlags(
                        env_hash,
                        protocol::keywords_to_flags(envobj.keywords().keys().cloned().collect()),
                    ),
                });
            }
            Ok(())
        }))
    }

    fn delete_messages(
        &mut self,
        _env_hashes: EnvelopeHashBatch,
        _mailbox_hash: MailboxHash,
    ) -> ResultFuture<()> {
        Err(MeliError::new("Unimplemented."))
    }
}

impl JmapType {
    pub fn new(
        s: &AccountSettings,
        is_subscribed: Box<dyn Fn(&str) -> bool + Send + Sync>,
        event_consumer: BackendEventConsumer,
    ) -> Result<Box<dyn MailBackend>> {
        let online_status = Arc::new(FutureMutex::new((
            std::time::Instant::now(),
            Err(MeliError::new("Account is uninitialised.")),
        )));
        let server_conf = JmapServerConf::new(s)?;

        let account_hash = {
            let mut hasher = DefaultHasher::new();
            hasher.write(s.name.as_bytes());
            hasher.finish()
        };
        let store = Arc::new(Store {
            account_name: Arc::new(s.name.clone()),
            account_hash,
            account_id: Arc::new(Mutex::new(Id::new())),
            online_status,
            event_consumer,
            is_subscribed: Arc::new(IsSubscribedFn(is_subscribed)),

            byte_cache: Default::default(),
            id_store: Default::default(),
            reverse_id_store: Default::default(),
            blob_id_store: Default::default(),
            tag_index: Default::default(),
            mailboxes: Default::default(),
            mailboxes_index: Default::default(),
            mailbox_state: Default::default(),
        });

        Ok(Box::new(JmapType {
            connection: Arc::new(FutureMutex::new(JmapConnection::new(
                &server_conf,
                store.clone(),
            )?)),
            store,
            server_conf,
        }))
    }

    pub fn validate_config(s: &AccountSettings) -> Result<()> {
        get_conf_val!(s["server_hostname"])?;
        get_conf_val!(s["server_username"])?;
        get_conf_val!(s["server_password"])?;
        get_conf_val!(s["server_port"], 443)?;
        get_conf_val!(s["danger_accept_invalid_certs"], false)?;
        Ok(())
    }
}