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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
//! Context module.

use std::collections::{BTreeMap, HashMap};
use std::ffi::OsString;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use anyhow::{bail, ensure, Context as _, Result};
use async_channel::{self as channel, Receiver, Sender};
use pgp::types::PublicKeyTrait;
use pgp::SignedPublicKey;
use ratelimit::Ratelimit;
use tokio::sync::{Mutex, Notify, OnceCell, RwLock};

use crate::aheader::EncryptPreference;
use crate::chat::{get_chat_cnt, ChatId, ProtectionStatus};
use crate::chatlist_events;
use crate::config::Config;
use crate::constants::{
    self, DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT, DC_CHAT_ID_TRASH, DC_VERSION_STR,
};
use crate::contact::{Contact, ContactId};
use crate::debug_logging::DebugLogging;
use crate::download::DownloadState;
use crate::events::{Event, EventEmitter, EventType, Events};
use crate::imap::{FolderMeaning, Imap, ServerMetadata};
use crate::key::{load_self_public_key, load_self_secret_key, DcKey as _};
use crate::login_param::{ConfiguredLoginParam, EnteredLoginParam};
use crate::message::{self, Message, MessageState, MsgId};
use crate::param::{Param, Params};
use crate::peer_channels::Iroh;
use crate::peerstate::Peerstate;
use crate::push::PushSubscriber;
use crate::quota::QuotaInfo;
use crate::scheduler::{convert_folder_meaning, SchedulerState};
use crate::sql::Sql;
use crate::stock_str::StockStrings;
use crate::timesmearing::SmearedTimestamp;
use crate::tools::{self, create_id, duration_to_str, time, time_elapsed};

/// Builder for the [`Context`].
///
/// Many arguments to the [`Context`] are kind of optional and only needed to handle
/// multiple contexts, for which the [account manager](crate::accounts::Accounts) should be
/// used.  This builder makes creating a new context simpler, especially for the
/// standalone-context case.
///
/// # Examples
///
/// Creating a new unencrypted database:
///
/// ```
/// # let rt = tokio::runtime::Runtime::new().unwrap();
/// # rt.block_on(async move {
/// use deltachat::context::ContextBuilder;
///
/// let dir = tempfile::tempdir().unwrap();
/// let context = ContextBuilder::new(dir.path().join("db"))
///      .open()
///      .await
///      .unwrap();
/// drop(context);
/// # });
/// ```
///
/// To use an encrypted database provide a password.  If the database does not yet exist it
/// will be created:
///
/// ```
/// # let rt = tokio::runtime::Runtime::new().unwrap();
/// # rt.block_on(async move {
/// use deltachat::context::ContextBuilder;
///
/// let dir = tempfile::tempdir().unwrap();
/// let context = ContextBuilder::new(dir.path().join("db"))
///      .with_password("secret".into())
///      .open()
///      .await
///      .unwrap();
/// drop(context);
/// # });
/// ```
#[derive(Clone, Debug)]
pub struct ContextBuilder {
    dbfile: PathBuf,
    id: u32,
    events: Events,
    stock_strings: StockStrings,
    password: Option<String>,

    push_subscriber: Option<PushSubscriber>,
}

impl ContextBuilder {
    /// Create the builder using the given database file.
    ///
    /// The *dbfile* should be in a dedicated directory and this directory must exist.  The
    /// [`Context`] will create other files and folders in the same directory as the
    /// database file used.
    pub fn new(dbfile: PathBuf) -> Self {
        ContextBuilder {
            dbfile,
            id: rand::random(),
            events: Events::new(),
            stock_strings: StockStrings::new(),
            password: None,
            push_subscriber: None,
        }
    }

    /// Sets the context ID.
    ///
    /// This identifier is used e.g. in [`Event`]s to identify which [`Context`] an event
    /// belongs to.  The only real limit on it is that it should not conflict with any other
    /// [`Context`]s you currently have open.  So if you handle multiple [`Context`]s you
    /// may want to use this.
    ///
    /// Note that the [account manager](crate::accounts::Accounts) is designed to handle the
    /// common case for using multiple [`Context`] instances.
    pub fn with_id(mut self, id: u32) -> Self {
        self.id = id;
        self
    }

    /// Sets the event channel for this [`Context`].
    ///
    /// Mostly useful when using multiple [`Context`]s, this allows creating one [`Events`]
    /// channel and passing it to all [`Context`]s so all events are received on the same
    /// channel.
    ///
    /// Note that the [account manager](crate::accounts::Accounts) is designed to handle the
    /// common case for using multiple [`Context`] instances.
    pub fn with_events(mut self, events: Events) -> Self {
        self.events = events;
        self
    }

    /// Sets the [`StockStrings`] map to use for this [`Context`].
    ///
    /// This is useful in order to share the same translation strings in all [`Context`]s.
    /// The mapping may be empty when set, it will be populated by
    /// [`Context::set_stock-translation`] or [`Accounts::set_stock_translation`] calls.
    ///
    /// Note that the [account manager](crate::accounts::Accounts) is designed to handle the
    /// common case for using multiple [`Context`] instances.
    ///
    /// [`Accounts::set_stock_translation`]: crate::accounts::Accounts::set_stock_translation
    pub fn with_stock_strings(mut self, stock_strings: StockStrings) -> Self {
        self.stock_strings = stock_strings;
        self
    }

    /// Sets the password to unlock the database.
    ///
    /// If an encrypted database is used it must be opened with a password.  Setting a
    /// password on a new database will enable encryption.
    pub fn with_password(mut self, password: String) -> Self {
        self.password = Some(password);
        self
    }

    /// Sets push subscriber.
    pub(crate) fn with_push_subscriber(mut self, push_subscriber: PushSubscriber) -> Self {
        self.push_subscriber = Some(push_subscriber);
        self
    }

    /// Builds the [`Context`] without opening it.
    pub async fn build(self) -> Result<Context> {
        let push_subscriber = self.push_subscriber.unwrap_or_default();
        let context = Context::new_closed(
            &self.dbfile,
            self.id,
            self.events,
            self.stock_strings,
            push_subscriber,
        )
        .await?;
        Ok(context)
    }

    /// Builds the [`Context`] and opens it.
    ///
    /// Returns error if context cannot be opened with the given passphrase.
    pub async fn open(self) -> Result<Context> {
        let password = self.password.clone().unwrap_or_default();
        let context = self.build().await?;
        match context.open(password).await? {
            true => Ok(context),
            false => bail!("database could not be decrypted, incorrect or missing password"),
        }
    }
}

/// The context for a single DeltaChat account.
///
/// This contains all the state for a single DeltaChat account, including background tasks
/// running in Tokio to operate the account.  The [`Context`] can be cheaply cloned.
///
/// Each context, and thus each account, must be associated with an directory where all the
/// state is kept.  This state is also preserved between restarts.
///
/// To use multiple accounts it is best to look at the [accounts
/// manager][crate::accounts::Accounts] which handles storing multiple accounts in a single
/// directory structure and handles loading them all concurrently.
#[derive(Clone, Debug)]
pub struct Context {
    pub(crate) inner: Arc<InnerContext>,
}

impl Deref for Context {
    type Target = InnerContext;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

/// Actual context, expensive to clone.
#[derive(Debug)]
pub struct InnerContext {
    /// Blob directory path
    pub(crate) blobdir: PathBuf,
    pub(crate) sql: Sql,
    pub(crate) smeared_timestamp: SmearedTimestamp,
    /// The global "ongoing" process state.
    ///
    /// This is a global mutex-like state for operations which should be modal in the
    /// clients.
    running_state: RwLock<RunningState>,
    /// Mutex to avoid generating the key for the user more than once.
    pub(crate) generating_key_mutex: Mutex<()>,
    /// Mutex to enforce only a single running oauth2 is running.
    pub(crate) oauth2_mutex: Mutex<()>,
    /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent.
    pub(crate) wrong_pw_warning_mutex: Mutex<()>,
    pub(crate) translated_stockstrings: StockStrings,
    pub(crate) events: Events,

    pub(crate) scheduler: SchedulerState,
    pub(crate) ratelimit: RwLock<Ratelimit>,

    /// Recently loaded quota information, if any.
    /// Set to `None` if quota was never tried to load.
    pub(crate) quota: RwLock<Option<QuotaInfo>>,

    /// IMAP UID resync request.
    pub(crate) resync_request: AtomicBool,

    /// Notify about new messages.
    ///
    /// This causes [`Context::wait_next_msgs`] to wake up.
    pub(crate) new_msgs_notify: Notify,

    /// Server ID response if ID capability is supported
    /// and the server returned non-NIL on the inbox connection.
    /// <https://datatracker.ietf.org/doc/html/rfc2971>
    pub(crate) server_id: RwLock<Option<HashMap<String, String>>>,

    /// IMAP METADATA.
    pub(crate) metadata: RwLock<Option<ServerMetadata>>,

    pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>,

    /// ID for this `Context` in the current process.
    ///
    /// This allows for multiple `Context`s open in a single process where each context can
    /// be identified by this ID.
    pub(crate) id: u32,

    creation_time: tools::Time,

    /// The text of the last error logged and emitted as an event.
    /// If the ui wants to display an error after a failure,
    /// `last_error` should be used to avoid races with the event thread.
    pub(crate) last_error: std::sync::RwLock<String>,

    /// If debug logging is enabled, this contains all necessary information
    ///
    /// Standard RwLock instead of [`tokio::sync::RwLock`] is used
    /// because the lock is used from synchronous [`Context::emit_event`].
    pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>,

    /// Push subscriber to store device token
    /// and register for heartbeat notifications.
    pub(crate) push_subscriber: PushSubscriber,

    /// True if account has subscribed to push notifications via IMAP.
    pub(crate) push_subscribed: AtomicBool,

    /// Iroh for realtime peer channels.
    pub(crate) iroh: OnceCell<Iroh>,
}

/// The state of ongoing process.
#[derive(Debug)]
enum RunningState {
    /// Ongoing process is allocated.
    Running { cancel_sender: Sender<()> },

    /// Cancel signal has been sent, waiting for ongoing process to be freed.
    ShallStop { request: tools::Time },

    /// There is no ongoing process, a new one can be allocated.
    Stopped,
}

impl Default for RunningState {
    fn default() -> Self {
        Self::Stopped
    }
}

/// Return some info about deltachat-core
///
/// This contains information mostly about the library itself, the
/// actual keys and their values which will be present are not
/// guaranteed.  Calling [Context::get_info] also includes information
/// about the context on top of the information here.
pub fn get_info() -> BTreeMap<&'static str, String> {
    let mut res = BTreeMap::new();
    res.insert("deltachat_core_version", format!("v{}", &*DC_VERSION_STR));
    res.insert("sqlite_version", rusqlite::version().to_string());
    res.insert("arch", (std::mem::size_of::<usize>() * 8).to_string());
    res.insert("num_cpus", num_cpus::get().to_string());
    res.insert("level", "awesome".into());
    res
}

impl Context {
    /// Creates new context and opens the database.
    pub async fn new(
        dbfile: &Path,
        id: u32,
        events: Events,
        stock_strings: StockStrings,
    ) -> Result<Context> {
        let context =
            Self::new_closed(dbfile, id, events, stock_strings, Default::default()).await?;

        // Open the database if is not encrypted.
        if context.check_passphrase("".to_string()).await? {
            context.sql.open(&context, "".to_string()).await?;
        }
        Ok(context)
    }

    /// Creates new context without opening the database.
    pub async fn new_closed(
        dbfile: &Path,
        id: u32,
        events: Events,
        stockstrings: StockStrings,
        push_subscriber: PushSubscriber,
    ) -> Result<Context> {
        let mut blob_fname = OsString::new();
        blob_fname.push(dbfile.file_name().unwrap_or_default());
        blob_fname.push("-blobs");
        let blobdir = dbfile.with_file_name(blob_fname);
        if !blobdir.exists() {
            tokio::fs::create_dir_all(&blobdir).await?;
        }
        let context = Context::with_blobdir(
            dbfile.into(),
            blobdir,
            id,
            events,
            stockstrings,
            push_subscriber,
        )?;
        Ok(context)
    }

