File size: 75,650 Bytes
0220cd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
use mailparse::ParsedMail;
use std::mem;

use super::*;
use crate::{
    chat,
    chatlist::Chatlist,
    constants::{self, Blocked, DC_DESIRED_TEXT_LEN, DC_ELLIPSIS},
    message::{MessageState, MessengerMessage},
    receive_imf::receive_imf,
    test_utils::{TestContext, TestContextManager},
    tools::time,
};

impl AvatarAction {
    pub fn is_change(&self) -> bool {
        match self {
            AvatarAction::Delete => false,
            AvatarAction::Change(_) => true,
        }
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mimeparser_fromheader() {
    let ctx = TestContext::new_alice().await;

    let mimemsg = MimeMessage::from_bytes(&ctx, b"From: g@c.de\n\nhi", None)
        .await
        .unwrap();
    let contact = mimemsg.from;
    assert_eq!(contact.addr, "g@c.de");
    assert_eq!(contact.display_name, None);

    let mimemsg = MimeMessage::from_bytes(&ctx, b"From:   g@c.de  \n\nhi", None)
        .await
        .unwrap();
    let contact = mimemsg.from;
    assert_eq!(contact.addr, "g@c.de");
    assert_eq!(contact.display_name, None);

    let mimemsg = MimeMessage::from_bytes(&ctx, b"From: <g@c.de>\n\nhi", None)
        .await
        .unwrap();
    let contact = mimemsg.from;
    assert_eq!(contact.addr, "g@c.de");
    assert_eq!(contact.display_name, None);

    let mimemsg = MimeMessage::from_bytes(&ctx, b"From: Goetz C <g@c.de>\n\nhi", None)
        .await
        .unwrap();
    let contact = mimemsg.from;
    assert_eq!(contact.addr, "g@c.de");
    assert_eq!(contact.display_name, Some("Goetz C".to_string()));

    let mimemsg = MimeMessage::from_bytes(&ctx, b"From: \"Goetz C\" <g@c.de>\n\nhi", None)
        .await
        .unwrap();
    let contact = mimemsg.from;
    assert_eq!(contact.addr, "g@c.de");
    assert_eq!(contact.display_name, Some("Goetz C".to_string()));

    let mimemsg =
        MimeMessage::from_bytes(&ctx, b"From: =?utf-8?q?G=C3=B6tz?= C <g@c.de>\n\nhi", None)
            .await
            .unwrap();
    let contact = mimemsg.from;
    assert_eq!(contact.addr, "g@c.de");
    assert_eq!(contact.display_name, Some("Götz C".to_string()));

    // although RFC 2047 says, encoded-words shall not appear inside quoted-string,
    // this combination is used in the wild eg. by MailMate
    let mimemsg = MimeMessage::from_bytes(
        &ctx,
        b"From: \"=?utf-8?q?G=C3=B6tz?= C\" <g@c.de>\n\nhi",
        None,
    )
    .await
    .unwrap();
    let contact = mimemsg.from;
    assert_eq!(contact.addr, "g@c.de");
    assert_eq!(contact.display_name, Some("Götz C".to_string()));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mimeparser_crash() {
    let context = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/issue_523.txt");
    let mimeparser = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();

    assert_eq!(mimeparser.get_subject(), None);
    assert_eq!(mimeparser.parts.len(), 1);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_rfc724_mid_exists() {
    let context = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/mail_with_message_id.txt");
    let mimeparser = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();

    assert_eq!(
        mimeparser.get_rfc724_mid(),
        Some("2dfdbde7@example.org".into())
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_rfc724_mid_not_exists() {
    let context = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/issue_523.txt");
    let mimeparser = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(mimeparser.get_rfc724_mid(), None);
}

#[test]
fn test_get_recipients() {
    let raw = include_bytes!("../../test-data/message/mail_with_cc.txt");
    let mail = mailparse::parse_mail(&raw[..]).unwrap();
    let recipients = get_recipients(&mail.headers);
    assert!(recipients.iter().any(|info| info.addr == "abc@bcd.com"));
    assert!(recipients.iter().any(|info| info.addr == "def@def.de"));
    assert_eq!(recipients.len(), 2);

    // If some header is present multiple times,
    // only the last one must be used.
    let raw = b"From: alice@example.org\n\
                    TO: mallory@example.com\n\
                    To: mallory@example.net\n\
                    To: bob@example.net\n\
                    Content-Type: text/plain\n\
                    Chat-Version: 1.0\n\
                    \n\
                    Hello\n\
                    ";
    let mail = mailparse::parse_mail(&raw[..]).unwrap();
    let recipients = get_recipients(&mail.headers);
    assert!(recipients.iter().any(|info| info.addr == "bob@example.net"));
    assert_eq!(recipients.len(), 1);
}

#[test]
fn test_is_attachment() {
    let raw = include_bytes!("../../test-data/message/mail_with_cc.txt");
    let mail = mailparse::parse_mail(raw).unwrap();
    assert!(!is_attachment_disposition(&mail));

    let raw = include_bytes!("../../test-data/message/mail_attach_txt.eml");
    let mail = mailparse::parse_mail(raw).unwrap();
    assert!(!is_attachment_disposition(&mail));
    assert!(!is_attachment_disposition(&mail.subparts[0]));
    assert!(is_attachment_disposition(&mail.subparts[1]));
}

fn load_mail_with_attachment<'a>(t: &'a TestContext, raw: &'a [u8]) -> ParsedMail<'a> {
    let mail = mailparse::parse_mail(raw).unwrap();
    assert!(get_attachment_filename(t, &mail).unwrap().is_none());
    assert!(
        get_attachment_filename(t, &mail.subparts[0])
            .unwrap()
            .is_none()
    );
    mail
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_attachment_filename() {
    let t = TestContext::new().await;
    let mail = load_mail_with_attachment(
        &t,
        include_bytes!("../../test-data/message/attach_filename_simple.eml"),
    );
    let filename = get_attachment_filename(&t, &mail.subparts[1]).unwrap();
    assert_eq!(filename, Some("test.html".to_string()))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_attachment_filename_encoded_words() {
    let t = TestContext::new().await;
    let mail = load_mail_with_attachment(
        &t,
        include_bytes!("../../test-data/message/attach_filename_encoded_words.eml"),
    );
    let filename = get_attachment_filename(&t, &mail.subparts[1]).unwrap();
    assert_eq!(filename, Some("Maßnahmen Okt. 2020.html".to_string()))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_attachment_filename_encoded_words_binary() {
    let t = TestContext::new().await;
    let mail = load_mail_with_attachment(
        &t,
        include_bytes!("../../test-data/message/attach_filename_encoded_words_binary.eml"),
    );
    let filename = get_attachment_filename(&t, &mail.subparts[1]).unwrap();
    assert_eq!(filename, Some(" § 165 Abs".to_string()))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_attachment_filename_encoded_words_windows1251() {
    let t = TestContext::new().await;
    let mail = load_mail_with_attachment(
        &t,
        include_bytes!("../../test-data/message/attach_filename_encoded_words_windows1251.eml"),
    );
    let filename = get_attachment_filename(&t, &mail.subparts[1]).unwrap();
    assert_eq!(filename, Some("file Что нового 2020.pdf".to_string()))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_attachment_filename_encoded_words_cont() {
    // test continued encoded-words and also test apostropes work that way
    let t = TestContext::new().await;
    let mail = load_mail_with_attachment(
        &t,
        include_bytes!("../../test-data/message/attach_filename_encoded_words_cont.eml"),
    );
    let filename = get_attachment_filename(&t, &mail.subparts[1]).unwrap();
    assert_eq!(filename, Some("Maßn'ah'men Okt. 2020.html".to_string()))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_attachment_filename_encoded_words_bad_delimiter() {
    let t = TestContext::new().await;
    let mail = load_mail_with_attachment(
        &t,
        include_bytes!("../../test-data/message/attach_filename_encoded_words_bad_delimiter.eml"),
    );
    let filename = get_attachment_filename(&t, &mail.subparts[1]).unwrap();
    // not decoded as a space is missing after encoded-words part
    assert_eq!(filename, Some("=?utf-8?q?foo?=.bar".to_string()))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_attachment_filename_apostrophed() {
    let t = TestContext::new().await;
    let mail = load_mail_with_attachment(
        &t,
        include_bytes!("../../test-data/message/attach_filename_apostrophed.eml"),
    );
    let filename = get_attachment_filename(&t, &mail.subparts[1]).unwrap();
    assert_eq!(filename, Some("Maßnahmen Okt. 2021.html".to_string()))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_attachment_filename_apostrophed_cont() {
    let t = TestContext::new().await;
    let mail = load_mail_with_attachment(
        &t,
        include_bytes!("../../test-data/message/attach_filename_apostrophed_cont.eml"),
    );
    let filename = get_attachment_filename(&t, &mail.subparts[1]).unwrap();
    assert_eq!(filename, Some("Maßnahmen März 2022.html".to_string()))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_attachment_filename_apostrophed_windows1251() {
    let t = TestContext::new().await;
    let mail = load_mail_with_attachment(
        &t,
        include_bytes!("../../test-data/message/attach_filename_apostrophed_windows1251.eml"),
    );
    let filename = get_attachment_filename(&t, &mail.subparts[1]).unwrap();
    assert_eq!(filename, Some("программирование.HTM".to_string()))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_attachment_filename_apostrophed_cp1252() {
    let t = TestContext::new().await;
    let mail = load_mail_with_attachment(
        &t,
        include_bytes!("../../test-data/message/attach_filename_apostrophed_cp1252.eml"),
    );
    let filename = get_attachment_filename(&t, &mail.subparts[1]).unwrap();
    assert_eq!(filename, Some("Auftragsbestätigung.pdf".to_string()))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_attachment_filename_apostrophed_invalid() {
    let t = TestContext::new().await;
    let mail = load_mail_with_attachment(
        &t,
        include_bytes!("../../test-data/message/attach_filename_apostrophed_invalid.eml"),
    );
    let filename = get_attachment_filename(&t, &mail.subparts[1]).unwrap();
    assert_eq!(filename, Some("somedäüta.html.zip".to_string()))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_attachment_filename_combined() {
    // test that if `filename` and `filename*0` are given, the filename is not doubled
    let t = TestContext::new().await;
    let mail = load_mail_with_attachment(
        &t,
        include_bytes!("../../test-data/message/attach_filename_combined.eml"),
    );
    let filename = get_attachment_filename(&t, &mail.subparts[1]).unwrap();
    assert_eq!(filename, Some("Maßnahmen Okt. 2020.html".to_string()))
}

#[test]
fn test_mailparse_content_type() {
    let ctype = mailparse::parse_content_type("text/plain; charset=utf-8; protected-headers=v1;");

    assert_eq!(ctype.mimetype, "text/plain");
    assert_eq!(ctype.charset, "utf-8");
    assert_eq!(
        ctype.params.get("protected-headers"),
        Some(&"v1".to_string())
    );
}

/// Test to reproduce
/// <https://github.com/staktrace/mailparse/issues/130>.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mailparse_0_16_0_panic() {
    let context = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/mailparse-0.16.0-panic.eml");

    // There should be an error, but no panic.
    assert!(
        MimeMessage::from_bytes(&context.ctx, &raw[..], None)
            .await
            .is_err()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_parse_first_addr() {
    let context = TestContext::new().await;
    let raw = b"From: hello@one.org, world@two.org\n\
                    Chat-Disposition-Notification-To: wrong\n\
                    Content-Type: text/plain\n\
                    Chat-Version: 1.0\n\
                    \n\
                    test1\n\
                    ";

    let mimeparser = MimeMessage::from_bytes(&context.ctx, &raw[..], None).await;

    assert!(mimeparser.is_err());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_parent_timestamp() {
    let context = TestContext::new_alice().await;
    let raw = b"From: foo@example.org\n\
                    Content-Type: text/plain\n\
                    Chat-Version: 1.0\n\
                    In-Reply-To: <Gr.beZgAF2Nn0-.oyaJOpeuT70@example.org>\n\
                    \n\
                    Some reply\n\
                    ";
    let mimeparser = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(
        mimeparser.get_parent_timestamp(&context.ctx).await.unwrap(),
        None
    );
    let timestamp = 1570435529;
    context
        .ctx
        .sql
        .execute(
            "INSERT INTO msgs (rfc724_mid, timestamp) VALUES(?,?)",
            ("Gr.beZgAF2Nn0-.oyaJOpeuT70@example.org", timestamp),
        )
        .await
        .expect("Failed to write to the database");
    assert_eq!(
        mimeparser.get_parent_timestamp(&context.ctx).await.unwrap(),
        Some(timestamp)
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mimeparser_with_context() {
    let context = TestContext::new_alice().await;
    let raw = b"From: hello@example.org\n\
                    Content-Type: multipart/mixed; boundary=\"==break==\";\n\
                    Subject: outer-subject\n\
                    Secure-Join-Group: no\n\
                    Secure-Join-Fingerprint: 123456\n\
                    Test-Header: Bar\n\
                    chat-VERSION: 0.0\n\
                    \n\
                    --==break==\n\
                    Content-Type: text/plain; protected-headers=\"v1\";\n\
                    Subject: inner-subject\n\
                    SecureBar-Join-Group: yes\n\
                    Test-Header: Xy\n\
                    chat-VERSION: 1.0\n\
                    \n\
                    test1\n\
                    \n\
                    --==break==--\n\
                    \n";

    let mimeparser = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();

    // non-overwritten headers do not bubble up
    let of = mimeparser.get_header(HeaderDef::SecureJoinGroup).unwrap();
    assert_eq!(of, "no");

    // unknown headers do not bubble upwards
    let of = mimeparser.get_header(HeaderDef::TestHeader).unwrap();
    assert_eq!(of, "Bar");

    // the following fields would bubble up
    // if the test would really use encryption for the protected part
    // however, as this is not the case, the outer things stay valid.
    // for Chat-Version, also the case-insensivity is tested.
    assert_eq!(mimeparser.get_subject(), Some("outer-subject".into()));

    let of = mimeparser.get_header(HeaderDef::ChatVersion).unwrap();
    assert_eq!(of, "0.0");
    assert_eq!(mimeparser.parts.len(), 1);

    // make sure, headers that are only allowed in the encrypted part
    // cannot be set from the outer part
    assert!(
        mimeparser
            .get_header(HeaderDef::SecureJoinFingerprint)
            .is_none()
    );
}

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

    let raw = include_bytes!("../../test-data/message/mail_attach_txt.eml");
    let mimeparser = MimeMessage::from_bytes(&t, &raw[..], None).await.unwrap();
    assert_eq!(mimeparser.user_avatar, None);
    assert_eq!(mimeparser.group_avatar, None);

    let raw = include_bytes!("../../test-data/message/mail_with_user_avatar.eml");
    let mimeparser = MimeMessage::from_bytes(&t, &raw[..], None).await.unwrap();
    assert_eq!(mimeparser.parts.len(), 1);
    assert_eq!(mimeparser.parts[0].typ, Viewtype::Text);
    assert!(mimeparser.user_avatar.unwrap().is_change());
    assert_eq!(mimeparser.group_avatar, None);

    let raw = include_bytes!("../../test-data/message/mail_with_user_avatar_deleted.eml");
    let mimeparser = MimeMessage::from_bytes(&t, &raw[..], None).await.unwrap();
    assert_eq!(mimeparser.parts.len(), 1);
    assert_eq!(mimeparser.parts[0].typ, Viewtype::Text);
    assert_eq!(mimeparser.user_avatar, Some(AvatarAction::Delete));
    assert_eq!(mimeparser.group_avatar, None);

    let raw = include_bytes!("../../test-data/message/mail_with_user_and_group_avatars.eml");
    let mimeparser = MimeMessage::from_bytes(&t, &raw[..], None).await.unwrap();
    assert_eq!(mimeparser.parts.len(), 1);
    assert_eq!(mimeparser.parts[0].typ, Viewtype::Text);
    assert!(mimeparser.user_avatar.unwrap().is_change());
    assert!(mimeparser.group_avatar.unwrap().is_change());

    // if the Chat-User-Avatar header is missing, the avatar become a normal attachment
    let raw = include_bytes!("../../test-data/message/mail_with_user_and_group_avatars.eml");
    let raw = String::from_utf8_lossy(raw).to_string();
    let raw = raw.replace("Chat-User-Avatar:", "Xhat-Xser-Xvatar:");
    let mimeparser = MimeMessage::from_bytes(&t, raw.as_bytes(), None)
        .await
        .unwrap();
    assert_eq!(mimeparser.parts.len(), 1);
    assert_eq!(mimeparser.parts[0].typ, Viewtype::Image);
    assert_eq!(mimeparser.user_avatar, None);
    assert!(mimeparser.group_avatar.unwrap().is_change());
}

/// Tests that video chat invitations that are not supported anymore
/// are displayed as text messages.
///
/// User can still click on the link manually.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mimeparser_with_videochat() {
    let t = TestContext::new_alice().await;

    let raw = include_bytes!("../../test-data/message/videochat_invitation.eml");
    let mimeparser = MimeMessage::from_bytes(&t, &raw[..], None).await.unwrap();
    assert_eq!(mimeparser.parts.len(), 1);
    assert_eq!(mimeparser.parts[0].typ, Viewtype::Text);
    assert_eq!(mimeparser.parts[0].param.get(Param::WebrtcRoom), None);
    assert!(
        mimeparser.parts[0]
            .msg
            .contains("https://example.org/p2p/?roomname=6HiduoAn4xN")
    );
    assert_eq!(mimeparser.user_avatar, None);
    assert_eq!(mimeparser.group_avatar, None);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mimeparser_message_kml() {
    let context = TestContext::new_alice().await;
    let raw = b"Chat-Version: 1.0\n\
From: foo <foo@example.org>\n\
To: bar <bar@example.org>\n\
Subject: Location streaming\n\
Content-Type: multipart/mixed; boundary=\"==break==\"\n\
\n\
\n\
--==break==\n\
Content-Type: text/plain; charset=utf-8\n\
\n\
--\n\
Sent with my Delta Chat Messenger: https://delta.chat\n\
\n\
--==break==\n\
Content-Type: application/vnd.google-earth.kml+xml\n\
Content-Disposition: attachment; filename=\"message.kml\"\n\
\n\
<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n\
<Document addr=\"foo@example.org\">\n\
<Placemark><Timestamp><when>XXX</when></Timestamp><Point><coordinates accuracy=\"48\">0.0,0.0</coordinates></Point></Placemark>\n\
</Document>\n\
</kml>\n\
\n\
--==break==--\n\
;";

    let mimeparser = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(
        mimeparser.get_subject(),
        Some("Location streaming".to_string())
    );
    assert!(mimeparser.location_kml.is_none());
    assert!(mimeparser.message_kml.is_some());

    // There is only one part because message.kml attachment is special
    // and only goes into message_kml.
    assert_eq!(mimeparser.parts.len(), 1);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_parse_mdn() {
    let context = TestContext::new_alice().await;
    let raw = b"Subject: =?utf-8?q?Chat=3A_Message_opened?=\n\
Date: Mon, 10 Jan 2020 00:00:00 +0000\n\
Chat-Version: 1.0\n\
Message-ID: <bar@example.org>\n\
To: Alice <alice@example.org>\n\
From: Bob <bob@example.org>\n\
Auto-Submitted: auto-replied\n\
Content-Type: multipart/report; report-type=disposition-notification;\n\t\
boundary=\"kJBbU58X1xeWNHgBtTbMk80M5qnV4N\"\n\
\n\
\n\
--kJBbU58X1xeWNHgBtTbMk80M5qnV4N\n\
Content-Type: text/plain; charset=utf-8\n\
\n\
The \"Encrypted message\" message you sent was displayed on the screen of the recipient.\n\
\n\
This is no guarantee the content was read.\n\
\n\
\n\
--kJBbU58X1xeWNHgBtTbMk80M5qnV4N\n\
Content-Type: message/disposition-notification\n\
\n\
Reporting-UA: Delta Chat 1.0.0-beta.22\n\
Original-Recipient: rfc822;bob@example.org\n\
Final-Recipient: rfc822;bob@example.org\n\
Original-Message-ID: <foo@example.org>\n\
Disposition: manual-action/MDN-sent-automatically; displayed\n\
\n\
\n\
--kJBbU58X1xeWNHgBtTbMk80M5qnV4N--\n\
";

    let message = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(
        message.get_subject(),
        Some("Chat: Message opened".to_string())
    );

    assert_eq!(message.parts.len(), 1);
    assert_eq!(message.mdn_reports.len(), 1);
    assert_eq!(message.is_bot, None);
}

/// Test parsing multiple MDNs combined in a single message.
///
/// RFC 6522 specifically allows MDNs to be nested inside
/// multipart MIME messages.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_parse_multiple_mdns() {
    let context = TestContext::new_alice().await;
    let raw = b"Subject: =?utf-8?q?Chat=3A_Message_opened?=\n\
Date: Mon, 10 Jan 2020 00:00:00 +0000\n\
Chat-Version: 1.0\n\
Message-ID: <foo@example.org>\n\
To: Alice <alice@example.org>\n\
From: Bob <bob@example.org>\n\
Content-Type: multipart/parallel; boundary=outer\n\
\n\
This is a multipart MDN.\n\
\n\
--outer\n\
Content-Type: multipart/report; report-type=disposition-notification;\n\t\
boundary=kJBbU58X1xeWNHgBtTbMk80M5qnV4N\n\
\n\
\n\
--kJBbU58X1xeWNHgBtTbMk80M5qnV4N\n\
Content-Type: text/plain; charset=utf-8\n\
\n\
The \"Encrypted message\" message you sent was displayed on the screen of the recipient.\n\
\n\
This is no guarantee the content was read.\n\
\n\
\n\
--kJBbU58X1xeWNHgBtTbMk80M5qnV4N\n\
Content-Type: message/disposition-notification\n\
\n\
Reporting-UA: Delta Chat 1.0.0-beta.22\n\
Original-Recipient: rfc822;bob@example.org\n\
Final-Recipient: rfc822;bob@example.org\n\
Original-Message-ID: <bar@example.org>\n\
Disposition: manual-action/MDN-sent-automatically; displayed\n\
\n\
\n\
--kJBbU58X1xeWNHgBtTbMk80M5qnV4N--\n\
--outer\n\
Content-Type: multipart/report; report-type=disposition-notification;\n\t\
boundary=zuOJlsTfZAukyawEPVdIgqWjaM9w2W\n\
\n\
\n\
--zuOJlsTfZAukyawEPVdIgqWjaM9w2W\n\
Content-Type: text/plain; charset=utf-8\n\
\n\
The \"Encrypted message\" message you sent was displayed on the screen of the recipient.\n\
\n\
This is no guarantee the content was read.\n\
\n\
\n\
--zuOJlsTfZAukyawEPVdIgqWjaM9w2W\n\
Content-Type: message/disposition-notification\n\
\n\
Reporting-UA: Delta Chat 1.0.0-beta.22\n\
Original-Recipient: rfc822;bob@example.org\n\
Final-Recipient: rfc822;bob@example.org\n\
Original-Message-ID: <baz@example.org>\n\
Disposition: manual-action/MDN-sent-automatically; displayed\n\
\n\
\n\
--zuOJlsTfZAukyawEPVdIgqWjaM9w2W--\n\
--outer--\n\
";

    let message = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(
        message.get_subject(),
        Some("Chat: Message opened".to_string())
    );

    assert_eq!(message.parts.len(), 2);
    assert_eq!(message.mdn_reports.len(), 2);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_parse_mdn_with_additional_message_ids() {
    let context = TestContext::new_alice().await;
    let raw = b"Subject: =?utf-8?q?Chat=3A_Message_opened?=\n\
Date: Mon, 10 Jan 2020 00:00:00 +0000\n\
Chat-Version: 1.0\n\
Message-ID: <bar@example.org>\n\
To: Alice <alice@example.org>\n\
From: Bob <bob@example.org>\n\
Content-Type: multipart/report; report-type=disposition-notification;\n\t\
boundary=\"kJBbU58X1xeWNHgBtTbMk80M5qnV4N\"\n\
\n\
\n\
--kJBbU58X1xeWNHgBtTbMk80M5qnV4N\n\
Content-Type: text/plain; charset=utf-8\n\
\n\
The \"Encrypted message\" message you sent was displayed on the screen of the recipient.\n\
\n\
This is no guarantee the content was read.\n\
\n\
\n\
--kJBbU58X1xeWNHgBtTbMk80M5qnV4N\n\
Content-Type: message/disposition-notification\n\
\n\
Reporting-UA: Delta Chat 1.0.0-beta.22\n\
Original-Recipient: rfc822;bob@example.org\n\
Final-Recipient: rfc822;bob@example.org\n\
Original-Message-ID: <foo@example.org>\n\
Disposition: manual-action/MDN-sent-automatically; displayed\n\
Additional-Message-IDs: <foo@example.com> <foo@example.net>\n\
\n\
\n\
--kJBbU58X1xeWNHgBtTbMk80M5qnV4N--\n\
";

    let message = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(
        message.get_subject(),
        Some("Chat: Message opened".to_string())
    );

    assert_eq!(message.parts.len(), 1);
    assert_eq!(message.mdn_reports.len(), 1);
    assert_eq!(
        message.mdn_reports[0].original_message_id,
        Some("foo@example.org".to_string())
    );
    assert_eq!(
        &message.mdn_reports[0].additional_message_ids,
        &["foo@example.com", "foo@example.net"]
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_parse_inline_attachment() {
    let context = TestContext::new_alice().await;
    let raw = br#"Date: Thu, 13 Feb 2020 22:41:20 +0000 (UTC)
From: sender@example.com
To: receiver@example.com
Subject: Mail with inline attachment
MIME-Version: 1.0
Content-Type: multipart/mixed;
	boundary="----=_Part_25_46172632.1581201680436"

------=_Part_25_46172632.1581201680436
Content-Type: text/plain; charset=utf-8

Hello!

------=_Part_25_46172632.1581201680436
Content-Type: application/pdf; name="some_pdf.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: inline; filename="some_pdf.pdf"

JVBERi0xLjUKJcOkw7zDtsOfCjIgMCBvYmoKPDwvTGVuZ3RoIDMgMCBSL0ZpbHRlci9GbGF0ZURl
Y29kZT4+CnN0cmVhbQp4nGVOuwoCMRDs8xVbC8aZvC4Hx4Hno7ATAhZi56MTtPH33YtXiLKQ3ZnM
MDYyMDYxNTE1RTlDOEE4Cj4+CnN0YXJ0eHJlZgo4Mjc4CiUlRU9GCg==
------=_Part_25_46172632.1581201680436--
"#;

    let message = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(
        message.get_subject(),
        Some("Mail with inline attachment".to_string())
    );

    assert_eq!(message.parts.len(), 1);
    assert_eq!(message.parts[0].typ, Viewtype::File);
    assert_eq!(message.parts[0].msg, "Mail with inline attachment – Hello!");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hide_html_without_content() {
    let t = TestContext::new_alice().await;
    let raw = br#"Date: Thu, 13 Feb 2020 22:41:20 +0000 (UTC)
From: sender@example.com
To: receiver@example.com
Subject: Mail with inline attachment
MIME-Version: 1.0
Content-Type: multipart/mixed;
	boundary="----=_Part_25_46172632.1581201680436"

------=_Part_25_46172632.1581201680436
Content-Type: text/html; charset=utf-8

<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252">
<meta name="GENERATOR" content="MSHTML 11.00.10570.1001"></head>
<body><img align="baseline" alt="" src="cid:1712254131-1" border="0" hspace="0">
</body>

------=_Part_25_46172632.1581201680436
Content-Type: application/pdf; name="some_pdf.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: inline; filename="some_pdf.pdf"

JVBERi0xLjUKJcOkw7zDtsOfCjIgMCBvYmoKPDwvTGVuZ3RoIDMgMCBSL0ZpbHRlci9GbGF0ZURl
Y29kZT4+CnN0cmVhbQp4nGVOuwoCMRDs8xVbC8aZvC4Hx4Hno7ATAhZi56MTtPH33YtXiLKQ3ZnM
MDYyMDYxNTE1RTlDOEE4Cj4+CnN0YXJ0eHJlZgo4Mjc4CiUlRU9GCg==
------=_Part_25_46172632.1581201680436--
"#;

    let message = MimeMessage::from_bytes(&t, &raw[..], None).await.unwrap();

    assert_eq!(message.parts.len(), 1);
    assert_eq!(message.parts[0].typ, Viewtype::File);
    assert_eq!(message.parts[0].msg, "");

    // Make sure the file is there even though the html is wrong:
    let param = &message.parts[0].param;
    let blob: BlobObject = param.get_file_blob(&t).unwrap().unwrap();
    let f = tokio::fs::File::open(blob.to_abs_path()).await.unwrap();
    let size = f.metadata().await.unwrap().len();
    assert_eq!(size, 154);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn parse_inline_image() {
    let context = TestContext::new_alice().await;
    let raw = br#"Message-ID: <foobar@example.org>
From: foo <foo@example.org>
Subject: example
To: bar@example.org
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="--11019878869865180"

----11019878869865180
Content-Type: text/plain; charset=utf-8

Test

----11019878869865180
Content-Type: image/jpeg;
 name="JPEG_filename.jpg"
Content-Transfer-Encoding: base64
Content-Disposition: inline;
 filename="JPEG_filename.jpg"

iVBORw0KGgoAAAANSUhEUgAAACAAAAAeCAAAAABoYUP1AAAAAXNSR0IArs4c6QAAAo1JREFUKJFdkdFuG0UUhr/szuxkxtlduzVx00jGUAhcI56CF0DiHXgFHqDiMfoCvAJC4gIJEBdVaZoGOY5dJ45r7zozmRlvzIVDm3Iu//PpP7/+s/OC/0+UREkEGZGr5N6mAX78MwISQEYJ6j6QYqZf7fzsYyRGJDISuQ9g6uMjW00WRCSRCP4DwNSEg496v828fC++B4yBGro7h+PliiiJHtR9B1vrmbtg359cOk+UqA8cDJm+eHu8yDfii6sAxK0u3hlsnPFn1WvT4XxYUqqtKu8cTMNKT8+nz3/aaWft3svKecBD/O9ETu2O//G7fXt5mHX2xwGP32aIEUNNvX/uh3z2pAkcKD+9XOLVNoMESw7YC+aPP8nqqSluyiuVaZRXCKLEQK3PxsP27UHe1lXV9eczCu2V8ippJA2gz+YTNTK9ttZOoYr+aeXwHp+k245cnFRNt1tmMJg3XV0dXQd3F5LcGn5fDnVQgwINRyFvtddnNmwBSW1qXfzNSDwoM+2A+aTbShfDd89Ka9ybiiLvGa33gK8THrWfVNUSSGLTALMRo/xBXnLbACu3QtRXY+sgkWnawKxCcLjPtr29gVZdPTidBUcSaXJeTfUL+mW4631Fmse+772xIGjSza/KTW/MYE/UCXPbEWs//Xxvqf8qZgYhG0jt8cnTnJpEgfDQ6rvE0n9tq66ICafil5OnOYt0hY94FUPoxI136uPpw4VIYNd+M5utrqvGpg0hc50bRl6BvLanX4pb/3347uWi/WgNHtYyyrdwszsX5fjZtwghy7C5sK2WgUoErcjIoEWr4fAHHhoRP+XZ86L/uMAarLFgsMBaAJhM8Ief9Ey7yHSmyXTp0GRoF7KQEdD/ArmtONKkgCleAAAAAElFTkSuQmCC


----11019878869865180--
"#;

    let message = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(message.get_subject(), Some("example".to_string()));

    assert_eq!(message.parts.len(), 1);
    assert_eq!(message.parts[0].typ, Viewtype::Image);
    assert_eq!(message.parts[0].msg, "example – Test");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn parse_thunderbird_html_embedded_image() {
    let context = TestContext::new_alice().await;
    let raw = br#"To: Alice <alice@example.org>
From: Bob <bob@example.org>
Subject: Test subject
Message-ID: <foobarbaz@example.org>
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101
 Thunderbird/68.7.0
MIME-Version: 1.0
Content-Type: multipart/alternative;
 boundary="------------779C1631600DF3DB8C02E53A"
Content-Language: en-US

This is a multi-part message in MIME format.
--------------779C1631600DF3DB8C02E53A
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit

Test


--------------779C1631600DF3DB8C02E53A
Content-Type: multipart/related;
 boundary="------------10CC6C2609EB38DA782C5CA9"


--------------10CC6C2609EB38DA782C5CA9
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: 7bit

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
Test<br>
<p><img moz-do-not-send="false" src="cid:part1.9DFA679B.52A88D69@example.org" alt=""></p>
</body>
</html>

--------------10CC6C2609EB38DA782C5CA9
Content-Type: image/png;
 name="1.png"
Content-Transfer-Encoding: base64
Content-ID: <part1.9DFA679B.52A88D69@example.org>
Content-Disposition: inline;
 filename="1.png"

iVBORw0KGgoAAAANSUhEUgAAACAAAAAeCAAAAABoYUP1AAAAAXNSR0IArs4c6QAAAo1JREFUKJFdkdFuG0UUhr/szuxkxtlduzVx00jGUAhcI56CF0DiHXgFHqDiMfoCvAJC4gIJEBdVaZoGOY5dJ45r7zozmRlvzIVDm3Iu//PpP7/+s/OC/0+UREkEGZGr5N6mAX78MwISQEYJ6j6QYqZf7fzsYyRGJDISuQ9g6uMjW00WRCSRCP4DwNSEg496v828fC++B4yBGro7h+PliiiJHtR9B1vrmbtg359cOk+UqA8cDJm+eHu8yDfii6sAxK0u3hlsnPFn1WvT4XxYUqqtKu8cTMNKT8+nz3/aaWft3svKecBD/O9ETu2O//G7fXt5mHX2xwGP32aIEUNNvX/uh3z2pAkcKD+9XOLVNoMESw7YC+aPP8nqqSluyiuVaZRXCKLEQK3PxsP27UHe1lXV9eczCu2V8ippJA2gz+YTNTK9ttZOoYr+aeXwHp+k245cnFRNt1tmMJg3XV0dXQd3F5LcGn5fDnVQgwINRyFvtddnNmwBSW1qXfzNSDwoM+2A+aTbShfDd89Ka9ybiiLvGa33gK8THrWfVNUSSGLTALMRo/xBXnLbACu3QtRXY+sgkWnawKxCcLjPtr29gVZdPTidBUcSaXJeTfUL+mW4631Fmse+772xIGjSza/KTW/MYE/UCXPbEWs//Xxvqf8qZgYhG0jt8cnTnJpEgfDQ6rvE0n9tq66ICafil5OnOYt0hY94FUPoxI136uPpw4VIYNd+M5utrqvGpg0hc50bRl6BvLanX4pb/3347uWi/WgNHtYyyrdwszsX5fjZtwghy7C5sK2WgUoErcjIoEWr4fAHHhoRP+XZ86L/uMAarLFgsMBaAJhM8Ief9Ey7yHSmyXTp0GRoF7KQEdD/ArmtONKkgCleAAAAAElFTkSuQmCC
--------------10CC6C2609EB38DA782C5CA9--

--------------779C1631600DF3DB8C02E53A--"#;

    let message = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(message.get_subject(), Some("Test subject".to_string()));

    assert_eq!(message.parts.len(), 1);
    assert_eq!(message.parts[0].typ, Viewtype::Image);
    assert_eq!(message.parts[0].msg, "Test subject – Test");
}

// Outlook specifies filename in the "name" attribute of Content-Type
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn parse_outlook_html_embedded_image() {
    let context = TestContext::new_alice().await;
    let raw = br#"From: Anonymous <anonymous@example.org>
To: Anonymous <anonymous@example.org>
Subject: Delta Chat is great stuff!
Date: Tue, 5 May 2020 01:23:45 +0000
MIME-Version: 1.0
Content-Type: multipart/related;
	boundary="----=_NextPart_000_0003_01D622B3.CA753E60"
X-Mailer: Microsoft Outlook 15.0

This is a multipart message in MIME format.

------=_NextPart_000_0003_01D622B3.CA753E60
Content-Type: multipart/alternative;
	boundary="----=_NextPart_001_0004_01D622B3.CA753E60"


------=_NextPart_001_0004_01D622B3.CA753E60
Content-Type: text/plain;
	charset="us-ascii"
Content-Transfer-Encoding: 7bit




------=_NextPart_001_0004_01D622B3.CA753E60
Content-Type: text/html;
	charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

<html>
<body>
<p>
Test<img src="cid:image001.jpg@01D622B3.C9D8D750">
</p>
</body>
</html>
------=_NextPart_001_0004_01D622B3.CA753E60--

------=_NextPart_000_0003_01D622B3.CA753E60
Content-Type: image/jpeg;
	name="image001.jpg"
Content-Transfer-Encoding: base64
Content-ID: <image001.jpg@01D622B3.C9D8D750>

iVBORw0KGgoAAAANSUhEUgAAACAAAAAeCAAAAABoYUP1AAAAAXNSR0IArs4c6QAAAo1JREFUKJFdkdFuG0UUhr/szuxkxtlduzVx00jGUAhcI56CF0DiHXgFHqDiMfoCvAJC4gIJEBdVaZoGOY5dJ45r7zozmRlvzIVDm3Iu//PpP7/+s/OC/0+UREkEGZGr5N6mAX78MwISQEYJ6j6QYqZf7fzsYyRGJDISuQ9g6uMjW00WRCSRCP4DwNSEg496v828fC++B4yBGro7h+PliiiJHtR9B1vrmbtg359cOk+UqA8cDJm+eHu8yDfii6sAxK0u3hlsnPFn1WvT4XxYUqqtKu8cTMNKT8+nz3/aaWft3svKecBD/O9ETu2O//G7fXt5mHX2xwGP32aIEUNNvX/uh3z2pAkcKD+9XOLVNoMESw7YC+aPP8nqqSluyiuVaZRXCKLEQK3PxsP27UHe1lXV9eczCu2V8ippJA2gz+YTNTK9ttZOoYr+aeXwHp+k245cnFRNt1tmMJg3XV0dXQd3F5LcGn5fDnVQgwINRyFvtddnNmwBSW1qXfzNSDwoM+2A+aTbShfDd89Ka9ybiiLvGa33gK8THrWfVNUSSGLTALMRo/xBXnLbACu3QtRXY+sgkWnawKxCcLjPtr29gVZdPTidBUcSaXJeTfUL+mW4631Fmse+772xIGjSza/KTW/MYE/UCXPbEWs//Xxvqf8qZgYhG0jt8cnTnJpEgfDQ6rvE0n9tq66ICafil5OnOYt0hY94FUPoxI136uPpw4VIYNd+M5utrqvGpg0hc50bRl6BvLanX4pb/3347uWi/WgNHtYyyrdwszsX5fjZtwghy7C5sK2WgUoErcjIoEWr4fAHHhoRP+XZ86L/uMAarLFgsMBaAJhM8Ief9Ey7yHSmyXTp0GRoF7KQEdD/ArmtONKkgCleAAAAAElFTkSuQmCC

------=_NextPart_000_0003_01D622B3.CA753E60--
"#;

    let message = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(
        message.get_subject(),
        Some("Delta Chat is great stuff!".to_string())
    );

    assert_eq!(message.parts.len(), 1);
    assert_eq!(message.parts[0].typ, Viewtype::Image);
    assert_eq!(message.parts[0].msg, "Delta Chat is great stuff! – Test");
}

#[test]
fn test_parse_message_id() {
    let test = parse_message_id("<foobar>");
    assert!(test.is_ok());
    assert_eq!(test.unwrap(), "foobar");

    let test = parse_message_id("<foo> <bar>");
    assert!(test.is_ok());
    assert_eq!(test.unwrap(), "foo");

    let test = parse_message_id("  < foo > <bar>");
    assert!(test.is_ok());
    assert_eq!(test.unwrap(), "foo");

    let test = parse_message_id("foo");
    assert!(test.is_ok());
    assert_eq!(test.unwrap(), "foo");

    let test = parse_message_id(" foo ");
    assert!(test.is_ok());
    assert_eq!(test.unwrap(), "foo");

    let test = parse_message_id("foo bar");
    assert!(test.is_ok());
    assert_eq!(test.unwrap(), "foo");

    let test = parse_message_id("  foo  bar ");
    assert!(test.is_ok());
    assert_eq!(test.unwrap(), "foo");

    let test = parse_message_id("");
    assert!(test.is_err());

    let test = parse_message_id(" ");
    assert!(test.is_err());

    let test = parse_message_id("<>");
    assert!(test.is_err());

    let test = parse_message_id("<> bar");
    assert!(test.is_ok());
    assert_eq!(test.unwrap(), "bar");
}

#[test]
fn test_parse_message_ids() {
    let test = parse_message_ids("  foo  bar <foobar>");
    assert_eq!(test.len(), 3);
    assert_eq!(test[0], "foo");
    assert_eq!(test[1], "bar");
    assert_eq!(test[2], "foobar");

    let test = parse_message_ids("  < foobar >");
    assert_eq!(test.len(), 1);
    assert_eq!(test[0], "foobar");

    let test = parse_message_ids("");
    assert!(test.is_empty());

    let test = parse_message_ids(" ");
    assert!(test.is_empty());

    let test = parse_message_ids("  < ");
    assert!(test.is_empty());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn parse_format_flowed_quote() {
    let context = TestContext::new_alice().await;
    let raw = br##"Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no
Subject: Re: swipe-to-reply
MIME-Version: 1.0
In-Reply-To: <bar@example.org>
Date: Tue, 06 Oct 2020 00:00:00 +0000
Chat-Version: 1.0
Message-ID: <foo@example.org>
To: bob <bob@example.org>
From: alice <alice@example.org>

> Long 
> quote.

Reply
"##;

    let message = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(
        message.get_subject(),
        Some("Re: swipe-to-reply".to_string())
    );

    assert_eq!(message.parts.len(), 1);
    assert_eq!(message.parts[0].typ, Viewtype::Text);
    assert_eq!(
        message.parts[0].param.get(Param::Quote).unwrap(),
        "Long quote."
    );
    assert_eq!(message.parts[0].msg, "Reply");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn parse_quote_without_reply() {
    let context = TestContext::new_alice().await;
    let raw = br##"Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no
Subject: Re: swipe-to-reply
MIME-Version: 1.0
In-Reply-To: <bar@example.org>
Date: Tue, 06 Oct 2020 00:00:00 +0000
Message-ID: <foo@example.org>
To: bob <bob@example.org>
From: alice <alice@example.org>

> Just a quote.
"##;

    let message = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(
        message.get_subject(),
        Some("Re: swipe-to-reply".to_string())
    );

    assert_eq!(message.parts.len(), 1);
    assert_eq!(message.parts[0].typ, Viewtype::Text);
    assert_eq!(
        message.parts[0].param.get(Param::Quote).unwrap(),
        "Just a quote."
    );
    assert_eq!(message.parts[0].msg, "");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn parse_quote_top_posting() {
    let context = TestContext::new_alice().await;
    let raw = br##"Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no
Subject: Re: top posting
MIME-Version: 1.0
In-Reply-To: <bar@example.org>
Message-ID: <foo@example.org>
To: bob <bob@example.org>
From: alice <alice@example.org>

A reply.

On 2020-10-25, Bob wrote:
> A quote.
"##;

    let message = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(message.get_subject(), Some("Re: top posting".to_string()));

    assert_eq!(message.parts.len(), 1);
    assert_eq!(message.parts[0].typ, Viewtype::Text);
    assert_eq!(
        message.parts[0].param.get(Param::Quote).unwrap(),
        "A quote."
    );
    assert_eq!(message.parts[0].msg, "A reply.");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_attachment_quote() {
    let context = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/quote_attach.eml");
    let mimeparser = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();

    assert_eq!(mimeparser.get_subject().unwrap(), "Message from Alice");
    assert_eq!(mimeparser.parts.len(), 1);
    assert_eq!(mimeparser.parts[0].msg, "Reply");
    assert_eq!(
        mimeparser.parts[0].param.get(Param::Quote).unwrap(),
        "Quote"
    );
    assert_eq!(mimeparser.parts[0].typ, Viewtype::File);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_quote_div() {
    let t = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/gmx-quote.eml");
    let mimeparser = MimeMessage::from_bytes(&t, raw, None).await.unwrap();
    assert_eq!(mimeparser.parts[0].msg, "YIPPEEEEEE\n\nMulti-line");
    assert_eq!(mimeparser.parts[0].param.get(Param::Quote).unwrap(), "Now?");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_allinkl_blockquote() {
    // all-inkl.com puts quotes into `<blockquote> </blockquote>`.
    let t = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/allinkl-quote.eml");
    let mimeparser = MimeMessage::from_bytes(&t, raw, None).await.unwrap();
    assert!(mimeparser.parts[0].msg.starts_with("It's 1.0."));
    assert_eq!(
        mimeparser.parts[0].param.get(Param::Quote).unwrap(),
        "What's the version?"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_add_subj_to_multimedia_msg() {
    let t = TestContext::new_alice().await;
    receive_imf(
        &t.ctx,
        include_bytes!("../../test-data/message/subj_with_multimedia_msg.eml"),
        false,
    )
    .await
    .unwrap();

    let chats = Chatlist::try_load(&t.ctx, 0, None, None).await.unwrap();
    let msg_id = chats.get_msg_id(0).unwrap().unwrap();
    let msg = Message::load_from_db(&t.ctx, msg_id).await.unwrap();

    assert_eq!(msg.text, "subj with important info – body text");
    assert_eq!(msg.viewtype, Viewtype::Image);
    assert_eq!(msg.error(), None);
    assert_eq!(msg.is_dc_message, MessengerMessage::No);
    assert_eq!(msg.chat_blocked, Blocked::Request);
    assert_eq!(msg.state, MessageState::InFresh);
    assert_eq!(msg.get_filebytes(&t).await.unwrap().unwrap(), 2115);
    assert!(msg.get_file(&t).is_some());
    assert_eq!(msg.get_filename().unwrap(), "avatar64x64.png");
    assert_eq!(msg.get_width(), 64);
    assert_eq!(msg.get_height(), 64);
    assert_eq!(msg.get_filemime().unwrap(), "image/png");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mime_modified_plain() {
    let t = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/text_plain_unspecified.eml");
    let mimeparser = MimeMessage::from_bytes(&t.ctx, raw, None).await.unwrap();
    assert!(!mimeparser.is_mime_modified);
    assert_eq!(
        mimeparser.parts[0].msg,
        "This message does not have Content-Type nor Subject."
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mime_modified_alt_plain_html() {
    let t = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/text_alt_plain_html.eml");
    let mimeparser = MimeMessage::from_bytes(&t.ctx, raw, None).await.unwrap();
    assert!(mimeparser.is_mime_modified);
    assert_eq!(
        mimeparser.parts[0].msg,
        "mime-modified test – this is plain"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mime_modified_alt_plain() {
    let t = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/text_alt_plain.eml");
    let mimeparser = MimeMessage::from_bytes(&t.ctx, raw, None).await.unwrap();
    assert!(!mimeparser.is_mime_modified);
    assert_eq!(
        mimeparser.parts[0].msg,
        "mime-modified test – \
        mime-modified should not be set set as there is no html and no special stuff;\n\
        although not being a delta-message.\n\
        test some special html-characters as < > and & but also \" and ' :)"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mime_modified_alt_html() {
    let t = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/text_alt_html.eml");
    let mimeparser = MimeMessage::from_bytes(&t.ctx, raw, None).await.unwrap();
    assert!(mimeparser.is_mime_modified);
    assert_eq!(
        mimeparser.parts[0].msg,
        "mime-modified test – mime-modified *set*; simplify is always regarded as lossy."
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mime_modified_html() {
    let t = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/text_html.eml");
    let mimeparser = MimeMessage::from_bytes(&t.ctx, raw, None).await.unwrap();
    assert!(mimeparser.is_mime_modified);
    assert_eq!(
        mimeparser.parts[0].msg,
        "mime-modified test – mime-modified *set*; simplify is always regarded as lossy."
    );
}

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

    static REPEAT_TXT: &str = "this text with 42 chars is just repeated.\n";
    static REPEAT_CNT: usize = DC_DESIRED_TEXT_LEN / REPEAT_TXT.len() + 2;
    let long_txt = format!("From: alice@c.de\n\n{}", REPEAT_TXT.repeat(REPEAT_CNT));
    assert_eq!(long_txt.matches("just repeated").count(), REPEAT_CNT);
    assert!(long_txt.len() > DC_DESIRED_TEXT_LEN);

    {
        let mimemsg = MimeMessage::from_bytes(&t, long_txt.as_ref(), None).await?;
        assert!(mimemsg.is_mime_modified);
        assert!(
            mimemsg.parts[0].msg.matches("just repeated").count()
                <= DC_DESIRED_TEXT_LEN / REPEAT_TXT.len()
        );
        assert!(mimemsg.parts[0].msg.len() <= DC_DESIRED_TEXT_LEN + DC_ELLIPSIS.len());
    }

    for draft in [false, true] {
        let chat = t.get_self_chat().await;
        let mut msg = Message::new_text(long_txt.clone());
        if draft {
            chat.id.set_draft(&t, Some(&mut msg)).await?;
        }
        let sent_msg = t.send_msg(chat.id, &mut msg).await;
        let msg = t.get_last_msg_in(chat.id).await;
        assert!(msg.has_html());
        let html = msg.id.get_html(&t).await?.unwrap();
        assert_eq!(html.matches("<!DOCTYPE html>").count(), 1);
        assert_eq!(html.matches("just repeated.<br/>").count(), REPEAT_CNT);
        assert!(
            msg.text.matches("just repeated.").count() <= DC_DESIRED_TEXT_LEN / REPEAT_TXT.len()
        );
        assert!(msg.text.len() <= DC_DESIRED_TEXT_LEN + DC_ELLIPSIS.len());

        let msg = t1.recv_msg(&sent_msg).await;
        assert!(msg.has_html());
        assert_eq!(msg.id.get_html(&t1).await?.unwrap(), html);
    }

    t.set_config(Config::Bot, Some("1")).await?;
    {
        let mimemsg = MimeMessage::from_bytes(&t, long_txt.as_ref(), None).await?;
        assert!(!mimemsg.is_mime_modified);
        assert_eq!(
            format!("{}\n", mimemsg.parts[0].msg),
            REPEAT_TXT.repeat(REPEAT_CNT)
        );
    }

    Ok(())
}

/// Tests that sender status (signature) does not appear
/// in HTML view of a long message.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_large_message_no_signature() -> Result<()> {
    let mut tcm = TestContextManager::new();
    let alice = &tcm.alice().await;
    let bob = &tcm.bob().await;

    alice
        .set_config(Config::Selfstatus, Some("Some signature"))
        .await?;
    let chat = alice.create_chat(bob).await;
    let txt = "Hello!\n".repeat(500);
    let sent = alice.send_text(chat.id, &txt).await;
    let msg = bob.recv_msg(&sent).await;

    assert_eq!(msg.has_html(), true);
    let html = msg.id.get_html(bob).await?.unwrap();
    assert_eq!(html.contains("Some signature"), false);
    Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_x_microsoft_original_message_id() {
    let t = TestContext::new_alice().await;
    let message = MimeMessage::from_bytes(&t, b"Date: Wed, 17 Feb 2021 15:45:15 +0000\n\
                Chat-Version: 1.0\n\
                Message-ID: <DBAPR03MB1180CE51A1BFE265BD018D4790869@DBAPR03MB6691.eurprd03.prod.outlook.com>\n\
                To: Bob <bob@example.org>\n\
                From: Alice <alice@example.org>\n\
                Subject: Message from Alice\n\
                Content-Type: text/plain\n\
                X-Microsoft-Original-Message-ID: <Mr.6Dx7ITn4w38.n9j7epIcuQI@outlook.com>\n\
                MIME-Version: 1.0\n\
                \n\
                Does it work with outlook now?\n\
                ", None)
            .await
            .unwrap();
    assert_eq!(
        message.get_rfc724_mid(),
        Some("Mr.6Dx7ITn4w38.n9j7epIcuQI@outlook.com".to_string())
    );
}

/// Tests that X-Microsoft-Original-Message-ID does not overwrite encrypted Message-ID.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_x_microsoft_original_message_id_precedence() -> Result<()> {
    let mut tcm = TestContextManager::new();
    let alice = tcm.alice().await;
    let bob = tcm.bob().await;

    let bob_chat_id = tcm.send_recv_accept(&alice, &bob, "hi").await.chat_id;
    chat::send_text_msg(&bob, bob_chat_id, "hi!".to_string()).await?;
    let mut sent_msg = bob.pop_sent_msg().await;

    // Insert X-Microsoft-Original-Message-ID.
    // It should be ignored because there is a Message-ID in the encrypted part.
    sent_msg.payload = sent_msg.payload.replace(
        "Message-ID:",
        "X-Microsoft-Original-Message-ID: <fake-message-id@example.net>\r\nMessage-ID:",
    );

    let msg = alice.recv_msg(&sent_msg).await;
    assert!(!msg.rfc724_mid.contains("fake-message-id"));
    Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_extra_imf_headers() -> Result<()> {
    let mut tcm = TestContextManager::new();
    let t = &tcm.alice().await;
    let chat_id = t.get_self_chat().await.id;

    for std_hp_composing in [false, true] {
        t.set_config_bool(Config::StdHeaderProtectionComposing, std_hp_composing)
            .await?;
        chat::send_text_msg(t, chat_id, "hi!".to_string()).await?;
        let sent_msg = t.pop_sent_msg().await;
        // Check removal of some nonexistent "Chat-*" header to protect the code from future
        // breakages. But headers not prefixed with "Chat-" remain unless a message has standard
        // Header Protection.
        let payload = sent_msg.payload.replace(
            "Message-ID:",
            "Chat-Forty-Two: 42\r\nForty-Two: 42\r\nMessage-ID:",
        );
        let msg = MimeMessage::from_bytes(t, payload.as_bytes(), None).await?;
        assert!(msg.headers.contains_key("chat-version"));
        assert!(!msg.headers.contains_key("chat-forty-two"));
        assert_ne!(msg.headers.contains_key("forty-two"), std_hp_composing);
    }
    Ok(())
}

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

    // A message with a long Message-ID.
    // Long message-IDs are generated by Mailjet.
    let raw = br"Date: Thu, 28 Jan 2021 00:26:57 +0000
Chat-Version: 1.0\n\
Message-ID: <ABCDEFGH.1234567_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA@mailjet.com>
To: Bob <bob@example.org>
From: Alice <alice@example.org>
Subject: ...

Some quote.
";
    receive_imf(&t, raw, false).await?;

    // Delta Chat generates In-Reply-To with a starting tab when Message-ID is too long.
    let raw = br"In-Reply-To:
	<ABCDEFGH.1234567_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA@mailjet.com>
Date: Thu, 28 Jan 2021 00:26:57 +0000
Chat-Version: 1.0\n\
Message-ID: <foobar@example.org>
To: Alice <alice@example.org>
From: Bob <bob@example.org>
Subject: ...

> Some quote.

Some reply
";

    receive_imf(&t, raw, false).await?;

    let msg = t.get_last_msg().await;
    assert_eq!(msg.get_text(), "Some reply");
    let quoted_message = msg.quoted_message(&t).await?.unwrap();
    assert_eq!(quoted_message.get_text(), "Some quote.");

    Ok(())
}

// Test that WantsMdn parameter is not set on outgoing messages.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_outgoing_wants_mdn() -> Result<()> {
    let alice = TestContext::new_alice().await;
    let bob = TestContext::new_bob().await;

    let raw = br"Date: Thu, 28 Jan 2021 00:26:57 +0000
Chat-Version: 1.0\n\
Message-ID: <foobarbaz@example.org>
To: Bob <bob@example.org>
From: Alice <alice@example.org>
Subject: subject
Chat-Disposition-Notification-To: alice@example.org

Message.
";

    // Bob receives message.
    receive_imf(&bob, raw, false).await?;
    let msg = bob.get_last_msg().await;
    // Message is incoming.
    assert!(msg.param.get_bool(Param::WantsMdn).unwrap());

    // Alice receives copy-to-self.
    receive_imf(&alice, raw, false).await?;
    let msg = alice.get_last_msg().await;
    // Message is outgoing, don't send read receipt to self.
    assert!(msg.param.get_bool(Param::WantsMdn).is_none());

    Ok(())
}

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

    // Alice receives BCC-self copy of a message sent to Bob.
    receive_imf(
        &alice,
        "Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\
                 From: alice@example.org\n\
                 To: bob@example.net\n\
                 Subject: foo\n\
                 Message-ID: first@example.com\n\
                 Chat-Version: 1.0\n\
                 Chat-Disposition-Notification-To: alice@example.org\n\
                 Date: Sun, 22 Mar 2020 22:37:57 +0000\n\
                 \n\
                 hello\n"
            .as_bytes(),
        false,
    )
    .await?;
    let msg = alice.get_last_msg().await;
    assert_eq!(msg.state, MessageState::OutDelivered);

    // Due to a bug in the old version running on the other device, Alice receives a read
    // receipt from self.
    receive_imf(
            &alice,
                "Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\
                 From: alice@example.org\n\
                 To: alice@example.org\n\
                 Subject: message opened\n\
                 Date: Sun, 22 Mar 2020 23:37:57 +0000\n\
                 Chat-Version: 1.0\n\
                 Message-ID: second@example.com\n\
                 Content-Type: multipart/report; report-type=disposition-notification; boundary=\"SNIPP\"\n\
                 \n\
                 \n\
                 --SNIPP\n\
                 Content-Type: text/plain; charset=utf-8\n\
                 \n\
                 Read receipts do not guarantee sth. was read.\n\
                 \n\
                 \n\
                 --SNIPP\n\
                 Content-Type: message/disposition-notification\n\
                 \n\
                 Original-Recipient: rfc822;bob@example.com\n\
                 Final-Recipient: rfc822;bob@example.com\n\
                 Original-Message-ID: <first@example.com>\n\
                 Disposition: manual-action/MDN-sent-automatically; displayed\n\
                 \n\
                 \n\
                 --SNIPP--"
            .as_bytes(),
            false,
        )
        .await?;

    // Check that the state has not changed to `MessageState::OutMdnRcvd`.
    let msg = Message::load_from_db(&alice, msg.id).await?;
    assert_eq!(msg.state, MessageState::OutDelivered);

    Ok(())
}

/// Test parsing of MDN sent by MS Exchange.
///
/// It does not have required Original-Message-ID field, so it is useless, but we want to
/// recognize it as MDN nevertheless to avoid displaying it in the chat as normal message.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_ms_exchange_mdn() -> Result<()> {
    let t = TestContext::new_alice().await;

    let original =
        include_bytes!("../../test-data/message/ms_exchange_report_original_message.eml");
    receive_imf(&t, original, false).await?;
    let original_msg_id = t.get_last_msg().await.id;

    // 1. Test mimeparser directly
    let mdn =
        include_bytes!("../../test-data/message/ms_exchange_report_disposition_notification.eml");
    let mimeparser = MimeMessage::from_bytes(&t.ctx, mdn, None).await?;
    assert_eq!(mimeparser.mdn_reports.len(), 1);
    assert_eq!(
        mimeparser.mdn_reports[0].original_message_id.as_deref(),
        Some("d5904dc344eeb5deaf9bb44603f0c716@posteo.de")
    );
    assert!(mimeparser.mdn_reports[0].additional_message_ids.is_empty());

    // 2. Test that marking the original msg as read works
    receive_imf(&t, mdn, false).await?;

    assert_eq!(
        original_msg_id.get_state(&t).await?,
        MessageState::OutMdnRcvd
    );

    Ok(())
}

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

    let mime_message = MimeMessage::from_bytes(
        &alice,
        include_bytes!("../../test-data/message/attached-eml.eml"),
        None,
    )
    .await?;

    assert_eq!(mime_message.parts.len(), 1);
    assert_eq!(mime_message.parts[0].typ, Viewtype::File);
    assert_eq!(
        mime_message.parts[0].mimetype,
        Some("message/rfc822".parse().unwrap(),)
    );
    assert_eq!(
        mime_message.parts[0].msg,
        "this is a classic email – I attached the .EML file".to_string()
    );
    assert_eq!(
        mime_message.parts[0].param.get(Param::Filename),
        Some(".eml")
    );

    assert_eq!(mime_message.parts[0].org_filename, Some(".eml".to_string()));

    Ok(())
}

/// Tests parsing of MIME message containing RFC 9078 reaction.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_parse_reaction() -> Result<()> {
    let alice = TestContext::new_alice().await;

    let mime_message = MimeMessage::from_bytes(
        &alice,
        "To: alice@example.org\n\
From: bob@example.net\n\
Date: Today, 29 February 2021 00:00:10 -800\n\
Message-ID: 56789@example.net\n\
In-Reply-To: 12345@example.org\n\
Subject: Meeting\n\
Mime-Version: 1.0 (1.0)\n\
Content-Type: text/plain; charset=utf-8\n\
Content-Disposition: reaction\n\
\n\
\u{1F44D}"
            .as_bytes(),
        None,
    )
    .await?;

    assert_eq!(mime_message.parts.len(), 1);
    assert_eq!(mime_message.parts[0].is_reaction, true);
    assert_eq!(
        mime_message
            .get_header(HeaderDef::InReplyTo)
            .and_then(|msgid| parse_message_id(msgid).ok())
            .unwrap(),
        "12345@example.org"
    );

    Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_jpeg_as_application_octet_stream() -> Result<()> {
    let context = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/jpeg-as-application-octet-stream.eml");

    let msg = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(msg.parts.len(), 1);
    assert_eq!(msg.parts[0].typ, Viewtype::Image);

    receive_imf(&context, &raw[..], false).await?;
    let msg = context.get_last_msg().await;
    assert_eq!(msg.get_viewtype(), Viewtype::Image);

    Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_schleuder() -> Result<()> {
    let context = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/schleuder.eml");

    let msg = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(msg.parts.len(), 2);

    // Header part.
    assert_eq!(msg.parts[0].typ, Viewtype::Text);

    // Actual contents part.
    assert_eq!(msg.parts[1].typ, Viewtype::Text);
    assert_eq!(msg.parts[1].msg, "hello,\nbye");

    Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_tlsrpt() -> Result<()> {
    let context = TestContext::new_alice().await;
    let raw = include_bytes!("../../test-data/message/tlsrpt.eml");

    let msg = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(msg.parts.len(), 1);

    assert_eq!(msg.parts[0].typ, Viewtype::File);
    assert_eq!(
        msg.parts[0].msg,
        "Report Domain: nine.testrun.org Submitter: google.com Report-ID: <2024.01.20T00.00.00Z+nine.testrun.org@google.com> – This is an aggregate TLS report from google.com"
    );

    Ok(())
}

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

    let beginning_time = time();

    // Receive a message with a date far in the future (year 3004)
    // I'm just going to assume that no one uses this code after the year 3000
    let mime_message = MimeMessage::from_bytes(
        &alice,
        b"To: alice@example.org\n\
              From: bob@example.net\n\
              Date: Today, 29 February 3004 00:00:10 -800\n\
              Message-ID: 56789@example.net\n\
              Subject: Meeting\n\
              Mime-Version: 1.0 (1.0)\n\
              Content-Type: text/plain; charset=utf-8\n\
              \n\
              Hi",
        None,
    )
    .await?;

    // We do allow the time to be in the future a bit (because of unsynchronized clocks),
    // but only 60 seconds:
    assert!(mime_message.timestamp_sent <= time() + 60);
    assert!(mime_message.timestamp_sent >= beginning_time + 60);
    assert!(mime_message.timestamp_rcvd <= time());

    Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hp_legacy_display() -> Result<()> {
    let mut tcm = TestContextManager::new();
    let alice = &tcm.alice().await;
    let bob = &tcm.bob().await;

    let mut msg = Message::new_text(
        "Subject: Dinner plans\n\
        \n\
        Let's eat"
            .to_string(),
    );
    msg.set_subject("Dinner plans".to_string());
    let chat_id = alice.create_chat(bob).await.id;
    alice.set_config_bool(Config::TestHooks, true).await?;
    *alice.pre_encrypt_mime_hook.lock() = Some(|_, mut mime| {
        for (h, v) in &mut mime.headers {
            if h == "Content-Type"
                && let mail_builder::headers::HeaderType::ContentType(ct) = v
            {
                *ct = ct.clone().attribute("hp-legacy-display", "1");
            }
        }
        mime
    });
    let sent_msg = alice.send_msg(chat_id, &mut msg).await;

    let msg_bob = bob.recv_msg(&sent_msg).await;
    assert_eq!(msg_bob.subject, "Dinner plans");
    assert_eq!(msg_bob.text, "Let's eat");
    Ok(())
}

/// Tests that subject is not prepended to the message
/// when bot receives it.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_bot_no_subject() {
    let context = TestContext::new().await;
    context.set_config(Config::Bot, Some("1")).await.unwrap();
    let raw = br#"Message-ID: <foobar@example.org>
From: foo <foo@example.org>
Subject: Some subject
To: bar@example.org
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8

/help
"#;

    let message = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(message.get_subject(), Some("Some subject".to_string()));

    assert_eq!(message.parts.len(), 1);
    assert_eq!(message.parts[0].typ, Viewtype::Text);
    // Not "Some subject – /help"
    assert_eq!(message.parts[0].msg, "/help");
}

/// Tests that Delta Chat takes the last header value
/// rather than the first one if multiple headers
/// are present.
///
/// DKIM signature applies to the last N headers
/// if header name is included N times in
/// DKIM-Signature.
///
/// If the client takes the first header
/// rather than the last, it can be fooled
/// into using unsigned header
/// when signed one is present
/// but not protected by oversigning.
///
/// See
/// <https://www.zone.eu/blog/2024/05/17/bimi-and-dmarc-cant-save-you/>
/// for reference.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_take_last_header() {
    let context = TestContext::new().await;

    // Mallory added second From: header.
    let raw = b"From: mallory@example.org\n\
                    From: alice@example.org\n\
                    Content-Type: text/plain\n\
                    Chat-Version: 1.0\n\
                    \n\
                    Hello\n\
                    ";

    let mimeparser = MimeMessage::from_bytes(&context.ctx, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(
        mimeparser.get_header(HeaderDef::From_).unwrap(),
        "alice@example.org"
    );
}

/// Tests that CRLF before MIME boundary
/// is not treated as the part body.
///
/// RFC 2046 explicitly says that
/// "The CRLF preceding the boundary delimiter line is conceptually attached
/// to the boundary so that it is possible to have a part that does not end
/// with a CRLF (line break). Body parts that must be considered to end with
/// line breaks, therefore, must have two CRLFs preceding the boundary delimiter
/// line, the first of which is part of the preceding body part,
/// and the second of which is part of the encapsulation boundary."
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mimeparser_trailing_newlines() {
    let context = TestContext::new_alice().await;

    // Example from <https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1>
    // with a `Content-Disposition` headers added to turn files
    // into attachments.
    let raw = b"From: Nathaniel Borenstein <nsb@bellcore.com>\r
To: Ned Freed <ned@innosoft.com>\r
Date: Sun, 21 Mar 1993 23:56:48 -0800 (PST)\r
Subject: Sample message\r
MIME-Version: 1.0\r
Content-type: multipart/mixed; boundary=\"simple boundary\"\r
\r
This is the preamble.  It is to be ignored, though it\r
is a handy place for composition agents to include an\r
explanatory note to non-MIME conformant readers.\r
\r
--simple boundary\r
Content-Disposition: attachment; filename=\"file1.txt\"\r
\r
This is implicitly typed plain US-ASCII text.\r
It does NOT end with a linebreak.\r
--simple boundary\r
Content-type: text/plain; charset=us-ascii\r
Content-Disposition: attachment; filename=\"file2.txt\"\r
\r
This is explicitly typed plain US-ASCII text.\r
It DOES end with a linebreak.\r
\r
--simple boundary--\r
\r
This is the epilogue.  It is also to be ignored.";

    let mimeparser = MimeMessage::from_bytes(&context, &raw[..], None)
        .await
        .unwrap();

    assert_eq!(mimeparser.parts.len(), 2);

    assert_eq!(mimeparser.parts[0].typ, Viewtype::File);
    let blob: BlobObject = mimeparser.parts[0]
        .param
        .get_file_blob(&context)
        .unwrap()
        .unwrap();
    assert_eq!(
        tokio::fs::read_to_string(blob.to_abs_path()).await.unwrap(),
        "This is implicitly typed plain US-ASCII text.\r\nIt does NOT end with a linebreak."
    );

    assert_eq!(mimeparser.parts[1].typ, Viewtype::File);
    let blob: BlobObject = mimeparser.parts[1]
        .param
        .get_file_blob(&context)
        .unwrap()
        .unwrap();
    assert_eq!(
        tokio::fs::read_to_string(blob.to_abs_path()).await.unwrap(),
        "This is explicitly typed plain US-ASCII text.\r\nIt DOES end with a linebreak.\r\n"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hidden_message_id() {
    let t = &TestContext::new().await;
    let raw = br#"Message-ID: bar@example.org
Date: Sun, 08 Dec 2019 23:12:55 +0000
To: <alice@example.org>
From: <tunis4@example.org>
Content-Type: multipart/mixed; boundary="luTiGu6GBoVLCvTkzVtmZmwsmhkNMw"


--luTiGu6GBoVLCvTkzVtmZmwsmhkNMw
Message-ID: foo@example.org
Content-Type: text/plain; charset=utf-8

Message with a correct Message-ID hidden header

--luTiGu6GBoVLCvTkzVtmZmwsmhkNMw--
"#;

    let message = MimeMessage::from_bytes(t, &raw[..], None).await.unwrap();
    assert_eq!(message.get_rfc724_mid().unwrap(), "foo@example.org");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_chat_edit_imf_header() -> Result<()> {
    let mut tcm = TestContextManager::new();
    let alice = &tcm.alice().await;
    let bob = &tcm.bob().await;
    let alice_chat = alice.create_email_chat(bob).await;

    // Alice sends a message, then sends an invalid edit request.
    let sent1 = alice.send_text(alice_chat.id, "foo").await;
    let alice_msg = sent1.load_from_db().await;
    assert_eq!(alice_chat.id.get_msg_cnt(alice).await?, 1);

    chat::send_edit_request(alice, alice_msg.id, "bar".to_string()).await?;
    let mut sent2 = alice.pop_sent_msg().await;
    let mut s0 = String::new();
    let mut s1 = String::new();
    for l in sent2.payload.lines() {
        if l.starts_with("Chat-Edit:") {
            s1 += l;
            s1 += "\n";
            continue;
        }
        s0 += l;
        s0 += "\n";
        if l.starts_with("Message-ID:") && s1.is_empty() {
            s1 = mem::take(&mut s0);
        }
    }
    sent2.payload = s1 + &s0;

    // Bob receives both messages, the edit request with "Chat-Edit" in IMF headers is
    // received as text message.
    let bob_msg = bob.recv_msg(&sent1).await;
    assert_eq!(bob_msg.text, "foo");
    assert_eq!(bob_msg.chat_id.get_msg_cnt(bob).await?, 1);
    let bob_msg = bob.recv_msg(&sent2).await;
    assert_eq!(bob_msg.text, constants::EDITED_PREFIX.to_string() + "bar");
    assert_eq!(bob_msg.chat_id.get_msg_cnt(bob).await?, 2);

    Ok(())
}

/// Tests that the last valid Autocrypt header is taken:
/// - The 3rd header is skipped because of the unknown critical attribute.
/// - The 2nd header is taken despite it has an unknown non-critical attribute.
/// - The 1st header shouldn't be looked at.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_multiple_autocrypt_hdrs() -> Result<()> {
    let mut tcm = TestContextManager::new();
    let bob = &tcm.bob().await;
    let msg_id = receive_imf(
        bob,
        include_bytes!("../../test-data/message/thunderbird_with_multiple_autocrypts.eml"),
        false,
    )
    .await?
    .unwrap()
    .msg_ids[0];
    let msg = Message::load_from_db(bob, msg_id).await?;
    assert!(msg.get_showpadlock());
    Ok(())
}

/// Tests that timestamp of signed but not encrypted message is protected.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_protected_date() -> Result<()> {
    let mut tcm = TestContextManager::new();
    let alice = &tcm.alice().await;
    let bob = &tcm.bob().await;

    alice.set_config(Config::SignUnencrypted, Some("1")).await?;

    let alice_chat = alice.create_email_chat(bob).await;
    let alice_msg_id = chat::send_text_msg(alice, alice_chat.id, "Hello!".to_string()).await?;
    let alice_msg = Message::load_from_db(alice, alice_msg_id).await?;
    assert_eq!(alice_msg.get_showpadlock(), false);

    let mut sent_msg = alice.pop_sent_msg().await;
    sent_msg.payload = sent_msg.payload.replacen(
        "Date:",
        "Date: Wed, 17 Mar 2021 14:30:53 +0100 (CET)\r\nX-Not-Date:",
        1,
    );
    let bob_msg = bob.recv_msg(&sent_msg).await;
    assert_eq!(alice_msg.get_text(), bob_msg.get_text());

    // Timestamp that the sender has put into the message
    // should always be displayed as is on the receiver.
    assert_eq!(alice_msg.get_timestamp(), bob_msg.get_timestamp());
    Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_huge_image_becomes_file() -> Result<()> {
    let t = TestContext::new_alice().await;
    let msg_id = receive_imf(
        &t,
        include_bytes!("../../test-data/message/image_huge_64M.eml"),
        false,
    )
    .await?
    .unwrap()
    .msg_ids[0];
    let msg = Message::load_from_db(&t.ctx, msg_id).await.unwrap();
    // Huge image should be treated as file:
    assert_eq!(msg.viewtype, Viewtype::File);
    assert!(msg.get_file(&t).is_some());
    assert_eq!(msg.get_filename().unwrap(), "huge_image.png");
    assert_eq!(msg.get_filemime().unwrap(), "image/png");
    // File has no width or height
    assert!(msg.param.get_int(Param::Width).is_none());
    assert!(msg.param.get_int(Param::Height).is_none());
    Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_4k_image_stays_image() -> Result<()> {
    let t = TestContext::new_alice().await;
    let msg_id = receive_imf(
        &t,
        include_bytes!("../../test-data/message/image_4k.eml"),
        false,
    )
    .await?
    .unwrap()
    .msg_ids[0];
    let msg = Message::load_from_db(&t.ctx, msg_id).await.unwrap();
    // 4K image should be treated as image:
    assert_eq!(msg.viewtype, Viewtype::Image);
    assert!(msg.get_file(&t).is_some());
    assert_eq!(msg.get_filename().unwrap(), "4k_image.png");
    assert_eq!(msg.get_filemime().unwrap(), "image/png");
    assert_eq!(msg.param.get_int(Param::Width).unwrap_or_default(), 3840);
    assert_eq!(msg.param.get_int(Param::Height).unwrap_or_default(), 2160);
    Ok(())
}

/// Tests that if multiple alternatives are available in multipart/alternative,
/// the last one is preferred.
///
/// RFC 2046 says the last supported alternative should be preferred:
/// <https://datatracker.ietf.org/doc/html/rfc2046#section-5.1.4>
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn prefer_last_alternative() {
    let mut tcm = TestContextManager::new();
    let context = &tcm.alice().await;
    let raw = br#"From: Bob <bob@example.net>
To: Alice <alice@example.org>
Subject: Alternatives
Date: Tue, 5 May 2020 01:23:45 +0000
MIME-Version: 1.0
Chat-Version: 1.0
Content-Type: multipart/alternative; boundary="boundary"

This is a multipart message in MIME format.

--boundary
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit

First alternative.
--boundary
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit

Second alternative.
--boundary
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit

Third alternative.
--boundary--
"#;

    let message = MimeMessage::from_bytes(context, &raw[..], None)
        .await
        .unwrap();
    assert_eq!(message.parts.len(), 1);
    assert_eq!(message.parts[0].typ, Viewtype::Text);
    assert_eq!(message.parts[0].msg, "Third alternative.");
}