    /// Opens the database with the given passphrase.
    ///
    /// Returns true if passphrase is correct, false is passphrase is not correct. Fails on other
    /// errors.
    pub async fn open(&self, passphrase: String) -> Result<bool> {
        if self.sql.check_passphrase(passphrase.clone()).await? {
            self.sql.open(self, passphrase).await?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Changes encrypted database passphrase.
    pub async fn change_passphrase(&self, passphrase: String) -> Result<()> {
        self.sql.change_passphrase(passphrase).await?;
        Ok(())
    }

    /// Returns true if database is open.
    pub async fn is_open(&self) -> bool {
        self.sql.is_open().await
    }

    /// Tests the database passphrase.
    ///
    /// Returns true if passphrase is correct.
    ///
    /// Fails if database is already open.
    pub(crate) async fn check_passphrase(&self, passphrase: String) -> Result<bool> {
        self.sql.check_passphrase(passphrase).await
    }

    pub(crate) fn with_blobdir(
        dbfile: PathBuf,
        blobdir: PathBuf,
        id: u32,
        events: Events,
        stockstrings: StockStrings,
        push_subscriber: PushSubscriber,
    ) -> Result<Context> {
        ensure!(
            blobdir.is_dir(),
            "Blobdir does not exist: {}",
            blobdir.display()
        );

        let new_msgs_notify = Notify::new();
        // Notify once immediately to allow processing old messages
        // without starting I/O.
        new_msgs_notify.notify_one();

        let inner = InnerContext {
            id,
            blobdir,
            running_state: RwLock::new(Default::default()),
            sql: Sql::new(dbfile),
            smeared_timestamp: SmearedTimestamp::new(),
            generating_key_mutex: Mutex::new(()),
            oauth2_mutex: Mutex::new(()),
            wrong_pw_warning_mutex: Mutex::new(()),
            translated_stockstrings: stockstrings,
            events,
            scheduler: SchedulerState::new(),
            ratelimit: RwLock::new(Ratelimit::new(Duration::new(60, 0), 6.0)), // Allow at least 1 message every 10 seconds + a burst of 6.
            quota: RwLock::new(None),
            resync_request: AtomicBool::new(false),
            new_msgs_notify,
            server_id: RwLock::new(None),
            metadata: RwLock::new(None),
            creation_time: tools::Time::now(),
            last_full_folder_scan: Mutex::new(None),
            last_error: std::sync::RwLock::new("".to_string()),
            debug_logging: std::sync::RwLock::new(None),
            push_subscriber,
            push_subscribed: AtomicBool::new(false),
            iroh: OnceCell::new(),
        };

        let ctx = Context {
            inner: Arc::new(inner),
        };

        Ok(ctx)
    }

    /// Starts the IO scheduler.
    pub async fn start_io(&self) {
        if !self.is_configured().await.unwrap_or_default() {
            warn!(self, "can not start io on a context that is not configured");
            return;
        }

        if self.is_chatmail().await.unwrap_or_default() {
            let mut lock = self.ratelimit.write().await;
            // Allow at least 1 message every second + a burst of 3.
            *lock = Ratelimit::new(Duration::new(3, 0), 3.0);
        }

        // The next line is mainly for iOS:
        // iOS starts a separate process for receiving notifications and if the user concurrently
        // starts the app, the UI process opens the database but waits with calling start_io()
        // until the notifications process finishes.
        // Now, some configs may have changed, so, we need to invalidate the cache.
        self.sql.config_cache.write().await.clear();

        self.scheduler.start(self.clone()).await;
    }

    /// Stops the IO scheduler.
    pub async fn stop_io(&self) {
        self.scheduler.stop(self).await;
    }

    /// Restarts the IO scheduler if it was running before
    /// when it is not running this is an no-op
    pub async fn restart_io_if_running(&self) {
        self.scheduler.restart(self).await;
    }

    /// Indicate that the network likely has come back.
    pub async fn maybe_network(&self) {
        if let Some(iroh) = self.iroh.get() {
            iroh.network_change().await;
        }
        self.scheduler.maybe_network().await;
    }

    /// Returns true if an account is on a chatmail server.
    pub async fn is_chatmail(&self) -> Result<bool> {
        self.get_config_bool(Config::IsChatmail).await
    }

    /// Returns maximum number of recipients the provider allows to send a single email to.
    pub(crate) async fn get_max_smtp_rcpt_to(&self) -> Result<usize> {
        let is_chatmail = self.is_chatmail().await?;
        let val = self
            .get_configured_provider()
            .await?
            .and_then(|provider| provider.opt.max_smtp_rcpt_to)
            .map_or_else(
                || match is_chatmail {
                    true => usize::MAX,
                    false => constants::DEFAULT_MAX_SMTP_RCPT_TO,
                },
                usize::from,
            );
        Ok(val)
    }

    /// Does a single round of fetching from IMAP and returns.
    ///
    /// Can be used even if I/O is currently stopped.
    /// If I/O is currently stopped, starts a new IMAP connection
    /// and fetches from Inbox and DeltaChat folders.
    pub async fn background_fetch(&self) -> Result<()> {
        if !(self.is_configured().await?) {
            return Ok(());
        }

        let address = self.get_primary_self_addr().await?;
        let time_start = tools::Time::now();
        info!(self, "background_fetch started fetching {address}.");

        if self.scheduler.is_running().await {
            self.scheduler.maybe_network().await;

            // Wait until fetching is finished.
            // Ideally we could wait for connectivity change events,
            // but sleep loop is good enough.

            // First 100 ms sleep in chunks of 10 ms.
            for _ in 0..10 {
                if self.all_work_done().await {
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }

            // If we are not finished in 100 ms, keep waking up every 100 ms.
            while !self.all_work_done().await {
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            }
        } else {
            // Pause the scheduler to ensure another connection does not start
            // while we are fetching on a dedicated connection.
            let _pause_guard = self.scheduler.pause(self.clone()).await?;

            // Start a new dedicated connection.
            let mut connection = Imap::new_configured(self, channel::bounded(1).1).await?;
            let mut session = connection.prepare(self).await?;

            // Fetch IMAP folders.
            // Inbox is fetched before Mvbox because fetching from Inbox
            // may result in moving some messages to Mvbox.
            for folder_meaning in [FolderMeaning::Inbox, FolderMeaning::Mvbox] {
                if let Some((_folder_config, watch_folder)) =
                    convert_folder_meaning(self, folder_meaning).await?
                {
                    connection
                        .fetch_move_delete(self, &mut session, &watch_folder, folder_meaning)
                        .await?;
                }
            }

            // Update quota (to send warning if full) - but only check it once in a while.
            if self
                .quota_needs_update(DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT)
                .await
            {
                if let Err(err) = self.update_recent_quota(&mut session).await {
                    warn!(self, "Failed to update quota: {err:#}.");
                }
            }
        }

        info!(
            self,
            "background_fetch done for {address} took {:?}.",
            time_elapsed(&time_start),
        );

        Ok(())
    }

    pub(crate) async fn schedule_resync(&self) -> Result<()> {
        self.resync_request.store(true, Ordering::Relaxed);
        self.scheduler.interrupt_inbox().await;
        Ok(())
    }

    /// Returns a reference to the underlying SQL instance.
    ///
    /// Warning: this is only here for testing, not part of the public API.
    #[cfg(feature = "internals")]
    pub fn sql(&self) -> &Sql {
        &self.inner.sql
    }

    /// Returns database file path.
    pub fn get_dbfile(&self) -> &Path {
        self.sql.dbfile.as_path()
    }

    /// Returns blob directory path.
    pub fn get_blobdir(&self) -> &Path {
        self.blobdir.as_path()
    }

    /// Emits a single event.
    pub fn emit_event(&self, event: EventType) {
        {
            let lock = self.debug_logging.read().expect("RwLock is poisoned");
            if let Some(debug_logging) = &*lock {
                debug_logging.log_event(event.clone());
            }
        }
        self.events.emit(Event {
            id: self.id,
            typ: event,
        });
    }

    /// Emits a generic MsgsChanged event (without chat or message id)
    pub fn emit_msgs_changed_without_ids(&self) {
        self.emit_event(EventType::MsgsChanged {
            chat_id: ChatId::new(0),
            msg_id: MsgId::new(0),
        });
    }

    /// Emits a MsgsChanged event with specified chat and message ids
    pub fn emit_msgs_changed(&self, chat_id: ChatId, msg_id: MsgId) {
        self.emit_event(EventType::MsgsChanged { chat_id, msg_id });
        chatlist_events::emit_chatlist_changed(self);
        chatlist_events::emit_chatlist_item_changed(self, chat_id);
    }

    /// Emits an IncomingMsg event with specified chat and message ids
    pub fn emit_incoming_msg(&self, chat_id: ChatId, msg_id: MsgId) {
        self.emit_event(EventType::IncomingMsg { chat_id, msg_id });
        chatlist_events::emit_chatlist_changed(self);
        chatlist_events::emit_chatlist_item_changed(self, chat_id);
    }

    /// Emits an LocationChanged event and a WebxdcStatusUpdate in case there is a maps integration
    pub async fn emit_location_changed(&self, contact_id: Option<ContactId>) -> Result<()> {
        self.emit_event(EventType::LocationChanged(contact_id));

        if let Some(msg_id) = self
            .get_config_parsed::<u32>(Config::WebxdcIntegration)
            .await?
        {
            self.emit_event(EventType::WebxdcStatusUpdate {
                msg_id: MsgId::new(msg_id),
                status_update_serial: Default::default(),
            })
        }

        Ok(())
    }

    /// Returns a receiver for emitted events.
    ///
    /// Multiple emitters can be created, but note that in this case each emitted event will
    /// only be received by one of the emitters, not by all of them.
    pub fn get_event_emitter(&self) -> EventEmitter {
        self.events.get_emitter()
    }

    /// Get the ID of this context.
    pub fn get_id(&self) -> u32 {
        self.id
    }

    // Ongoing process allocation/free/check

    /// Tries to acquire the global UI "ongoing" mutex.
    ///
    /// This is for modal operations during which no other user actions are allowed.  Only
    /// one such operation is allowed at any given time.
    ///
    /// The return value is a cancel token, which will release the ongoing mutex when
    /// dropped.
    pub(crate) async fn alloc_ongoing(&self) -> Result<Receiver<()>> {
        let mut s = self.running_state.write().await;
        ensure!(
            matches!(*s, RunningState::Stopped),
            "There is already another ongoing process running."
        );

        let (sender, receiver) = channel::bounded(1);
        *s = RunningState::Running {
            cancel_sender: sender,
        };

        Ok(receiver)
    }

    pub(crate) async fn free_ongoing(&self) {
        let mut s = self.running_state.write().await;
        if let RunningState::ShallStop { request } = *s {
            info!(self, "Ongoing stopped in {:?}", time_elapsed(&request));
        }
        *s = RunningState::Stopped;
    }

    /// Signal an ongoing process to stop.
    pub async fn stop_ongoing(&self) {
        let mut s = self.running_state.write().await;
        match &*s {
            RunningState::Running { cancel_sender } => {
                if let Err(err) = cancel_sender.send(()).await {
                    warn!(self, "could not cancel ongoing: {:#}", err);
                }
                info!(self, "Signaling the ongoing process to stop ASAP.",);
                *s = RunningState::ShallStop {
                    request: tools::Time::now(),
                };
            }
            RunningState::ShallStop { .. } | RunningState::Stopped => {
                info!(self, "No ongoing process to stop.",);
            }
        }
    }

    #[allow(unused)]
    pub(crate) async fn shall_stop_ongoing(&self) -> bool {
        match &*self.running_state.read().await {
            RunningState::Running { .. } => false,
            RunningState::ShallStop { .. } | RunningState::Stopped => true,
        }
    }

    /*******************************************************************************
     * UI chat/message related API
     ******************************************************************************/

    /// Returns information about the context as key-value pairs.
    pub async fn get_info(&self) -> Result<BTreeMap<&'static str, String>> {
        let unset = "0";
        let l = EnteredLoginParam::load(self).await?;
        let l2 = ConfiguredLoginParam::load(self)
            .await?
            .map_or_else(|| "Not configured".to_string(), |param| param.to_string());
        let secondary_addrs = self.get_secondary_self_addrs().await?.join(", ");
        let displayname = self.get_config(Config::Displayname).await?;
        let chats = get_chat_cnt(self).await?;
        let unblocked_msgs = message::get_unblocked_msg_cnt(self).await;
        let request_msgs = message::get_request_msg_cnt(self).await;
        let contacts = Contact::get_real_cnt(self).await?;
        let is_configured = self.get_config_int(Config::Configured).await?;
        let proxy_enabled = self.get_config_int(Config::ProxyEnabled).await?;
        let dbversion = self
            .sql
            .get_raw_config_int("dbversion")
            .await?
            .unwrap_or_default();
        let journal_mode = self
            .sql
            .query_get_value("PRAGMA journal_mode;", ())
            .await?
            .unwrap_or_else(|| "unknown".to_string());
        let e2ee_enabled = self.get_config_int(Config::E2eeEnabled).await?;
        let mdns_enabled = self.get_config_int(Config::MdnsEnabled).await?;
        let bcc_self = self.get_config_int(Config::BccSelf).await?;
        let sync_msgs = self.get_config_int(Config::SyncMsgs).await?;
        let disable_idle = self.get_config_bool(Config::DisableIdle).await?;

        let prv_key_cnt = self.sql.count("SELECT COUNT(*) FROM keypairs;", ()).await?;

        let pub_key_cnt = self
            .sql
            .count("SELECT COUNT(*) FROM acpeerstates;", ())
            .await?;
        let fingerprint_str = match load_self_public_key(self).await {
            Ok(key) => key.dc_fingerprint().hex(),
            Err(err) => format!("<key failure: {err}>"),
        };

        let sentbox_watch = self.get_config_int(Config::SentboxWatch).await?;
        let mvbox_move = self.get_config_int(Config::MvboxMove).await?;
        let only_fetch_mvbox = self.get_config_int(Config::OnlyFetchMvbox).await?;
        let folders_configured = self
            .sql
            .get_raw_config_int(constants::DC_FOLDERS_CONFIGURED_KEY)
            .await?
            .unwrap_or_default();

        let configured_inbox_folder = self
            .get_config(Config::ConfiguredInboxFolder)
            .await?
            .unwrap_or_else(|| "<unset>".to_string());
        let configured_sentbox_folder = self
            .get_config(Config::ConfiguredSentboxFolder)
            .await?
            .unwrap_or_else(|| "<unset>".to_string());
        let configured_mvbox_folder = self
            .get_config(Config::ConfiguredMvboxFolder)
            .await?
            .unwrap_or_else(|| "<unset>".to_string());
        let configured_trash_folder = self
            .get_config(Config::ConfiguredTrashFolder)
            .await?
            .unwrap_or_else(|| "<unset>".to_string());

        let mut res = get_info();

        // insert values
        res.insert("bot", self.get_config_int(Config::Bot).await?.to_string());
        res.insert("number_of_chats", chats.to_string());
        res.insert("number_of_chat_messages", unblocked_msgs.to_string());
        res.insert("messages_in_contact_requests", request_msgs.to_string());
        res.insert("number_of_contacts", contacts.to_string());
        res.insert("database_dir", self.get_dbfile().display().to_string());
        res.insert("database_version", dbversion.to_string());
        res.insert(
            "database_encrypted",
            self.sql
                .is_encrypted()
                .await
                .map_or_else(|| "closed".to_string(), |b| b.to_string()),
        );
        res.insert("journal_mode", journal_mode);
        res.insert("blobdir", self.get_blobdir().display().to_string());
        res.insert("displayname", displayname.unwrap_or_else(|| unset.into()));
        res.insert(
            "selfavatar",
            self.get_config(Config::Selfavatar)
                .await?
                .unwrap_or_else(|| "<unset>".to_string()),
        );
        res.insert("is_configured", is_configured.to_string());
        res.insert("proxy_enabled", proxy_enabled.to_string());
        res.insert("entered_account_settings", l.to_string());
        res.insert("used_account_settings", l2);

        if let Some(server_id) = &*self.server_id.read().await {
            res.insert("imap_server_id", format!("{server_id:?}"));
        }

        res.insert("is_chatmail", self.is_chatmail().await?.to_string());
        res.insert(
            "fix_is_chatmail",
            self.get_config_bool(Config::FixIsChatmail)
                .await?
                .to_string(),
        );
        res.insert(
            "is_muted",
            self.get_config_bool(Config::IsMuted).await?.to_string(),
        );
        res.insert(
            "private_tag",
            self.get_config(Config::PrivateTag)
                .await?
                .unwrap_or_else(|| "<unset>".to_string()),
        );

        if let Some(metadata) = &*self.metadata.read().await {
            if let Some(comment) = &metadata.comment {
                res.insert("imap_server_comment", format!("{comment:?}"));
            }

            if let Some(admin) = &metadata.admin {
                res.insert("imap_server_admin", format!("{admin:?}"));
            }
        }

        res.insert("secondary_addrs", secondary_addrs);
        res.insert(
            "fetch_existing_msgs",
            self.get_config_int(Config::FetchExistingMsgs)
                .await?
                .to_string(),
        );
        res.insert(
            "fetched_existing_msgs",
            self.get_config_bool(Config::FetchedExistingMsgs)
                .await?
                .to_string(),
        );
        res.insert(
            "show_emails",
            self.get_config_int(Config::ShowEmails).await?.to_string(),
        );
        res.insert(
            "save_mime_headers",
            self.get_config_bool(Config::SaveMimeHeaders)
                .await?
                .to_string(),
        );
        res.insert(
            "download_limit",
            self.get_config_int(Config::DownloadLimit)
                .await?
                .to_string(),
        );
        res.insert("sentbox_watch", sentbox_watch.to_string());
        res.insert("mvbox_move", mvbox_move.to_string());
        res.insert("only_fetch_mvbox", only_fetch_mvbox.to_string());
        res.insert(
            constants::DC_FOLDERS_CONFIGURED_KEY,
            folders_configured.to_string(),
        );
        res.insert("configured_inbox_folder", configured_inbox_folder);
        res.insert("configured_sentbox_folder", configured_sentbox_folder);
        res.insert("configured_mvbox_folder", configured_mvbox_folder);
        res.insert("configured_trash_folder", configured_trash_folder);
        res.insert("mdns_enabled", mdns_enabled.to_string());
        res.insert("e2ee_enabled", e2ee_enabled.to_string());
        res.insert(
            "key_gen_type",
            self.get_config_int(Config::KeyGenType).await?.to_string(),
        );
        res.insert("bcc_self", bcc_self.to_string());
        res.insert("sync_msgs", sync_msgs.to_string());
        res.insert("disable_idle", disable_idle.to_string());
        res.insert("private_key_count", prv_key_cnt.to_string());
        res.insert("public_key_count", pub_key_cnt.to_string());
        res.insert("fingerprint", fingerprint_str);
        res.insert(
            "webrtc_instance",
            self.get_config(Config::WebrtcInstance)
                .await?
                .unwrap_or_else(|| "<unset>".to_string()),
        );
        res.insert(
            "media_quality",
            self.get_config_int(Config::MediaQuality).await?.to_string(),
        );
        res.insert(
            "delete_device_after",
            self.get_config_int(Config::DeleteDeviceAfter)
                .await?
                .to_string(),
        );
        res.insert(
            "delete_server_after",
            self.get_config_int(Config::DeleteServerAfter)
                .await?
                .to_string(),
        );
        res.insert(
            "delete_to_trash",
            self.get_config(Config::DeleteToTrash)
                .await?
                .unwrap_or_else(|| "<unset>".to_string()),
        );
        res.insert(
            "last_housekeeping",
            self.get_config_int(Config::LastHousekeeping)
                .await?
                .to_string(),
        );
        res.insert(
            "last_cant_decrypt_outgoing_msgs",
            self.get_config_int(Config::LastCantDecryptOutgoingMsgs)
                .await?
                .to_string(),
        );
        res.insert(
            "scan_all_folders_debounce_secs",
            self.get_config_int(Config::ScanAllFoldersDebounceSecs)
                .await?
                .to_string(),
        );
        res.insert(
            "quota_exceeding",
            self.get_config_int(Config::QuotaExceeding)
                .await?
                .to_string(),
        );
        res.insert(
            "authserv_id_candidates",
            self.get_config(Config::AuthservIdCandidates)
                .await?
                .unwrap_or_default(),
        );
        res.insert(
            "sign_unencrypted",
            self.get_config_int(Config::SignUnencrypted)
                .await?
                .to_string(),
        );
        res.insert(
            "protect_autocrypt",
            self.get_config_int(Config::ProtectAutocrypt)
                .await?
                .to_string(),
        );
        res.insert(
            "debug_logging",
            self.get_config_int(Config::DebugLogging).await?.to_string(),
        );
        res.insert(
            "last_msg_id",
            self.get_config_int(Config::LastMsgId).await?.to_string(),
        );
        res.insert(
            "gossip_period",
            self.get_config_int(Config::GossipPeriod).await?.to_string(),
        );
        res.insert(
            "verified_one_on_one_chats",
            self.get_config_bool(Config::VerifiedOneOnOneChats)
                .await?
                .to_string(),
        );
        res.insert(
            "webxdc_realtime_enabled",
            self.get_config_bool(Config::WebxdcRealtimeEnabled)
                .await?
                .to_string(),
        );

        let elapsed = time_elapsed(&self.creation_time);
        res.insert("uptime", duration_to_str(elapsed));

        Ok(res)
    }

    async fn get_self_report(&self) -> Result<String> {
        #[derive(Default)]
        struct ChatNumbers {
            protected: u32,
            protection_broken: u32,
            opportunistic_dc: u32,
            opportunistic_mua: u32,
            unencrypted_dc: u32,
            unencrypted_mua: u32,
        }

        let mut res = String::new();
        res += &format!("core_version {}\n", get_version_str());

        let num_msgs: u32 = self
            .sql
            .query_get_value(
                "SELECT COUNT(*) FROM msgs WHERE hidden=0 AND chat_id!=?",
                (DC_CHAT_ID_TRASH,),
            )
            .await?
            .unwrap_or_default();
        res += &format!("num_msgs {}\n", num_msgs);

        let num_chats: u32 = self
            .sql
            .query_get_value("SELECT COUNT(*) FROM chats WHERE id>9 AND blocked!=1", ())
            .await?
            .unwrap_or_default();
        res += &format!("num_chats {}\n", num_chats);

        let db_size = tokio::fs::metadata(&self.sql.dbfile).await?.len();
        res += &format!("db_size_bytes {}\n", db_size);

        let secret_key = &load_self_secret_key(self).await?.primary_key;
        let key_created = secret_key.created_at().timestamp();
        res += &format!("key_created {}\n", key_created);

        // how many of the chats active in the last months are:
        // - protected
        // - protection-broken
        // - opportunistic-encrypted and the contact uses Delta Chat
        // - opportunistic-encrypted and the contact uses a classical MUA
        // - unencrypted and the contact uses Delta Chat
        // - unencrypted and the contact uses a classical MUA
        let three_months_ago = time().saturating_sub(3600 * 24 * 30 * 3);
        let chats = self
            .sql
            .query_map(
                "SELECT c.protected, m.param, m.msgrmsg
                    FROM chats c
                    JOIN msgs m
                        ON c.id=m.chat_id
                        AND m.id=(
                                SELECT id
                                FROM msgs
                                WHERE chat_id=c.id
                                AND hidden=0
                                AND download_state=?
                                AND to_id!=?
                                ORDER BY timestamp DESC, id DESC LIMIT 1)
                    WHERE c.id>9
                    AND (c.blocked=0 OR c.blocked=2)
                    AND IFNULL(m.timestamp,c.created_timestamp) > ?
                    GROUP BY c.id",
                (DownloadState::Done, ContactId::INFO, three_months_ago),
                |row| {
                    let protected: ProtectionStatus = row.get(0)?;
                    let message_param: Params =
                        row.get::<_, String>(1)?.parse().unwrap_or_default();
                    let is_dc_message: bool = row.get(2)?;
                    Ok((protected, message_param, is_dc_message))
                },
                |rows| {
                    let mut chats = ChatNumbers::default();
                    for row in rows {
                        let (protected, message_param, is_dc_message) = row?;
                        let encrypted = message_param
                            .get_bool(Param::GuaranteeE2ee)
                            .unwrap_or(false);

                        if protected == ProtectionStatus::Protected {
                            chats.protected += 1;
                        } else if protected == ProtectionStatus::ProtectionBroken {
                            chats.protection_broken += 1;
                        } else if encrypted {
                            if is_dc_message {
                                chats.opportunistic_dc += 1;
                            } else {
                                chats.opportunistic_mua += 1;
                            }
                        } else if is_dc_message {
                            chats.unencrypted_dc += 1;
                        } else {
                            chats.unencrypted_mua += 1;
                        }
                    }
                    Ok(chats)
                },
            )
            .await?;
        res += &format!("chats_protected {}\n", chats.protected);
        res += &format!("chats_protection_broken {}\n", chats.protection_broken);
        res += &format!("chats_opportunistic_dc {}\n", chats.opportunistic_dc);
        res += &format!("chats_opportunistic_mua {}\n", chats.opportunistic_mua);
        res += &format!("chats_unencrypted_dc {}\n", chats.unencrypted_dc);
        res += &format!("chats_unencrypted_mua {}\n", chats.unencrypted_mua);

        let self_reporting_id = match self.get_config(Config::SelfReportingId).await? {
            Some(id) => id,
            None => {
                let id = create_id();
                self.set_config(Config::SelfReportingId, Some(&id)).await?;
                id
            }
        };
        res += &format!("self_reporting_id {}", self_reporting_id);

        Ok(res)
    }

    /// Drafts a message with statistics about the usage of Delta Chat.
    /// The user can inspect the message if they want, and then hit "Send".
    ///
    /// On the other end, a bot will receive the message and make it available
    /// to Delta Chat's developers.
    pub async fn draft_self_report(&self) -> Result<ChatId> {
        const SELF_REPORTING_BOT: &str = "self_reporting@testrun.org";

        let contact_id = Contact::create(self, "Statistics bot", SELF_REPORTING_BOT).await?;
        let chat_id = ChatId::create_for_contact(self, contact_id).await?;

        // We're including the bot's public key in Delta Chat
        // so that the first message to the bot can directly be encrypted:
        let public_key = SignedPublicKey::from_base64(
            "xjMEZbfBlBYJKwYBBAHaRw8BAQdABpLWS2PUIGGo4pslVt4R8sylP5wZihmhf1DTDr3oCM\
	        PNHDxzZWxmX3JlcG9ydGluZ0B0ZXN0cnVuLm9yZz7CiwQQFggAMwIZAQUCZbfBlAIbAwQLCQgHBhUI\
	        CQoLAgMWAgEWIQTS2i16sHeYTckGn284K3M5Z4oohAAKCRA4K3M5Z4oohD8dAQCQV7CoH6UP4PD+Nq\
	        I4kW5tbbqdh2AnDROg60qotmLExAEAxDfd3QHAK9f8b9qQUbLmHIztCLxhEuVbWPBEYeVW0gvOOARl\
	        t8GUEgorBgEEAZdVAQUBAQdAMBUhYoAAcI625vGZqnM5maPX4sGJ7qvJxPAFILPy6AcDAQgHwngEGB\
	        YIACAFAmW3wZQCGwwWIQTS2i16sHeYTckGn284K3M5Z4oohAAKCRA4K3M5Z4oohPwCAQCvzk1ObIkj\
	        2GqsuIfaULlgdnfdZY8LNary425CEfHZDQD5AblXVrlMO1frdlc/Vo9z3pEeCrfYdD7ITD3/OeVoiQ\
	        4=",
        )?;
        let mut peerstate = Peerstate::from_public_key(
            SELF_REPORTING_BOT,
            0,
            EncryptPreference::Mutual,
            &public_key,
        );
        let fingerprint = public_key.dc_fingerprint();
        peerstate.set_verified(public_key, fingerprint, "".to_string())?;
        peerstate.save_to_db(&self.sql).await?;
        chat_id
            .set_protection(self, ProtectionStatus::Protected, time(), Some(contact_id))
            .await?;

        let mut msg = Message::new_text(self.get_self_report().await?);

        chat_id.set_draft(self, Some(&mut msg)).await?;

        Ok(chat_id)
    }

    /// Get a list of fresh, unmuted messages in unblocked chats.
    ///
    /// The list starts with the most recent message
    /// and is typically used to show notifications.
    /// Moreover, the number of returned messages
    /// can be used for a badge counter on the app icon.
    pub async fn get_fresh_msgs(&self) -> Result<Vec<MsgId>> {
        let list = self
            .sql
            .query_map(
                concat!(
                    "SELECT m.id",
                    " FROM msgs m",
                    " LEFT JOIN contacts ct",
                    "        ON m.from_id=ct.id",
                    " LEFT JOIN chats c",
                    "        ON m.chat_id=c.id",
                    " WHERE m.state=?",
                    "   AND m.hidden=0",
                    "   AND m.chat_id>9",
                    "   AND ct.blocked=0",
                    "   AND c.blocked=0",
                    "   AND NOT(c.muted_until=-1 OR c.muted_until>?)",
                    " ORDER BY m.timestamp DESC,m.id DESC;"
                ),
                (MessageState::InFresh, time()),
                |row| row.get::<_, MsgId>(0),
                |rows| {
                    let mut list = Vec::new();
                    for row in rows {
                        list.push(row?);
                    }
                    Ok(list)
                },
            )
            .await?;
        Ok(list)
    }

    /// Returns a list of messages with database ID higher than requested.
    ///
    /// Blocked contacts and chats are excluded,
    /// but self-sent messages and contact requests are included in the results.
    pub async fn get_next_msgs(&self) -> Result<Vec<MsgId>> {
        let last_msg_id = match self.get_config(Config::LastMsgId).await? {
            Some(s) => MsgId::new(s.parse()?),
            None => {
                // If `last_msg_id` is not set yet,
                // subtract 1 from the last id,
                // so a single message is returned and can
                // be marked as seen.
                self.sql
                    .query_row(
                        "SELECT IFNULL((SELECT MAX(id) - 1 FROM msgs), 0)",
                        (),
                        |row| {
                            let msg_id: MsgId = row.get(0)?;
                            Ok(msg_id)
                        },
                    )
                    .await?
            }
        };

        let list = self
            .sql
            .query_map(
                "SELECT m.id
                     FROM msgs m
                     LEFT JOIN contacts ct
                            ON m.from_id=ct.id
                     LEFT JOIN chats c
                            ON m.chat_id=c.id
                     WHERE m.id>?
                       AND m.hidden=0
                       AND m.chat_id>9
                       AND ct.blocked=0
                       AND c.blocked!=1
                     ORDER BY m.id ASC",
                (
                    last_msg_id.to_u32(), // Explicitly convert to u32 because 0 is allowed.
                ),
                |row| {
                    let msg_id: MsgId = row.get(0)?;
                    Ok(msg_id)
                },
                |rows| {
                    let mut list = Vec::new();
                    for row in rows {
                        list.push(row?);
                    }
                    Ok(list)
                },
            )
            .await?;
        Ok(list)
    }

    /// Returns a list of messages with database ID higher than last marked as seen.
    ///
    /// This function is supposed to be used by bot to request messages
    /// that are not processed yet.
    ///
    /// Waits for notification and returns a result.
    /// Note that the result may be empty if the message is deleted
    /// shortly after notification or notification is manually triggered
    /// to interrupt waiting.
    /// Notification may be manually triggered by calling [`Self::stop_io`].
    pub async fn wait_next_msgs(&self) -> Result<Vec<MsgId>> {
        self.new_msgs_notify.notified().await;
        let list = self.get_next_msgs().await?;
        Ok(list)
    }

    /// Searches for messages containing the query string case-insensitively.
    ///
    /// If `chat_id` is provided this searches only for messages in this chat, if `chat_id`
    /// is `None` this searches messages from all chats.
    ///
    /// NB: Wrt the search in long messages which are shown truncated with the "Show Full Message…"
    /// button, we only look at the first several kilobytes. Let's not fix this -- one can send a
    /// dictionary in the message that matches any reasonable search request, but the user won't see
    /// the match because they should tap on "Show Full Message…" for that. Probably such messages
    /// would only clutter search results.
    pub async fn search_msgs(&self, chat_id: Option<ChatId>, query: &str) -> Result<Vec<MsgId>> {
        let real_query = query.trim().to_lowercase();
        if real_query.is_empty() {
            return Ok(Vec::new());
        }
        let str_like_in_text = format!("%{real_query}%");

        let list = if let Some(chat_id) = chat_id {
            self.sql
                .query_map(
                    "SELECT m.id AS id
                 FROM msgs m
                 LEFT JOIN contacts ct
                        ON m.from_id=ct.id
                 WHERE m.chat_id=?
                   AND m.hidden=0
                   AND ct.blocked=0
                   AND IFNULL(txt_normalized, txt) LIKE ?
                 ORDER BY m.timestamp,m.id;",
                    (chat_id, str_like_in_text),
                    |row| row.get::<_, MsgId>("id"),
                    |rows| {
                        let mut ret = Vec::new();
                        for id in rows {
                            ret.push(id?);
                        }
                        Ok(ret)
                    },
                )
                .await?
        } else {
            // For performance reasons results are sorted only by `id`, that is in the order of
            // message reception.
            //
            // Unlike chat view, sorting by `timestamp` is not necessary but slows down the query by
            // ~25% according to benchmarks.
            //
            // To speed up incremental search, where queries for few characters usually return lots
            // of unwanted results that are discarded moments later, we added `LIMIT 1000`.
            // According to some tests, this limit speeds up eg. 2 character searches by factor 10.
            // The limit is documented and UI may add a hint when getting 1000 results.
            self.sql
                .query_map(
                    "SELECT m.id AS id
                 FROM msgs m
                 LEFT JOIN contacts ct
                        ON m.from_id=ct.id
                 LEFT JOIN chats c
                        ON m.chat_id=c.id
                 WHERE m.chat_id>9
                   AND m.hidden=0
                   AND c.blocked!=1
                   AND ct.blocked=0
                   AND IFNULL(txt_normalized, txt) LIKE ?
                 ORDER BY m.id DESC LIMIT 1000",
                    (str_like_in_text,),
                    |row| row.get::<_, MsgId>("id"),
                    |rows| {
                        let mut ret = Vec::new();
                        for id in rows {
                            ret.push(id?);
                        }
                        Ok(ret)
                    },
                )
                .await?
        };

        Ok(list)
    }

    /// Returns true if given folder name is the name of the inbox.
    pub async fn is_inbox(&self, folder_name: &str) -> Result<bool> {
        let inbox = self.get_config(Config::ConfiguredInboxFolder).await?;
        Ok(inbox.as_deref() == Some(folder_name))
    }

    /// Returns true if given folder name is the name of the "sent" folder.
    pub async fn is_sentbox(&self, folder_name: &str) -> Result<bool> {
        let sentbox = self.get_config(Config::ConfiguredSentboxFolder).await?;
        Ok(sentbox.as_deref() == Some(folder_name))
    }

    /// Returns true if given folder name is the name of the "DeltaChat" folder.
    pub async fn is_mvbox(&self, folder_name: &str) -> Result<bool> {
        let mvbox = self.get_config(Config::ConfiguredMvboxFolder).await?;
        Ok(mvbox.as_deref() == Some(folder_name))
    }

    /// Returns true if given folder name is the name of the trash folder.
    pub async fn is_trash(&self, folder_name: &str) -> Result<bool> {
        let trash = self.get_config(Config::ConfiguredTrashFolder).await?;
        Ok(trash.as_deref() == Some(folder_name))
    }

    pub(crate) async fn should_delete_to_trash(&self) -> Result<bool> {
        if let Some(v) = self.get_config_bool_opt(Config::DeleteToTrash).await? {
            return Ok(v);
        }
        if let Some(provider) = self.get_configured_provider().await? {
            return Ok(provider.opt.delete_to_trash);
        }
        Ok(false)
    }

    /// Returns `target` for deleted messages as per `imap` table. Empty string means "delete w/o
    /// moving to trash".
    pub(crate) async fn get_delete_msgs_target(&self) -> Result<String> {
        if !self.should_delete_to_trash().await? {
            return Ok("".into());
        }
        self.get_config(Config::ConfiguredTrashFolder)
            .await?
            .context("No configured trash folder")
    }

    pub(crate) fn derive_blobdir(dbfile: &Path) -> PathBuf {
        let mut blob_fname = OsString::new();
        blob_fname.push(dbfile.file_name().unwrap_or_default());
        blob_fname.push("-blobs");
        dbfile.with_file_name(blob_fname)
    }

    pub(crate) fn derive_walfile(dbfile: &Path) -> PathBuf {
        let mut wal_fname = OsString::new();
        wal_fname.push(dbfile.file_name().unwrap_or_default());
        wal_fname.push("-wal");
        dbfile.with_file_name(wal_fname)
    }
}

/// Returns core version as a string.
pub fn get_version_str() -> &'static str {
    &DC_VERSION_STR
}

#[cfg(test)]
mod tests {
    use anyhow::Context as _;
    use strum::IntoEnumIterator;
    use tempfile::tempdir;

    use super::*;
    use crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration};
    use crate::chatlist::Chatlist;
    use crate::constants::Chattype;
    use crate::mimeparser::SystemMessage;
    use crate::receive_imf::receive_imf;
    use crate::test_utils::{get_chat_msg, TestContext};
    use crate::tools::{create_outgoing_rfc724_mid, SystemTime};

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_wrong_db() -> Result<()> {
        let tmp = tempfile::tempdir()?;
        let dbfile = tmp.path().join("db.sqlite");
        tokio::fs::write(&dbfile, b"123").await?;
        let res = Context::new(&dbfile, 1, Events::new(), StockStrings::new()).await?;

        // Broken database is indistinguishable from encrypted one.
        assert_eq!(res.is_open().await, false);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_get_fresh_msgs() {
        let t = TestContext::new().await;
        let fresh = t.get_fresh_msgs().await.unwrap();
        assert!(fresh.is_empty())
    }

    async fn receive_msg(t: &TestContext, chat: &Chat) {
        let members = get_chat_contacts(t, chat.id).await.unwrap();
        let contact = Contact::get_by_id(t, *members.first().unwrap())
            .await
            .unwrap();
        let msg = format!(
            "From: {}\n\
             To: alice@example.org\n\
             Message-ID: <{}>\n\
             Chat-Version: 1.0\n\
             Date: Sun, 22 Mar 2020 22:37:57 +0000\n\
             \n\
             hello\n",
            contact.get_addr(),
            create_outgoing_rfc724_mid()
        );
        println!("{msg}");
        receive_imf(t, msg.as_bytes(), false).await.unwrap();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_get_fresh_msgs_and_muted_chats() {
        // receive various mails in 3 chats
        let t = TestContext::new_alice().await;
        let bob = t.create_chat_with_contact("", "bob@g.it").await;
        let claire = t.create_chat_with_contact("", "claire@g.it").await;
        let dave = t.create_chat_with_contact("", "dave@g.it").await;
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 0);

        receive_msg(&t, &bob).await;
        assert_eq!(get_chat_msgs(&t, bob.id).await.unwrap().len(), 1);
        assert_eq!(bob.id.get_fresh_msg_cnt(&t).await.unwrap(), 1);
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 1);

        receive_msg(&t, &claire).await;
        receive_msg(&t, &claire).await;
        assert_eq!(get_chat_msgs(&t, claire.id).await.unwrap().len(), 2);
        assert_eq!(claire.id.get_fresh_msg_cnt(&t).await.unwrap(), 2);
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 3);

        receive_msg(&t, &dave).await;
        receive_msg(&t, &dave).await;
        receive_msg(&t, &dave).await;
        assert_eq!(get_chat_msgs(&t, dave.id).await.unwrap().len(), 3);
        assert_eq!(dave.id.get_fresh_msg_cnt(&t).await.unwrap(), 3);
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 6);

        // mute one of the chats
        set_muted(&t, claire.id, MuteDuration::Forever)
            .await
            .unwrap();
        assert_eq!(claire.id.get_fresh_msg_cnt(&t).await.unwrap(), 2);
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 4); // muted claires messages are no longer counted

        // receive more messages
        receive_msg(&t, &bob).await;
        receive_msg(&t, &claire).await;
        receive_msg(&t, &dave).await;
        assert_eq!(get_chat_msgs(&t, claire.id).await.unwrap().len(), 3);
        assert_eq!(claire.id.get_fresh_msg_cnt(&t).await.unwrap(), 3);
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 6); // muted claire is not counted

        // unmute claire again
        set_muted(&t, claire.id, MuteDuration::NotMuted)
            .await
            .unwrap();
        assert_eq!(claire.id.get_fresh_msg_cnt(&t).await.unwrap(), 3);
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 9); // claire is counted again
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_get_fresh_msgs_and_muted_until() {
        let t = TestContext::new_alice().await;
        let bob = t.create_chat_with_contact("", "bob@g.it").await;
        receive_msg(&t, &bob).await;
        assert_eq!(get_chat_msgs(&t, bob.id).await.unwrap().len(), 1);

        // chat is unmuted by default, here and in the following assert(),
        // we check mainly that the SQL-statements in is_muted() and get_fresh_msgs()
        // have the same view to the database.
        assert!(!bob.is_muted());
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 1);

        // test get_fresh_msgs() with mute_until in the future
        set_muted(
            &t,
            bob.id,
            MuteDuration::Until(SystemTime::now() + Duration::from_secs(3600)),
        )
        .await
        .unwrap();
        let bob = Chat::load_from_db(&t, bob.id).await.unwrap();
        assert!(bob.is_muted());
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 0);

        // to test get_fresh_msgs() with mute_until in the past,
        // we need to modify the database directly
        t.sql
            .execute(
                "UPDATE chats SET muted_until=? WHERE id=?;",
                (time() - 3600, bob.id),
            )
            .await
            .unwrap();
        let bob = Chat::load_from_db(&t, bob.id).await.unwrap();
        assert!(!bob.is_muted());
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 1);

        // test get_fresh_msgs() with "forever" mute_until
        set_muted(&t, bob.id, MuteDuration::Forever).await.unwrap();
        let bob = Chat::load_from_db(&t, bob.id).await.unwrap();
        assert!(bob.is_muted());
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 0);

        // to test get_fresh_msgs() with invalid mute_until (everything < -1),
        // that results in "muted forever" by definition.
        t.sql
            .execute("UPDATE chats SET muted_until=-2 WHERE id=?;", (bob.id,))
            .await
            .unwrap();
        let bob = Chat::load_from_db(&t, bob.id).await.unwrap();
        assert!(!bob.is_muted());
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 1);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_muted_context() -> Result<()> {
        let t = TestContext::new_alice().await;
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 0);
        t.set_config(Config::IsMuted, Some("1")).await?;
        let chat = t.create_chat_with_contact("", "bob@g.it").await;
        receive_msg(&t, &chat).await;

        // muted contexts should still show dimmed badge counters eg. in the sidebars,
        // (same as muted chats show dimmed badge counters in the chatlist)
        // therefore the fresh messages count should not be affected.
        assert_eq!(t.get_fresh_msgs().await.unwrap().len(), 1);

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_blobdir_exists() {
        let tmp = tempfile::tempdir().unwrap();
        let dbfile = tmp.path().join("db.sqlite");
        Context::new(&dbfile, 1, Events::new(), StockStrings::new())
            .await
            .unwrap();
        let blobdir = tmp.path().join("db.sqlite-blobs");
        assert!(blobdir.is_dir());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_wrong_blogdir() {
        let tmp = tempfile::tempdir().unwrap();
        let dbfile = tmp.path().join("db.sqlite");
        let blobdir = tmp.path().join("db.sqlite-blobs");
        tokio::fs::write(&blobdir, b"123").await.unwrap();
        let res = Context::new(&dbfile, 1, Events::new(), StockStrings::new()).await;
        assert!(res.is_err());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_sqlite_parent_not_exists() {
        let tmp = tempfile::tempdir().unwrap();
        let subdir = tmp.path().join("subdir");
        let dbfile = subdir.join("db.sqlite");
        let dbfile2 = dbfile.clone();
        Context::new(&dbfile, 1, Events::new(), StockStrings::new())
            .await
            .unwrap();
        assert!(subdir.is_dir());
        assert!(dbfile2.is_file());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_with_empty_blobdir() {
        let tmp = tempfile::tempdir().unwrap();
        let dbfile = tmp.path().join("db.sqlite");
        let blobdir = PathBuf::new();
        let res = Context::with_blobdir(
            dbfile,
            blobdir,
            1,
            Events::new(),
            StockStrings::new(),
            Default::default(),
        );
        assert!(res.is_err());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_with_blobdir_not_exists() {
        let tmp = tempfile::tempdir().unwrap();
        let dbfile = tmp.path().join("db.sqlite");
        let blobdir = tmp.path().join("blobs");
        let res = Context::with_blobdir(
            dbfile,
            blobdir,
            1,
            Events::new(),
            StockStrings::new(),
            Default::default(),
        );
        assert!(res.is_err());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn no_crashes_on_context_deref() {
        let t = TestContext::new().await;
        std::mem::drop(t);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_get_info() {
        let t = TestContext::new().await;

        let info = t.get_info().await.unwrap();
        assert!(info.contains_key("database_dir"));
    }

    #[test]
    fn test_get_info_no_context() {
        let info = get_info();
        assert!(info.contains_key("deltachat_core_version"));
        assert!(!info.contains_key("database_dir"));
        assert_eq!(info.get("level").unwrap(), "awesome");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_get_info_completeness() {
        // For easier debugging,
        // get_info() shall return all important information configurable by the Config-values.
        //
        // There are exceptions for Config-values considered to be unimportant,
        // too sensitive or summarized in another item.
        let skip_from_get_info = vec![
            "addr",
            "displayname",
            "imap_certificate_checks",
            "mail_server",
            "mail_user",
            "mail_pw",
            "mail_port",
            "mail_security",
            "notify_about_wrong_pw",
            "self_reporting_id",
            "selfstatus",
            "send_server",
            "send_user",
            "send_pw",
            "send_port",
            "send_security",
            "server_flags",
            "skip_start_messages",
            "smtp_certificate_checks",
            "proxy_url",      // May contain passwords, don't leak it to the logs.
            "socks5_enabled", // SOCKS5 options are deprecated.
            "socks5_host",
            "socks5_port",
            "socks5_user",
            "socks5_password",
            "key_id",
            "webxdc_integration",
        ];
        let t = TestContext::new().await;
        let info = t.get_info().await.unwrap();
        for key in Config::iter() {
            let key: String = key.to_string();
            if !skip_from_get_info.contains(&&*key)
                && !key.starts_with("configured")
                && !key.starts_with("sys.")
            {
                assert!(
                    info.contains_key(&*key),
                    "'{key}' missing in get_info() output"
                );
            }
        }
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_search_msgs() -> Result<()> {
        let alice = TestContext::new_alice().await;
        let self_talk = ChatId::create_for_contact(&alice, ContactId::SELF).await?;
        let chat = alice
            .create_chat_with_contact("Bob", "bob@example.org")
            .await;

        // Global search finds nothing.
        let res = alice.search_msgs(None, "foo").await?;
        assert!(res.is_empty());

        // Search in chat with Bob finds nothing.
        let res = alice.search_msgs(Some(chat.id), "foo").await?;
        assert!(res.is_empty());

        // Add messages to chat with Bob.
        let mut msg1 = Message::new_text("foobar".to_string());
        send_msg(&alice, chat.id, &mut msg1).await?;

        let mut msg2 = Message::new_text("barbaz".to_string());
        send_msg(&alice, chat.id, &mut msg2).await?;

        alice.send_text(chat.id, "Δ-Chat").await;

        // Global search with a part of text finds the message.
        let res = alice.search_msgs(None, "ob").await?;
        assert_eq!(res.len(), 1);

        // Global search for "bar" matches both "foobar" and "barbaz".
        let res = alice.search_msgs(None, "bar").await?;
        assert_eq!(res.len(), 2);

        // Message added later is returned first.
        assert_eq!(res.first(), Some(&msg2.id));
        assert_eq!(res.get(1), Some(&msg1.id));

        // Search is case-insensitive.
        for chat_id in [None, Some(chat.id)] {
            let res = alice.search_msgs(chat_id, "δ-chat").await?;
            assert_eq!(res.len(), 1);
        }

        // Global search with longer text does not find any message.
        let res = alice.search_msgs(None, "foobarbaz").await?;
        assert!(res.is_empty());

        // Search for random string finds nothing.
        let res = alice.search_msgs(None, "abc").await?;
        assert!(res.is_empty());

        // Search in chat with Bob finds the message.
        let res = alice.search_msgs(Some(chat.id), "foo").await?;
        assert_eq!(res.len(), 1);

        // Search in Saved Messages does not find the message.
        let res = alice.search_msgs(Some(self_talk), "foo").await?;
        assert!(res.is_empty());

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_search_unaccepted_requests() -> Result<()> {
        let t = TestContext::new_alice().await;
        receive_imf(
            &t,
            b"From: BobBar <bob@example.org>\n\
                 To: alice@example.org\n\
                 Subject: foo\n\
                 Message-ID: <msg1234@example.org>\n\
                 Chat-Version: 1.0\n\
                 Date: Tue, 25 Oct 2022 13:37:00 +0000\n\
                 \n\
                 hello bob, foobar test!\n",
            false,
        )
        .await?;
        let chat_id = t.get_last_msg().await.get_chat_id();
        let chat = Chat::load_from_db(&t, chat_id).await?;
        assert_eq!(chat.get_type(), Chattype::Single);
        assert!(chat.is_contact_request());

        assert_eq!(Chatlist::try_load(&t, 0, None, None).await?.len(), 1);
        assert_eq!(
            Chatlist::try_load(&t, 0, Some("BobBar"), None).await?.len(),
            1
        );
        assert_eq!(t.search_msgs(None, "foobar").await?.len(), 1);
        assert_eq!(t.search_msgs(Some(chat_id), "foobar").await?.len(), 1);

        chat_id.block(&t).await?;

        assert_eq!(Chatlist::try_load(&t, 0, None, None).await?.len(), 0);
        assert_eq!(
            Chatlist::try_load(&t, 0, Some("BobBar"), None).await?.len(),
            0
        );
        assert_eq!(t.search_msgs(None, "foobar").await?.len(), 0);
        assert_eq!(t.search_msgs(Some(chat_id), "foobar").await?.len(), 0);

        let contact_ids = get_chat_contacts(&t, chat_id).await?;
        Contact::unblock(&t, *contact_ids.first().unwrap()).await?;

        assert_eq!(Chatlist::try_load(&t, 0, None, None).await?.len(), 1);
        assert_eq!(
            Chatlist::try_load(&t, 0, Some("BobBar"), None).await?.len(),
            1
        );
        assert_eq!(t.search_msgs(None, "foobar").await?.len(), 1);
        assert_eq!(t.search_msgs(Some(chat_id), "foobar").await?.len(), 1);

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_limit_search_msgs() -> Result<()> {
        let alice = TestContext::new_alice().await;
        let chat = alice
            .create_chat_with_contact("Bob", "bob@example.org")
            .await;

        // Add 999 messages
        let mut msg = Message::new_text("foobar".to_string());
        for _ in 0..999 {
            send_msg(&alice, chat.id, &mut msg).await?;
        }
        let res = alice.search_msgs(None, "foo").await?;
        assert_eq!(res.len(), 999);

        // Add one more message, no limit yet
        send_msg(&alice, chat.id, &mut msg).await?;
        let res = alice.search_msgs(None, "foo").await?;
        assert_eq!(res.len(), 1000);

        // Add one more message, that one is truncated then
        send_msg(&alice, chat.id, &mut msg).await?;
        let res = alice.search_msgs(None, "foo").await?;
        assert_eq!(res.len(), 1000);

        // In-chat should not be not limited
        let res = alice.search_msgs(Some(chat.id), "foo").await?;
        assert_eq!(res.len(), 1001);

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_check_passphrase() -> Result<()> {
        let dir = tempdir()?;
        let dbfile = dir.path().join("db.sqlite");

        let context = ContextBuilder::new(dbfile.clone())
            .with_id(1)
            .build()
            .await
            .context("failed to create context")?;
        assert_eq!(context.open("foo".to_string()).await?, true);
        assert_eq!(context.is_open().await, true);
        drop(context);

        let context = ContextBuilder::new(dbfile)
            .with_id(2)
            .build()
            .await
            .context("failed to create context")?;
        assert_eq!(context.is_open().await, false);
        assert_eq!(context.check_passphrase("bar".to_string()).await?, false);
        assert_eq!(context.open("false".to_string()).await?, false);
        assert_eq!(context.open("foo".to_string()).await?, true);

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_context_change_passphrase() -> Result<()> {
        let dir = tempdir()?;
        let dbfile = dir.path().join("db.sqlite");

        let context = ContextBuilder::new(dbfile)
            .with_id(1)
            .build()
            .await
            .context("failed to create context")?;
        assert_eq!(context.open("foo".to_string()).await?, true);
        assert_eq!(context.is_open().await, true);

        context
            .set_config(Config::Addr, Some("alice@example.org"))
            .await?;

        context
            .change_passphrase("bar".to_string())
            .await
            .context("Failed to change passphrase")?;

        assert_eq!(
            context.get_config(Config::Addr).await?.unwrap(),
            "alice@example.org"
        );

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_ongoing() -> Result<()> {
        let context = TestContext::new().await;

        // No ongoing process allocated.
        assert!(context.shall_stop_ongoing().await);

        let receiver = context.alloc_ongoing().await?;

        // Cannot allocate another ongoing process while the first one is running.
        assert!(context.alloc_ongoing().await.is_err());

        // Stop signal is not sent yet.
        assert!(receiver.try_recv().is_err());

        assert!(!context.shall_stop_ongoing().await);

        // Send the stop signal.
        context.stop_ongoing().await;

        // Receive stop signal.
        receiver.recv().await?;

        assert!(context.shall_stop_ongoing().await);

        // Ongoing process is still running even though stop signal was received,
        // so another one cannot be allocated.
        assert!(context.alloc_ongoing().await.is_err());

        context.free_ongoing().await;

        // No ongoing process allocated, should have been stopped already.
        assert!(context.shall_stop_ongoing().await);

        // Another ongoing process can be allocated now.
        let _receiver = context.alloc_ongoing().await?;

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_get_next_msgs() -> Result<()> {
        let alice = TestContext::new_alice().await;
        let bob = TestContext::new_bob().await;

        let alice_chat = alice.create_chat(&bob).await;

        assert!(alice.get_next_msgs().await?.is_empty());
        assert!(bob.get_next_msgs().await?.is_empty());

        let sent_msg = alice.send_text(alice_chat.id, "Hi Bob").await;
        let received_msg = bob.recv_msg(&sent_msg).await;

        let bob_next_msg_ids = bob.get_next_msgs().await?;
        assert_eq!(bob_next_msg_ids.len(), 1);
        assert_eq!(bob_next_msg_ids.first(), Some(&received_msg.id));

        bob.set_config_u32(Config::LastMsgId, received_msg.id.to_u32())
            .await?;
        assert!(bob.get_next_msgs().await?.is_empty());

        // Next messages include self-sent messages.
        let alice_next_msg_ids = alice.get_next_msgs().await?;
        assert_eq!(alice_next_msg_ids.len(), 1);
        assert_eq!(alice_next_msg_ids.first(), Some(&sent_msg.sender_msg_id));

        alice
            .set_config_u32(Config::LastMsgId, sent_msg.sender_msg_id.to_u32())
            .await?;
        assert!(alice.get_next_msgs().await?.is_empty());

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_draft_self_report() -> Result<()> {
        let alice = TestContext::new_alice().await;

        let chat_id = alice.draft_self_report().await?;
        let msg = get_chat_msg(&alice, chat_id, 0, 1).await;
        assert_eq!(msg.get_info_type(), SystemMessage::ChatProtectionEnabled);

        let chat = Chat::load_from_db(&alice, chat_id).await?;
        assert!(chat.is_protected());

        let mut draft = chat_id.get_draft(&alice).await?.unwrap();
        assert!(draft.text.starts_with("core_version"));

        // Test that sending into the protected chat works:
        let _sent = alice.send_msg(chat_id, &mut draft).await;

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_cache_is_cleared_when_io_is_started() -> Result<()> {
        let alice = TestContext::new_alice().await;
        assert_eq!(
            alice.get_config(Config::ShowEmails).await?,
            Some("2".to_string())
        );

        // Change the config circumventing the cache
        // This simulates what the notification plugin on iOS might do
        // because it runs in a different process
        alice
            .sql
            .execute(
                "INSERT OR REPLACE INTO config (keyname, value) VALUES ('show_emails', '0')",
                (),
            )
            .await?;

        // Alice's Delta Chat doesn't know about it yet:
        assert_eq!(
            alice.get_config(Config::ShowEmails).await?,
            Some("2".to_string())
        );

        // Starting IO will fail of course because no server settings are configured,
        // but it should invalidate the caches:
        alice.start_io().await;

        assert_eq!(
            alice.get_config(Config::ShowEmails).await?,
            Some("0".to_string())
        );

        Ok(())
    }
}