aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/pixart/messenger/services/XmppConnectionService.java
blob: bb443c3759be531b0b98a9a547728fac402172f7 (plain)
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
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
package de.pixart.messenger.services;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.security.KeyChain;
import android.support.annotation.BoolRes;
import android.support.annotation.IntegerRes;
import android.support.v4.app.RemoteInput;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.LruCache;
import android.util.Pair;

import net.java.otr4j.OtrException;
import net.java.otr4j.session.Session;
import net.java.otr4j.session.SessionID;
import net.java.otr4j.session.SessionImpl;
import net.java.otr4j.session.SessionStatus;

import org.conscrypt.Conscrypt;
import org.openintents.openpgp.IOpenPgpService2;
import org.openintents.openpgp.util.OpenPgpApi;
import org.openintents.openpgp.util.OpenPgpServiceConnection;

import java.net.URL;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

import de.pixart.messenger.BuildConfig;
import de.pixart.messenger.Config;
import de.pixart.messenger.R;
import de.pixart.messenger.android.JabberIdContact;
import de.pixart.messenger.crypto.OmemoSetting;
import de.pixart.messenger.crypto.PgpDecryptionService;
import de.pixart.messenger.crypto.PgpEngine;
import de.pixart.messenger.crypto.axolotl.AxolotlService;
import de.pixart.messenger.crypto.axolotl.FingerprintStatus;
import de.pixart.messenger.crypto.axolotl.XmppAxolotlMessage;
import de.pixart.messenger.entities.Account;
import de.pixart.messenger.entities.Blockable;
import de.pixart.messenger.entities.Bookmark;
import de.pixart.messenger.entities.Contact;
import de.pixart.messenger.entities.Conversation;
import de.pixart.messenger.entities.Conversational;
import de.pixart.messenger.entities.DownloadableFile;
import de.pixart.messenger.entities.Message;
import de.pixart.messenger.entities.MucOptions;
import de.pixart.messenger.entities.MucOptions.OnRenameListener;
import de.pixart.messenger.entities.Presence;
import de.pixart.messenger.entities.PresenceTemplate;
import de.pixart.messenger.entities.Roster;
import de.pixart.messenger.entities.ServiceDiscoveryResult;
import de.pixart.messenger.entities.Transferable;
import de.pixart.messenger.entities.TransferablePlaceholder;
import de.pixart.messenger.generator.AbstractGenerator;
import de.pixart.messenger.generator.IqGenerator;
import de.pixart.messenger.generator.MessageGenerator;
import de.pixart.messenger.generator.PresenceGenerator;
import de.pixart.messenger.http.CustomURLStreamHandlerFactory;
import de.pixart.messenger.http.HttpConnectionManager;
import de.pixart.messenger.parser.AbstractParser;
import de.pixart.messenger.parser.IqParser;
import de.pixart.messenger.parser.MessageParser;
import de.pixart.messenger.parser.PresenceParser;
import de.pixart.messenger.persistance.DatabaseBackend;
import de.pixart.messenger.persistance.FileBackend;
import de.pixart.messenger.ui.SettingsActivity;
import de.pixart.messenger.ui.UiCallback;
import de.pixart.messenger.ui.interfaces.OnAvatarPublication;
import de.pixart.messenger.ui.interfaces.OnMediaLoaded;
import de.pixart.messenger.ui.interfaces.OnSearchResultsAvailable;
import de.pixart.messenger.utils.Compatibility;
import de.pixart.messenger.utils.ConversationsFileObserver;
import de.pixart.messenger.utils.CryptoHelper;
import de.pixart.messenger.utils.ExceptionHelper;
import de.pixart.messenger.utils.MimeUtils;
import de.pixart.messenger.utils.Namespace;
import de.pixart.messenger.utils.OnPhoneContactsLoadedListener;
import de.pixart.messenger.utils.PhoneHelper;
import de.pixart.messenger.utils.QuickLoader;
import de.pixart.messenger.utils.ReplacingSerialSingleThreadExecutor;
import de.pixart.messenger.utils.ReplacingTaskManager;
import de.pixart.messenger.utils.Resolver;
import de.pixart.messenger.utils.SerialSingleThreadExecutor;
import de.pixart.messenger.utils.StringUtils;
import de.pixart.messenger.utils.WakeLockHelper;
import de.pixart.messenger.utils.XmppUri;
import de.pixart.messenger.xml.Element;
import de.pixart.messenger.xmpp.OnBindListener;
import de.pixart.messenger.xmpp.OnContactStatusChanged;
import de.pixart.messenger.xmpp.OnIqPacketReceived;
import de.pixart.messenger.xmpp.OnKeyStatusUpdated;
import de.pixart.messenger.xmpp.OnMessageAcknowledged;
import de.pixart.messenger.xmpp.OnMessagePacketReceived;
import de.pixart.messenger.xmpp.OnPresencePacketReceived;
import de.pixart.messenger.xmpp.OnStatusChanged;
import de.pixart.messenger.xmpp.OnUpdateBlocklist;
import de.pixart.messenger.xmpp.Patches;
import de.pixart.messenger.xmpp.XmppConnection;
import de.pixart.messenger.xmpp.chatstate.ChatState;
import de.pixart.messenger.xmpp.forms.Data;
import de.pixart.messenger.xmpp.jid.OtrJidHelper;
import de.pixart.messenger.xmpp.jingle.JingleConnectionManager;
import de.pixart.messenger.xmpp.jingle.OnJinglePacketReceived;
import de.pixart.messenger.xmpp.jingle.stanzas.JinglePacket;
import de.pixart.messenger.xmpp.mam.MamReference;
import de.pixart.messenger.xmpp.pep.Avatar;
import de.pixart.messenger.xmpp.pep.PublishOptions;
import de.pixart.messenger.xmpp.stanzas.IqPacket;
import de.pixart.messenger.xmpp.stanzas.MessagePacket;
import de.pixart.messenger.xmpp.stanzas.PresencePacket;
import me.leolin.shortcutbadger.ShortcutBadger;
import rocks.xmpp.addr.Jid;

public class XmppConnectionService extends Service {

    public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
    public static final String ACTION_MARK_AS_READ = "mark_as_read";
    public static final String ACTION_SNOOZE = "snooze";
    public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
    public static final String ACTION_TRY_AGAIN = "try_again";
    public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
    public static final String ACTION_IDLE_PING = "idle_ping";
    public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh";
    public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received";
    public static final String FDroid = "org.fdroid.fdroid";
    public static final String PlayStore = "com.android.vending";
    private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp";

    static {
        URL.setURLStreamHandlerFactory(new CustomURLStreamHandlerFactory());
    }

    public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
    private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor("FileAdding");
    private final SerialSingleThreadExecutor mVideoCompressionExecutor = new SerialSingleThreadExecutor("VideoCompression");
    private final SerialSingleThreadExecutor mDatabaseWriterExecutor = new SerialSingleThreadExecutor("DatabaseWriter");
    private final SerialSingleThreadExecutor mDatabaseReaderExecutor = new SerialSingleThreadExecutor("DatabaseReader");
    private final SerialSingleThreadExecutor mNotificationExecutor = new SerialSingleThreadExecutor("NotificationExecutor");
    private final ReplacingTaskManager mRosterSyncTaskManager = new ReplacingTaskManager();
    private final IBinder mBinder = new XmppConnectionBinder();
    private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
    private final IqGenerator mIqGenerator = new IqGenerator(this);
    private final List<String> mInProgressAvatarFetches = new ArrayList<>();
    private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
    private final OnIqPacketReceived mDefaultIqHandler = (account, packet) -> {
        if (packet.getType() != IqPacket.TYPE.RESULT) {
            Element error = packet.findChild("error");
            String text = error != null ? error.findChildContent("text") : null;
            if (text != null) {
                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received iq error - " + text);
            }
        }
    };
    //Ui callback listeners
    private final Set<OnConversationUpdate> mOnConversationUpdates = Collections.newSetFromMap(new WeakHashMap<OnConversationUpdate, Boolean>());
    private final Set<OnShowErrorToast> mOnShowErrorToasts = Collections.newSetFromMap(new WeakHashMap<OnShowErrorToast, Boolean>());
    private final Set<OnAccountUpdate> mOnAccountUpdates = Collections.newSetFromMap(new WeakHashMap<OnAccountUpdate, Boolean>());
    private final Set<OnCaptchaRequested> mOnCaptchaRequested = Collections.newSetFromMap(new WeakHashMap<OnCaptchaRequested, Boolean>());
    private final Set<OnRosterUpdate> mOnRosterUpdates = Collections.newSetFromMap(new WeakHashMap<OnRosterUpdate, Boolean>());
    private final Set<OnUpdateBlocklist> mOnUpdateBlocklist = Collections.newSetFromMap(new WeakHashMap<OnUpdateBlocklist, Boolean>());
    private final Set<OnMucRosterUpdate> mOnMucRosterUpdate = Collections.newSetFromMap(new WeakHashMap<OnMucRosterUpdate, Boolean>());
    private final Set<OnKeyStatusUpdated> mOnKeyStatusUpdated = Collections.newSetFromMap(new WeakHashMap<OnKeyStatusUpdated, Boolean>());
    private final Object LISTENER_LOCK = new Object();
    public DatabaseBackend databaseBackend;
    private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {

        @Override
        public boolean onMessageAcknowledged(Account account, String uuid) {
            for (final Conversation conversation : getConversations()) {
                if (conversation.getAccount() == account) {
                    Message message = conversation.findUnsentMessageWithUuid(uuid);
                    if (message != null) {
                        message.setStatus(Message.STATUS_SEND);
                        message.setErrorMessage(null);
                        databaseBackend.updateMessage(message, false);
                        return true;
                    }
                }
            }
            return false;
        }
    };
    public FileBackend fileBackend = new FileBackend(this);
    private final ConversationsFileObserver fileObserver = new ConversationsFileObserver(
            Environment.getExternalStorageDirectory().getAbsolutePath()
    ) {
        @Override
        public void onEvent(int event, String path) {
            Log.d(Config.LOGTAG, "event " + event + " path=" + path);
            markFileDeleted(path);
        }
    };
    public HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(this);
    private ReplacingSerialSingleThreadExecutor mContactMergerExecutor = new ReplacingSerialSingleThreadExecutor("ContactMerger");
    private long mLastActivity = 0;
    private MemorizingTrustManager mMemorizingTrustManager;
    private NotificationService mNotificationService = new NotificationService(this);
    private ShortcutService mShortcutService = new ShortcutService(this);
    private AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
    protected AtomicBoolean mForceForegroundService = new AtomicBoolean(false);
    private OnMessagePacketReceived mMessageParser = new MessageParser(this);
    private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
    private IqParser mIqParser = new IqParser(this);
    private MessageGenerator mMessageGenerator = new MessageGenerator(this);
    private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
    private List<Account> accounts;
    private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(this);
    public OnContactStatusChanged onContactStatusChanged = (contact, online) -> {
        Conversation conversation = find(getConversations(), contact);
        if (conversation != null) {
            if (online) {
                conversation.endOtrIfNeeded();
                if (contact.getPresences().size() == 1) {
                    sendUnsentMessages(conversation);
                }
            } else {
                //check if the resource we are haveing a conversation with is still online
                if (conversation.hasValidOtrSession()) {
                    String otrResource = conversation.getOtrSession().getSessionID().getUserID();
                    if (!(Arrays.asList(contact.getPresences().toResourceArray()).contains(otrResource))) {
                        conversation.endOtrIfNeeded();
                    }
                }
            }
        }
    };
    private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {

        @Override
        public void onJinglePacketReceived(Account account, JinglePacket packet) {
            mJingleConnectionManager.deliverPacket(account, packet);
        }
    };
    private AvatarService mAvatarService = new AvatarService(this);
    private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
    private PushManagementService mPushManagementService = new PushManagementService(this);
    private QuickConversationsService mQuickConversationsService = new QuickConversationsService(this);
    private final OnBindListener mOnBindListener = new OnBindListener() {

        @Override
        public void onBind(final Account account) {
            synchronized (mInProgressAvatarFetches) {
                for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
                    final String KEY = iterator.next();
                    if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
                        iterator.remove();
                    }
                }
            }
            boolean needsUpdating = account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, true);
            needsUpdating |= account.setOption(Account.OPTION_HTTP_UPLOAD_AVAILABLE, account.getXmppConnection().getFeatures().httpUpload(0));
            if (needsUpdating) {
                databaseBackend.updateAccount(account);
            }
            account.getRoster().clearPresences();
            mJingleConnectionManager.cancelInTransmission();
            fetchRosterFromServer(account);
            if (!account.getXmppConnection().getFeatures().bookmarksConversion()) {
                fetchBookmarks(account);
            }
            final boolean flexible = account.getXmppConnection().getFeatures().flexibleOfflineMessageRetrieval();
            final boolean catchup = getMessageArchiveService().inCatchup(account);
            if (flexible && catchup) {
                sendIqPacket(account, mIqGenerator.purgeOfflineMessages(), (acc, packet) -> {
                    if (packet.getType() == IqPacket.TYPE.RESULT) {
                        Log.d(Config.LOGTAG, acc.getJid().asBareJid() + ": successfully purged offline messages");
                    }
                });
            }
            sendPresence(account);
            if (mPushManagementService.available(account)) {
                mPushManagementService.registerPushTokenOnServer(account);
            }
            connectMultiModeConversations(account);
            syncDirtyContacts(account);
        }
    };
    private int unreadCount = -1;
    private AtomicLong mLastExpiryRun = new AtomicLong(0);
    private SecureRandom mRandom;
    private LruCache<Pair<String, String>, ServiceDiscoveryResult> discoCache = new LruCache<>(20);
    private OnStatusChanged statusListener = new OnStatusChanged() {

        @Override
        public void onStatusChanged(final Account account) {
            XmppConnection connection = account.getXmppConnection();
            updateAccountUi();
            if (account.getStatus() == Account.State.ONLINE || account.getStatus().isError()) {
                mQuickConversationsService.signalAccountStateChange();
            }
            if (account.getStatus() == Account.State.ONLINE) {
                synchronized (mLowPingTimeoutMode) {
                    if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
                    }
                }
                if (account.setShowErrorNotification(true)) {
                    databaseBackend.updateAccount(account);
                }
                mMessageArchiveService.executePendingQueries(account);
                if (connection != null && connection.getFeatures().csi()) {
                    if (checkListeners()) {
                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//inactive");
                        connection.sendInactive();
                    } else {
                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//active");
                        connection.sendActive();
                    }
                }
                List<Conversation> conversations = getConversations();
                for (Conversation conversation : conversations) {
                    if (conversation.getAccount() == account
                            && !account.pendingConferenceJoins.contains(conversation)) {
                        if (!conversation.startOtrIfNeeded()) {
                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": couldn't start OTR with " + conversation.getContact().getJid() + " when needed");
                        }
                        checkDeletedFiles(conversation);
                        sendUnsentMessages(conversation);
                        resendFailedFileMessages(conversation);
                    }
                }
                for (Conversation conversation : account.pendingConferenceLeaves) {
                    leaveMuc(conversation);
                }
                account.pendingConferenceLeaves.clear();
                for (Conversation conversation : account.pendingConferenceJoins) {
                    joinMuc(conversation);
                }
                account.pendingConferenceJoins.clear();
                scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
            } else if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) {
                resetSendingToWaiting(account);
                if (account.isEnabled() && isInLowPingTimeoutMode(account)) {
                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": went into offline state during low ping mode. reconnecting now");
                    reconnectAccount(account, true, false);
                } else {
                    int timeToReconnect = mRandom.nextInt(10) + 2;
                    scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
                }
            } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
                databaseBackend.updateAccount(account);
                reconnectAccount(account, true, false);
            } else if (account.getStatus() != Account.State.CONNECTING && account.getStatus() != Account.State.NO_INTERNET) {
                resetSendingToWaiting(account);
                if (connection != null && account.getStatus().isAttemptReconnect()) {
                    final int next = connection.getTimeToNextAttempt();
                    final boolean lowPingTimeoutMode = isInLowPingTimeoutMode(account);
                    if (next <= 0) {
                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. reconnecting now. lowPingTimeout=" + Boolean.toString(lowPingTimeoutMode));
                        reconnectAccount(account, true, false);
                    } else {
                        final int attempt = connection.getAttempt() + 1;
                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. try again in " + next + "s for the " + attempt + " time. lowPingTimeout=" + Boolean.toString(lowPingTimeoutMode));
                        scheduleWakeUpCall(next, account.getUuid().hashCode());
                    }
                }
            }
            getNotificationService().updateErrorNotification();
        }
    };

    private OpenPgpServiceConnection pgpServiceConnection;
    private PgpEngine mPgpEngine = null;
    private WakeLock wakeLock;
    private PowerManager pm;
    private LruCache<String, Bitmap> mBitmapCache;
    private BroadcastReceiver mInternalEventReceiver = new InternalEventReceiver();
    private BroadcastReceiver mInternalScreenEventReceiver = new InternalEventReceiver();

    private static String generateFetchKey(Account account, final Avatar avatar) {
        return account.getJid().asBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
    }

    private boolean isInLowPingTimeoutMode(Account account) {
        synchronized (mLowPingTimeoutMode) {
            return mLowPingTimeoutMode.contains(account.getJid().asBareJid());
        }
    }

    public void startForcingForegroundNotification() {
        mForceForegroundService.set(true);
        toggleForegroundService();
    }

    public void stopForcingForegroundNotification() {
        mForceForegroundService.set(false);
        toggleForegroundService();
    }

    public boolean areMessagesInitialized() {
        return this.restoredFromDatabaseLatch.getCount() == 0;
    }

    public PgpEngine getPgpEngine() {
        if (!Config.supportOpenPgp()) {
            return null;
        } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
            if (this.mPgpEngine == null) {
                this.mPgpEngine = new PgpEngine(new OpenPgpApi(
                        getApplicationContext(),
                        pgpServiceConnection.getService()), this);
            }
            return mPgpEngine;
        } else {
            return null;
        }

    }

    public OpenPgpApi getOpenPgpApi() {
        if (!Config.supportOpenPgp()) {
            return null;
        } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
            return new OpenPgpApi(this, pgpServiceConnection.getService());
        } else {
            return null;
        }
    }

    public FileBackend getFileBackend() {
        return this.fileBackend;
    }

    public AvatarService getAvatarService() {
        return this.mAvatarService;
    }

    public void attachLocationToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
        int encryption = conversation.getNextEncryption();
        if (encryption == Message.ENCRYPTION_PGP) {
            encryption = Message.ENCRYPTION_DECRYPTED;
        }
        Message message = new Message(conversation, uri.toString(), encryption);
        if (conversation.getNextCounterpart() != null) {
            message.setCounterpart(conversation.getNextCounterpart());
        }
        if (encryption == Message.ENCRYPTION_DECRYPTED) {
            getPgpEngine().encrypt(message, callback);
        } else {
            sendMessage(message);
            callback.success(message);
        }
    }

    public void attachFileToConversation(final Conversation conversation, final Uri uri, final String type, final UiCallback<Message> callback) {
        final Message message;
        if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
            message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
        } else {
            message = new Message(conversation, "", conversation.getNextEncryption());
        }
        message.setCounterpart(conversation.getNextCounterpart());
        message.setType(Message.TYPE_FILE);
        final AttachFileToConversationRunnable runnable = new AttachFileToConversationRunnable(this, uri, type, message, callback);
        if (runnable.isVideoMessage()) {
            mVideoCompressionExecutor.execute(runnable);
        } else {
            mFileAddingExecutor.execute(runnable);
        }
    }

    public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
        final String mimeType = MimeUtils.guessMimeTypeFromUri(this, uri);
        final String compressPictures = getCompressPicturesPreference();

        if ("never".equals(compressPictures)
                || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
                || (mimeType != null && mimeType.endsWith("/gif"))
                || getFileBackend().unusualBounds(uri)) {
            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": not compressing picture. sending as file");
            attachFileToConversation(conversation, uri, mimeType, callback);
            return;
        }
        final Message message;
        if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
            message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
        } else {
            message = new Message(conversation, "", conversation.getNextEncryption());
        }
        message.setCounterpart(conversation.getNextCounterpart());
        message.setType(Message.TYPE_IMAGE);
        mFileAddingExecutor.execute(() -> {
            try {
                getFileBackend().copyImageToPrivateStorage(message, uri);
                if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
                    final PgpEngine pgpEngine = getPgpEngine();
                    if (pgpEngine != null) {
                        pgpEngine.encrypt(message, callback);
                    } else if (callback != null) {
                        callback.error(R.string.unable_to_connect_to_keychain, null);
                    }
                } else {
                    sendMessage(message);
                    callback.success(message);
                }
            } catch (final FileBackend.FileCopyException e) {
                callback.error(e.getResId(), message);
            }
        });
    }

    public Conversation find(Bookmark bookmark) {
        return find(bookmark.getAccount(), bookmark.getJid());
    }

    public Conversation find(final Account account, final Jid jid) {
        return find(getConversations(), account, jid);
    }

    public boolean isMuc(final Account account, final Jid jid) {
        final Conversation c = find(account, jid);
        return c != null && c.getMode() == Conversational.MODE_MULTI;
    }

    public void search(List<String> term, OnSearchResultsAvailable onSearchResultsAvailable) {
        MessageSearchTask.search(this, term, onSearchResultsAvailable);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        final String action = intent == null ? null : intent.getAction();
        String pushedAccountHash = null;
        boolean interactive = false;
        if (action != null) {
            final String uuid = intent.getStringExtra("uuid");
            switch (action) {
                case ConnectivityManager.CONNECTIVITY_ACTION:
                    if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
                        resetAllAttemptCounts(true, false);
                    }
                    break;
                case Intent.ACTION_SHUTDOWN:
                    logoutAndSave(true);
                    return START_NOT_STICKY;
                case ACTION_CLEAR_NOTIFICATION:
                    mNotificationExecutor.execute(() -> {
                        try {
                            final Conversation c = findConversationByUuid(uuid);
                            if (c != null) {
                                mNotificationService.clear(c);
                            } else {
                                mNotificationService.clear();
                            }
                            restoredFromDatabaseLatch.await();

                        } catch (InterruptedException e) {
                            Log.d(Config.LOGTAG, "unable to process clear notification");
                        }
                    });
                    break;
                case ACTION_DISMISS_ERROR_NOTIFICATIONS:
                    dismissErrorNotifications();
                    break;
                case ACTION_TRY_AGAIN:
                    resetAllAttemptCounts(false, true);
                    interactive = true;
                    break;
                case ACTION_REPLY_TO_CONVERSATION:
                    Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
                    if (remoteInput == null) {
                        break;
                    }
                    final CharSequence body = remoteInput.getCharSequence("text_reply");
                    final boolean dismissNotification = intent.getBooleanExtra("dismiss_notification", false);
                    if (body == null || body.length() <= 0) {
                        break;
                    }
                    mNotificationExecutor.execute(() -> {
                        try {
                            restoredFromDatabaseLatch.await();
                            final Conversation c = findConversationByUuid(uuid);
                            if (c != null) {
                                directReply(c, body.toString(), dismissNotification);
                            }
                        } catch (InterruptedException e) {
                            Log.d(Config.LOGTAG, "unable to process direct reply");
                        }
                    });
                    break;
                case ACTION_MARK_AS_READ:
                    mNotificationExecutor.execute(() -> {
                        final Conversation c = findConversationByUuid(uuid);
                        if (c == null) {
                            Log.d(Config.LOGTAG, "received mark read intent for unknown conversation (" + uuid + ")");
                            return;
                        }
                        try {
                            restoredFromDatabaseLatch.await();
                            sendReadMarker(c, null);
                        } catch (InterruptedException e) {
                            Log.d(Config.LOGTAG, "unable to process notification read marker for conversation " + c.getName());
                        }

                    });
                    break;
                case ACTION_SNOOZE:
                    mNotificationExecutor.execute(() -> {
                        final Conversation c = findConversationByUuid(uuid);
                        if (c == null) {
                            Log.d(Config.LOGTAG, "received snooze intent for unknown conversation (" + uuid + ")");
                            return;
                        }
                        c.setMutedTill(System.currentTimeMillis() + 30 * 60 * 1000);
                        mNotificationService.clear(c);
                        updateConversation(c);
                    });
                case AudioManager.RINGER_MODE_CHANGED_ACTION:
                case NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED:
                    if (dndOnSilentMode()) {
                        refreshAllPresences();
                    }
                    break;
                case Intent.ACTION_SCREEN_ON:
                    deactivateGracePeriod();
                case Intent.ACTION_SCREEN_OFF:
                    if (awayWhenScreenOff()) {
                        refreshAllPresences();
                    }
                    break;
                case ACTION_FCM_TOKEN_REFRESH:
                    refreshAllFcmTokens();
                    break;
                case ACTION_IDLE_PING:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        scheduleNextIdlePing();
                    }
                    break;
                case ACTION_FCM_MESSAGE_RECEIVED:
                    pushedAccountHash = intent.getStringExtra("account");
                    Log.d(Config.LOGTAG, "push message arrived in service. account=" + pushedAccountHash);
                    break;
                case Intent.ACTION_SEND:
                    Uri uri = intent.getData();
                    if (uri != null) {
                        Log.d(Config.LOGTAG, "received uri permission for " + uri.toString());
                    }
                    return START_STICKY;
            }
        }
        synchronized (this) {
            WakeLockHelper.acquire(wakeLock);
            boolean pingNow = ConnectivityManager.CONNECTIVITY_ACTION.equals(action);
            HashSet<Account> pingCandidates = new HashSet<>();
            for (Account account : accounts) {
                pingNow |= processAccountState(account,
                        interactive,
                        "ui".equals(action),
                        CryptoHelper.getAccountFingerprint(account, PhoneHelper.getAndroidId(this)).equals(pushedAccountHash),
                        pingCandidates);
            }
            if (pingNow) {
                for (Account account : pingCandidates) {
                    List<Conversation> conversations = getConversations();
                    for (Conversation conversation : conversations) {
                        if (conversation.getAccount() == account && !account.pendingConferenceJoins.contains(conversation)) {
                            resendFailedFileMessages(conversation);
                        }
                    }
                    final boolean lowTimeout = isInLowPingTimeoutMode(account);
                    account.getXmppConnection().sendPing();
                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + " send ping (action=" + action + ", lowTimeout=" + Boolean.toString(lowTimeout) + ")");
                    scheduleWakeUpCall(lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT, account.getUuid().hashCode());
                }
            }
            WakeLockHelper.release(wakeLock);
        }
        if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
            expireOldMessages();
        }
        return START_STICKY;
    }

    private boolean processAccountState(Account account, boolean interactive, boolean isUiAction, boolean isAccountPushed, HashSet<Account> pingCandidates) {
        storeNumberOfAccounts(this.getAccounts().size());
        boolean pingNow = false;
        if (account.getStatus().isAttemptReconnect()) {
            if (!hasInternetConnection()) {
                account.setStatus(Account.State.NO_INTERNET);
                if (statusListener != null) {
                    statusListener.onStatusChanged(account);
                }
            } else {
                if (account.getStatus() == Account.State.NO_INTERNET) {
                    account.setStatus(Account.State.OFFLINE);
                    if (statusListener != null) {
                        statusListener.onStatusChanged(account);
                    }
                }
                if (account.getStatus() == Account.State.ONLINE) {
                    synchronized (mLowPingTimeoutMode) {
                        long lastReceived = account.getXmppConnection().getLastPacketReceived();
                        long lastSent = account.getXmppConnection().getLastPingSent();
                        long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
                        long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
                        int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().asBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
                        long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
                        if (lastSent > lastReceived) {
                            if (pingTimeoutIn < 0) {
                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping timeout");
                                this.reconnectAccount(account, true, interactive);
                            } else {
                                int secs = (int) (pingTimeoutIn / 1000);
                                this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
                            }
                        } else {
                            pingCandidates.add(account);
                            if (isAccountPushed) {
                                pingNow = true;
                                if (mLowPingTimeoutMode.add(account.getJid().asBareJid())) {
                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": entering low ping timeout mode");
                                }
                            } else if (msToNextPing <= 0) {
                                pingNow = true;
                            } else {
                                this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
                                if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");

                                }
                            }
                        }
                    }
                } else if (account.getStatus() == Account.State.OFFLINE) {
                    reconnectAccount(account, true, interactive);
                } else if (account.getStatus() == Account.State.CONNECTING) {
                    long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
                    long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
                    long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
                    long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
                    if (timeout < 0) {
                        Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting (secondsSinceLast=" + secondsSinceLastConnect + ")");
                        account.getXmppConnection().resetAttemptCount(false);
                        reconnectAccount(account, true, interactive);
                    } else if (discoTimeout < 0) {
                        account.getXmppConnection().sendDiscoTimeout();
                        scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
                    } else {
                        scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
                    }
                } else {
                    if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
                        reconnectAccount(account, true, interactive);
                    }
                }
            }
        }
        return pingNow;
    }

    private void storeNumberOfAccounts(int accounts) {
        //write No of accounts to file
        final SharedPreferences.Editor editor = getPreferences().edit();
        Log.d(Config.LOGTAG, "Number of accounts is " + accounts);
        editor.putInt(SettingsActivity.NUMBER_OF_ACCOUNTS, accounts);
        editor.commit();
    }

    public boolean isDataSaverDisabled() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
            return !connectivityManager.isActiveNetworkMetered()
                    || connectivityManager.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
        } else {
            return true;
        }
    }

    private void directReply(Conversation conversation, String body, final boolean dismissAfterReply) {
        Message message = new Message(conversation, body, conversation.getNextEncryption());
        message.markUnread();
        if (message.getEncryption() == Message.ENCRYPTION_PGP) {
            getPgpEngine().encrypt(message, new UiCallback<Message>() {
                @Override
                public void success(Message message) {
                    message.setEncryption(Message.ENCRYPTION_DECRYPTED);
                    sendMessage(message);
                    if (dismissAfterReply) {
                        markRead((Conversation) message.getConversation(), true);
                    } else {
                        mNotificationService.pushFromDirectReply(message);
                    }
                }

                @Override
                public void error(int errorCode, Message object) {

                }

                @Override
                public void userInputRequried(PendingIntent pi, Message object) {

                }
            });
        } else {
            sendMessage(message);
            if (dismissAfterReply) {
                markRead(conversation, true);
            } else {
                mNotificationService.pushFromDirectReply(message);
            }
        }
    }

    private boolean dndOnSilentMode() {
        return getBooleanPreference(SettingsActivity.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
    }

    private boolean manuallyChangePresence() {
        return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
    }

    private boolean treatVibrateAsSilent() {
        return getBooleanPreference(SettingsActivity.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
    }

    private boolean awayWhenScreenOff() {
        return getBooleanPreference(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
    }

    private String getCompressPicturesPreference() {
        return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression));
    }

    public int getCompressImageResolutionPreference() {
        switch (getPreferences().getString("image_compression", getResources().getString(R.string.picture_compression))) {
            case "low":
                return 720;
            case "mid":
                return 1920;
            case "high":
                return 3840;
            default:
                return 3840;
        }
    }

    public int getCompressImageSizePreference() {
        switch (getPreferences().getString("image_compression", getResources().getString(R.string.picture_compression))) {
            case "low":
                return 209715; // 0.2 * 1024 * 1024 = 209715 (0.2 MiB)
            case "mid":
                return 524288; // 0.5 * 1024 * 1024 = 524288 (0.5 MiB)
            case "high":
                return 1048576; // 1 * 1024 * 1024 = 1048576 (1 MiB)
            default:
                return 524288;
        }
    }

    public int getCompressVideoResolutionPreference() {
        switch (getPreferences().getString("video_compression", getResources().getString(R.string.video_compression))) {
            case "low":
                return 144;
            case "mid":
                return 360;
            case "high":
                return 720;
            default:
                return 360;
        }
    }

    public int getCompressVideoBitratePreference() {
        switch (getPreferences().getString("video_compression", getResources().getString(R.string.video_compression))) {
            case "low":
                return 100000;
            case "mid":
                return 500000;
            case "high":
                return 2000000;
            default:
                return 500000;
        }
    }

    public boolean getAttachmentChoicePreference() {
        return getBooleanPreference(SettingsActivity.QUICK_SHARE_ATTACHMENT_CHOICE, R.bool.quick_share_attachment_choice);
    }

    private Presence.Status getTargetPresence() {
        if (dndOnSilentMode() && isPhoneSilenced()) {
            return Presence.Status.DND;
        } else if (awayWhenScreenOff() && !isInteractive()) {
            return Presence.Status.AWAY;
        } else {
            return Presence.Status.ONLINE;
        }
    }

    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    public boolean isInteractive() {
        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

        final boolean isScreenOn;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            isScreenOn = pm.isScreenOn();
        } else {
            isScreenOn = pm.isInteractive();
        }
        return isScreenOn;
    }

    private boolean isPhoneSilenced() {
        final boolean notificationDnd;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            final NotificationManager notificationManager = getSystemService(NotificationManager.class);
            final int filter = notificationManager == null ? NotificationManager.INTERRUPTION_FILTER_UNKNOWN : notificationManager.getCurrentInterruptionFilter();
            notificationDnd = filter >= NotificationManager.INTERRUPTION_FILTER_PRIORITY;
        } else {
            notificationDnd = false;
        }
        final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        final int ringerMode = audioManager == null ? AudioManager.RINGER_MODE_NORMAL : audioManager.getRingerMode();
        try {
            if (treatVibrateAsSilent()) {
                return notificationDnd || ringerMode != AudioManager.RINGER_MODE_NORMAL;
            } else {
                return notificationDnd || ringerMode == AudioManager.RINGER_MODE_SILENT;
            }
        } catch (Throwable throwable) {
            Log.d(Config.LOGTAG, "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
            return notificationDnd;
        }
    }

    private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
        Log.d(Config.LOGTAG, "resetting all attempt counts");
        for (Account account : accounts) {
            if (account.hasErrorStatus() || reallyAll) {
                final XmppConnection connection = account.getXmppConnection();
                if (connection != null) {
                    connection.resetAttemptCount(retryImmediately);
                }
            }
            if (account.setShowErrorNotification(true)) {
                databaseBackend.updateAccount(account);
            }
        }
        mNotificationService.updateErrorNotification();
    }

    private void dismissErrorNotifications() {
        for (final Account account : this.accounts) {
            if (account.hasErrorStatus()) {
                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": dismissing error notification");
                if (account.setShowErrorNotification(false)) {
                    databaseBackend.updateAccount(account);
                }
            }
        }
    }

    private void expireOldMessages() {
        expireOldMessages(false);
    }

    public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
        mLastExpiryRun.set(SystemClock.elapsedRealtime());
        mDatabaseWriterExecutor.execute(() -> {
            long timestamp = getAutomaticMessageDeletionDate();
            if (timestamp > 0) {
                databaseBackend.expireOldMessages(timestamp);
                synchronized (XmppConnectionService.this.conversations) {
                    for (Conversation conversation : XmppConnectionService.this.conversations) {
                        conversation.expireOldMessages(timestamp);
                        if (resetHasMessagesLeftOnServer) {
                            conversation.messagesLoaded.set(true);
                            conversation.setHasMessagesLeftOnServer(true);
                        }
                    }
                }
                updateConversationUi();
            }
        });
    }

    public boolean hasInternetConnection() {
        final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            final NetworkInfo activeNetwork = cm == null ? null : cm.getActiveNetworkInfo();
            return activeNetwork != null && (activeNetwork.isConnected() || activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET);
        } catch (RuntimeException e) {
            Log.d(Config.LOGTAG, "unable to check for internet connection", e);
            return true; //if internet connection can not be checked it is probably best to just try
        }
    }

    public boolean isWIFI() {
        final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            final NetworkInfo activeNetwork = cm == null ? null : cm.getActiveNetworkInfo();
            if (activeNetwork != null) { // connected to the internet
                if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                    return true;
                }
            }
        } catch (RuntimeException e) {
            Log.d(Config.LOGTAG, "unable to check for WIFI connection", e);
            return false;
        }
        return false;
    }

    public boolean isMobile() {
        final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            final NetworkInfo activeNetwork = cm == null ? null : cm.getActiveNetworkInfo();
            if (activeNetwork != null) { // connected to the internet
                if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                    if (!activeNetwork.isRoaming()) {
                        return true;
                    }
                }
            }
        } catch (RuntimeException e) {
            Log.d(Config.LOGTAG, "unable to check for mobile connection", e);
            return false;
        }
        return false;
    }

    public boolean isMobileRoaming() {
        final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            final NetworkInfo activeNetwork = cm == null ? null : cm.getActiveNetworkInfo();
            if (activeNetwork != null) { // connected to the internet
                if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                    if (activeNetwork.isRoaming()) {
                        return true;
                    }
                }
            }
        } catch (RuntimeException e) {
            Log.d(Config.LOGTAG, "unable to check for roaming connection", e);
            return false;
        }
        return false;
    }

    @SuppressLint("TrulyRandom")
    @Override
    public void onCreate() {
        OmemoSetting.load(this);
        ExceptionHelper.init(getApplicationContext());
        try {
            Security.insertProviderAt(Conscrypt.newProvider(), 1);
        } catch (Throwable throwable) {
            Log.e(Config.LOGTAG, "unable to initialize security provider", throwable);
        }
        Resolver.init(this);
        this.mRandom = new SecureRandom();
        updateMemorizingTrustmanager();
        if (Compatibility.runsTwentySix()) {
            mNotificationService.initializeChannels();
        }
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;
        this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(final String key, final Bitmap bitmap) {
                return bitmap.getByteCount() / 1024;
            }
        };
        if (mLastActivity == 0) {
            mLastActivity = getPreferences().getLong(SETTING_LAST_ACTIVITY_TS, System.currentTimeMillis());
        }

        Log.d(Config.LOGTAG, "initializing database...");
        this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
        Log.d(Config.LOGTAG, "restoring accounts...");
        this.accounts = databaseBackend.getAccounts();

        final SharedPreferences.Editor editor = getPreferences().edit();
        if (this.accounts.size() == 0 && Arrays.asList("Sony", "Sony Ericsson").contains(Build.MANUFACTURER)) {
            editor.putBoolean(SettingsActivity.SHOW_FOREGROUND_SERVICE, true);
            Log.d(Config.LOGTAG, Build.MANUFACTURER + " is on blacklist. enabling foreground service");
        }
        editor.putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts()).apply();
        editor.apply();
        restoreFromDatabase();

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            startContactObserver();
        }
        if (Compatibility.hasStoragePermission(this)) {
            Log.d(Config.LOGTAG, "starting file observer");
            new Thread(fileObserver::startWatching).start();
        }
        if (Config.supportOpenPgp()) {
            this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
                @Override
                public void onBound(IOpenPgpService2 service) {
                    for (Account account : accounts) {
                        final PgpDecryptionService pgp = account.getPgpDecryptionService();
                        if (pgp != null) {
                            pgp.continueDecryption(true);
                        }
                    }
                }

                @Override
                public void onError(Exception e) {
                }
            });
            this.pgpServiceConnection.bindToService();
        }

        this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Config.LOGTAG + ":Service");
        toggleForegroundService();
        updateUnreadCountBadge();
        toggleScreenEventReceiver();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            scheduleNextIdlePing();
            IntentFilter intentFilter = new IntentFilter();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            }
            intentFilter.addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED);
            registerReceiver(this.mInternalEventReceiver, intentFilter);
        }
        //start export log service every day at given time
        ScheduleAutomaticExport();
        // cancel scheduled exporter
        CancelAutomaticExport(false);
    }

    public void startContactObserver() {
        getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new ContentObserver(null) {
            @Override
            public void onChange(boolean selfChange) {
                super.onChange(selfChange);
                if (restoredFromDatabaseLatch.getCount() == 0) {
                    loadPhoneContacts();
                }
            }
        });
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (level >= TRIM_MEMORY_COMPLETE) {
            Log.d(Config.LOGTAG, "clear cache due to low memory");
            getBitmapCache().evictAll();
        }
    }

    @Override
    public void onDestroy() {
        try {
            unregisterReceiver(this.mInternalEventReceiver);
        } catch (IllegalArgumentException e) {
            //ignored
        }
        fileObserver.stopWatching();
        super.onDestroy();
        // cancel scheduled exporter
        CancelAutomaticExport(true);
    }

    public void restartFileObserver() {
        Log.d(Config.LOGTAG, "restarting file observer");
        new Thread(fileObserver::restartWatching).start();
    }

    public void toggleScreenEventReceiver() {
        if (awayWhenScreenOff() && !manuallyChangePresence()) {
            final IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            registerReceiver(this.mInternalScreenEventReceiver, filter);
        } else {
            try {
                unregisterReceiver(this.mInternalScreenEventReceiver);
            } catch (IllegalArgumentException e) {
                //ignored
            }
        }
    }

    public void toggleForegroundService() {
        final boolean status;
        if (mForceForegroundService.get() || (Compatibility.keepForegroundService(this)/* && hasEnabledAccounts()*/)) {
            startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
            status = true;
        } else {
            stopForeground(true);
            status = false;
        }
        mNotificationService.dismissForcedForegroundNotification(); //if the channel was changed the previous call might fail
        Log.d(Config.LOGTAG, "ForegroundService: " + (status ? "on" : "off"));
    }

    @Override
    public void onTaskRemoved(final Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mForceForegroundService.get()) {
            Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
        } else {
            this.logoutAndSave(false);
        }
    }

    private void logoutAndSave(boolean stop) {
        int activeAccounts = 0;
        for (final Account account : accounts) {
            if (account.getStatus() != Account.State.DISABLED) {
                databaseBackend.writeRoster(account.getRoster());
                activeAccounts++;
            }
            if (account.getXmppConnection() != null) {
                new Thread(() -> disconnect(account, false)).start();
            }
        }
        if (stop || activeAccounts == 0) {
            Log.d(Config.LOGTAG, "good bye");
            stopSelf();
        }
    }

    public void scheduleWakeUpCall(int seconds, int requestCode) {
        final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        if (alarmManager == null) {
            return;
        }
        final Intent intent = new Intent(this, EventReceiver.class);
        intent.setAction("ping");
        try {
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
        } catch (RuntimeException e) {
            Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
        } catch (Exception e) {
            Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void scheduleNextIdlePing() {
        final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        if (alarmManager == null) {
            return;
        }
        final Intent intent = new Intent(this, EventReceiver.class);
        intent.setAction(ACTION_IDLE_PING);
        try {
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
            alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
        } catch (RuntimeException e) {
            Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
        }
    }

    public XmppConnection createConnection(final Account account) {
        final XmppConnection connection = new XmppConnection(account, this);
        connection.setOnMessagePacketReceivedListener(this.mMessageParser);
        connection.setOnStatusChangedListener(this.statusListener);
        connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
        connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
        connection.setOnJinglePacketReceivedListener(this.jingleListener);
        connection.setOnBindListener(this.mOnBindListener);
        connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
        AxolotlService axolotlService = account.getAxolotlService();
        if (axolotlService != null) {
            connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
        }
        return connection;
    }

    public void sendChatState(Conversation conversation) {
        if (sendChatStates()) {
            MessagePacket packet = mMessageGenerator.generateChatState(conversation);
            sendMessagePacket(conversation.getAccount(), packet);
        }
    }

    private void sendFileMessage(final Message message, final boolean delay) {
        Log.d(Config.LOGTAG, "send file message");
        final Account account = message.getConversation().getAccount();
        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
                || message.getConversation().getMode() == Conversation.MODE_MULTI) {
            mHttpConnectionManager.createNewUploadConnection(message, delay);
        } else {
            mJingleConnectionManager.createNewConnection(message);
        }
    }

    public void sendMessage(final Message message) {
        sendMessage(message, false, false);
    }

    private void sendMessage(final Message message, final boolean resend, final boolean delay) {
        final Account account = message.getConversation().getAccount();
        if (account.setShowErrorNotification(true)) {
            databaseBackend.updateAccount(account);
            mNotificationService.updateErrorNotification();
        }
        final Conversation conversation = (Conversation) message.getConversation();
        account.deactivateGracePeriod();
        MessagePacket packet = null;
        final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
                || !Patches.BAD_MUC_REFLECTION.contains(account.getServerIdentity()))
                && !message.edited();
        boolean saveInDb = addToConversation;
        message.setStatus(Message.STATUS_WAITING);

        if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
            conversation.endOtrIfNeeded();
            conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
                    new Conversation.OnMessageFound() {
                        @Override
                        public void onMessageFound(Message message) {
                            markMessage(message, Message.STATUS_SEND_FAILED);
                        }
                    });
        }

        if (account.isOnlineAndConnected()) {
            switch (message.getEncryption()) {
                case Message.ENCRYPTION_NONE:
                    if (message.needsUploading()) {
                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
                                || conversation.getMode() == Conversation.MODE_MULTI
                                || message.fixCounterpart()) {
                            this.sendFileMessage(message, delay);
                        } else {
                            break;
                        }
                    } else {
                        packet = mMessageGenerator.generateChat(message);
                    }
                    break;
                case Message.ENCRYPTION_PGP:
                case Message.ENCRYPTION_DECRYPTED:
                    if (message.needsUploading()) {
                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
                                || conversation.getMode() == Conversation.MODE_MULTI
                                || message.fixCounterpart()) {
                            this.sendFileMessage(message, delay);
                        } else {
                            break;
                        }
                    } else {
                        packet = mMessageGenerator.generatePgpChat(message);
                    }
                    break;
                case Message.ENCRYPTION_OTR:
                    SessionImpl otrSession = conversation.getOtrSession();
                    if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
                        try {
                            message.setCounterpart(OtrJidHelper.fromSessionID(otrSession.getSessionID()));
                        } catch (IllegalArgumentException e) {
                            break;
                        }
                        if (message.needsUploading()) {
                            mJingleConnectionManager.createNewConnection(message);
                        } else {
                            packet = mMessageGenerator.generateOtrChat(message);
                        }
                    } else if (otrSession == null) {
                        if (message.fixCounterpart()) {
                            conversation.startOtrSession(message.getCounterpart().getResource(), true);
                        } else {
                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not fix counterpart for OTR message to contact " + message.getCounterpart());
                            break;
                        }
                    } else {
                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + " OTR session with " + message.getContact() + " is in wrong state: " + otrSession.getSessionStatus().toString());
                    }
                    break;
                case Message.ENCRYPTION_AXOLOTL:
                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
                    if (message.needsUploading()) {
                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
                                || conversation.getMode() == Conversation.MODE_MULTI
                                || message.fixCounterpart()) {
                            this.sendFileMessage(message, delay);
                        } else {
                            break;
                        }
                    } else {
                        XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
                        if (axolotlMessage == null) {
                            account.getAxolotlService().preparePayloadMessage(message, delay);
                        } else {
                            packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
                        }
                    }
                    break;

            }
            if (packet != null) {
                if (account.getXmppConnection().getFeatures().sm() || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
                    message.setStatus(Message.STATUS_UNSEND);
                } else {
                    message.setStatus(Message.STATUS_SEND);
                }
            }
        } else {
            switch (message.getEncryption()) {
                case Message.ENCRYPTION_DECRYPTED:
                    if (!message.needsUploading()) {
                        String pgpBody = message.getEncryptedBody();
                        String decryptedBody = message.getBody();
                        message.setBody(pgpBody); //TODO might throw NPE
                        message.setEncryption(Message.ENCRYPTION_PGP);
                        if (message.edited()) {
                            message.setBody(decryptedBody);
                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
                            databaseBackend.updateMessage(message, message.getEditedId());
                            updateConversationUi();
                            return;
                        } else {
                            databaseBackend.createMessage(message);
                            saveInDb = false;
                            message.setBody(decryptedBody);
                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
                        }
                    }
                    break;
                case Message.ENCRYPTION_OTR:
                    if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": create otr session without starting for " + message.getContact().getJid());
                        conversation.startOtrSession(message.getCounterpart().getResource(), false);
                    }
                    break;
                case Message.ENCRYPTION_AXOLOTL:
                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
                    break;
            }
        }

        boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && message.getType() != Message.TYPE_PRIVATE;
        if (mucMessage) {
            message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
        }

        if (resend) {
            if (packet != null && addToConversation) {
                if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
                    markMessage(message, Message.STATUS_UNSEND);
                } else {
                    markMessage(message, Message.STATUS_SEND);
                }
            }
        } else {
            if (addToConversation) {
                conversation.add(message);
            }
            if (saveInDb) {
                databaseBackend.createMessage(message);
            } else if (message.edited()) {
                databaseBackend.updateMessage(message, message.getEditedId());
            }
            updateConversationUi();
        }
        if (packet != null) {
            if (delay) {
                mMessageGenerator.addDelay(packet, message.getTimeSent());
            }
            if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
                if (this.sendChatStates()) {
                    packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
                }
            }
            sendMessagePacket(account, packet);
        }
    }

    private void sendUnsentMessages(final Conversation conversation) {
        conversation.findWaitingMessages(message -> resendMessage(message, true));
    }

    private void resendFailedFileMessages(final Conversation conversation) {
        conversation.findFailedMessagesWithFiles(new Conversation.OnMessageFound() {

            @Override
            public void onMessageFound(Message message) {
                if (mHttpConnectionManager.getAutoAcceptFileSize() >= message.getFileParams().size) {
                    Log.d(Config.LOGTAG, "Resend failed message with size " + message.getFileParams().size + " bytes for " + conversation.getJid());
                    resendMessage(message, true);
                }
            }
        });
    }

    public void resendMessage(final Message message, final boolean delay) {
        sendMessage(message, true, delay);
    }

    public void fetchRosterFromServer(final Account account) {
        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
        if (!"".equals(account.getRosterVersion())) {
            Log.d(Config.LOGTAG, account.getJid().asBareJid()
                    + ": fetching roster version " + account.getRosterVersion());
        } else {
            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
        }
        iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
        sendIqPacket(account, iqPacket, mIqParser);
    }

    public void fetchBookmarks(final Account account) {
        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
        final Element query = iqPacket.query("jabber:iq:private");
        query.addChild("storage", Namespace.BOOKMARKS);
        final OnIqPacketReceived callback = (a, response) -> {
            if (response.getType() == IqPacket.TYPE.RESULT) {
                final Element query1 = response.query();
                final Element storage = query1.findChild("storage", "storage:bookmarks");
                processBookmarks(a, storage);
            } else {
                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
            }
        };
        sendIqPacket(account, iqPacket, callback);
    }

    public void processBookmarks(Account account, Element storage) {
        final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
        final boolean autojoin = respectAutojoin();
        if (storage != null) {
            for (final Element item : storage.getChildren()) {
                if (item.getName().equals("conference")) {
                    final Bookmark bookmark = Bookmark.parse(item, account);
                    Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
                    if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
                        bookmark.setBookmarkName(old.getBookmarkName());
                    }
                    Conversation conversation = find(bookmark);
                    if (conversation != null) {
                        bookmark.setConversation(conversation);
                    } else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
                        conversation = findOrCreateConversation(account, bookmark.getJid(), true, true, false);
                        bookmark.setConversation(conversation);
                    }
                }
            }
        }
        account.setBookmarks(new CopyOnWriteArrayList<>(bookmarks.values()));
    }

    public void pushBookmarks(Account account) {
        if (account.getXmppConnection().getFeatures().bookmarksConversion()) {
            pushBookmarksPep(account);
        } else {
            pushBookmarksPrivateXml(account);
        }
    }

    private void pushBookmarksPrivateXml(Account account) {
        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
        IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
        Element query = iqPacket.query("jabber:iq:private");
        Element storage = query.addChild("storage", "storage:bookmarks");
        for (Bookmark bookmark : account.getBookmarks()) {
            storage.addChild(bookmark);
        }
        sendIqPacket(account, iqPacket, mDefaultIqHandler);
    }

    private void pushBookmarksPep(Account account) {
        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
        Element storage = new Element("storage", "storage:bookmarks");
        for (Bookmark bookmark : account.getBookmarks()) {
            storage.addChild(bookmark);
        }
        pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, PublishOptions.persistentWhitelistAccess());
    }

    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final Bundle options) {
        pushNodeAndEnforcePublishOptions(account, node, element, options, true);
    }

    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final Bundle options, final boolean retry) {
        IqPacket packet = mIqGenerator.publishElement(node, element, options);
        Log.d(Config.LOGTAG, packet.toString());
        sendIqPacket(account, packet, (a, response) -> {
            if (response.getType() == IqPacket.TYPE.RESULT) {
                return;
            }
            final Element error = response.getType() == IqPacket.TYPE.ERROR ? response.findChild("error") : null;
            final boolean preconditionNotMet = error != null && error.hasChild("precondition-not-met", Namespace.PUBSUB_ERROR);
            if (retry && preconditionNotMet) {
                pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
                    @Override
                    public void onPushSucceeded() {
                        pushNodeAndEnforcePublishOptions(account, node, element, options, false);
                    }

                    @Override
                    public void onPushFailed() {
                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
                    }
                });
            } else {
                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing bookmarks (retry=" + Boolean.toString(retry) + ") " + response);
            }
        });
    }

    private void restoreFromDatabase() {
        synchronized (this.conversations) {
            final Map<String, Account> accountLookupTable = new Hashtable<>();
            for (Account account : this.accounts) {
                accountLookupTable.put(account.getUuid(), account);
            }
            Log.d(Config.LOGTAG, "restoring conversations...");
            final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
            this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
            for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
                Conversation conversation = iterator.next();
                Account account = accountLookupTable.get(conversation.getAccountUuid());
                if (account != null) {
                    conversation.setAccount(account);
                } else {
                    Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
                    iterator.remove();
                }
            }
            long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
            Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
            Runnable runnable = () -> {
                long deletionDate = getAutomaticMessageDeletionDate();
                mLastExpiryRun.set(SystemClock.elapsedRealtime());
                if (deletionDate > 0) {
                    Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
                    databaseBackend.expireOldMessages(deletionDate);
                }
                Log.d(Config.LOGTAG, "restoring roster...");
                for (Account account : accounts) {
                    databaseBackend.readRoster(account.getRoster());
                    account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
                }
                getBitmapCache().evictAll();
                loadPhoneContacts();
                Log.d(Config.LOGTAG, "restoring messages...");
                final long startMessageRestore = SystemClock.elapsedRealtime();
                final Conversation quickLoad = QuickLoader.get(this.conversations);
                if (quickLoad != null) {
                    restoreMessages(quickLoad);
                    updateConversationUi();
                    final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
                    Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
                }
                for (Conversation conversation : this.conversations) {
                    if (quickLoad != conversation) {
                        restoreMessages(conversation);
                    }
                }
                mNotificationService.finishBacklog(false);
                restoredFromDatabaseLatch.countDown();
                final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
                Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
                updateConversationUi();
            };
            mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
        }
    }

    private void restoreMessages(Conversation conversation) {
        conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
        checkDeletedFiles(conversation);
        conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
        conversation.findUnreadMessages(message -> mNotificationService.pushFromBacklog(message));
    }

    public void loadPhoneContacts() {
        mContactMergerExecutor.execute(() -> {
            Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
            Log.d(Config.LOGTAG, "start merging phone contacts with roster");
            for (Account account : accounts) {
                List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
                for (JabberIdContact jidContact : contacts.values()) {
                    final Contact contact = account.getRoster().getContact(jidContact.getJid());
                    boolean needsCacheClean = contact.setPhoneContact(jidContact);
                    if (needsCacheClean) {
                        getAvatarService().clear(contact);
                    }
                    withSystemAccounts.remove(contact);
                }
                for (Contact contact : withSystemAccounts) {
                    boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
                    if (needsCacheClean) {
                        getAvatarService().clear(contact);
                    }
                }
            }
            Log.d(Config.LOGTAG, "finished merging phone contacts");
            mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
            updateRosterUi();
            mQuickConversationsService.considerSync();
        });
    }

    public void syncRoster(final Account account) {
        mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
    }

    public List<Conversation> getConversations() {
        return this.conversations;
    }

    private void checkDeletedFiles(Conversation conversation) {
        conversation.findMessagesWithFiles(message -> {
            if (!getFileBackend().isFileAvailable(message)) {
                message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
                final int s = message.getStatus();
                if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
                    markMessage(message, Message.STATUS_SEND_FAILED);
                }
            }
        });
    }

    private void markFileDeleted(final String path) {
        Log.d(Config.LOGTAG, "deleted file " + path);
        for (Conversation conversation : getConversations()) {
            conversation.findMessagesWithFiles(message -> {
                DownloadableFile file = fileBackend.getFile(message);
                if (file.getAbsolutePath().equals(path)) {
                    if (!file.exists()) {
                        message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
                        final int s = message.getStatus();
                        if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
                            markMessage(message, Message.STATUS_SEND_FAILED);
                        } else {
                            updateConversationUi();
                        }
                    } else {
                        Log.d(Config.LOGTAG, "found matching message for file " + path + " but file still exists");
                    }
                }
            });
        }
    }

    public void populateWithOrderedConversations(final List<Conversation> list) {
        populateWithOrderedConversations(list, true);
    }

    public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
        list.clear();
        if (includeNoFileUpload) {
            list.addAll(getConversations());
        } else {
            for (Conversation conversation : getConversations()) {
                if (conversation.getMode() == Conversation.MODE_SINGLE
                        || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
                    list.add(conversation);
                }
            }
        }
        try {
            Collections.sort(list);
        } catch (IllegalArgumentException e) {
            //ignore
        }
    }

    public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
        if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
            return;
        } else if (timestamp == 0) {
            return;
        }
        Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
        final Runnable runnable = () -> {
            final Account account = conversation.getAccount();
            List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
            if (messages.size() > 0) {
                conversation.addAll(0, messages);
                checkDeletedFiles(conversation);
                callback.onMoreMessagesLoaded(messages.size(), conversation);
            } else if (conversation.hasMessagesLeftOnServer()
                    && account.isOnlineAndConnected()
                    && conversation.getLastClearHistory().getTimestamp() == 0) {
                final boolean mamAvailable;
                if (conversation.getMode() == Conversation.MODE_SINGLE) {
                    mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
                } else {
                    mamAvailable = conversation.getMucOptions().mamSupport();
                }
                if (mamAvailable) {
                    MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
                    if (query != null) {
                        query.setCallback(callback);
                        callback.informUser(R.string.fetching_history_from_server);
                    } else {
                        callback.informUser(R.string.not_fetching_history_retention_period);
                    }
                }
            }
        };
        mDatabaseReaderExecutor.execute(runnable);
    }

    public List<Account> getAccounts() {
        return this.accounts;
    }

    public List<Conversation> findAllConferencesWith(Contact contact) {
        ArrayList<Conversation> results = new ArrayList<>();
        for (final Conversation c : conversations) {
            if (c.getMode() == Conversation.MODE_MULTI && c.getMucOptions().isContactInRoom(contact)) {
                results.add(c);
            }
        }
        return results;
    }

    public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
        for (final Conversation conversation : haystack) {
            if (conversation.getContact() == contact) {
                return conversation;
            }
        }
        return null;
    }

    public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
        if (jid == null) {
            return null;
        }
        for (final Conversation conversation : haystack) {
            if ((account == null || conversation.getAccount() == account)
                    && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
                return conversation;
            }
        }
        return null;
    }

    public boolean isConversationsListEmpty(final Conversation ignore) {
        synchronized (this.conversations) {
            final int size = this.conversations.size();
            return size == 0 || size == 1 && this.conversations.get(0) == ignore;
        }
    }

    public boolean isConversationStillOpen(final Conversation conversation) {
        synchronized (this.conversations) {
            for (Conversation current : this.conversations) {
                if (current == conversation) {
                    return true;
                }
            }
        }
        return false;
    }

    public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
        return this.findOrCreateConversation(account, jid, muc, false, async);
    }

    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
        return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
    }

    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
        synchronized (this.conversations) {
            Conversation conversation = find(account, jid);
            if (conversation != null) {
                return conversation;
            }
            conversation = databaseBackend.findConversation(account, jid);
            final boolean loadMessagesFromDb;
            if (conversation != null) {
                conversation.setStatus(Conversation.STATUS_AVAILABLE);
                conversation.setAccount(account);
                if (muc) {
                    conversation.setMode(Conversation.MODE_MULTI);
                    conversation.setContactJid(jid);
                } else {
                    conversation.setMode(Conversation.MODE_SINGLE);
                    conversation.setContactJid(jid.asBareJid());
                }
                databaseBackend.updateConversation(conversation);
                loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
            } else {
                String conversationName;
                Contact contact = account.getRoster().getContact(jid);
                if (contact != null) {
                    conversationName = contact.getDisplayName();
                } else {
                    conversationName = jid.getLocal();
                }
                if (muc) {
                    conversation = new Conversation(conversationName, account, jid,
                            Conversation.MODE_MULTI);
                } else {
                    conversation = new Conversation(conversationName, account, jid.asBareJid(),
                            Conversation.MODE_SINGLE);
                }
                this.databaseBackend.createConversation(conversation);
                loadMessagesFromDb = false;
            }
            final Conversation c = conversation;
            final Runnable runnable = () -> {
                if (loadMessagesFromDb) {
                    c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
                    updateConversationUi();
                    c.messagesLoaded.set(true);
                }
                if (account.getXmppConnection() != null
                        && !c.getContact().isBlocked()
                        && account.getXmppConnection().getFeatures().mam()
                        && !muc) {
                    if (query == null) {
                        mMessageArchiveService.query(c);
                    } else {
                        if (query.getConversation() == null) {
                            mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
                        }
                    }
                }
                checkDeletedFiles(c);
                if (joinAfterCreate) {
                    joinMuc(c);

                }
            };
            if (async) {
                mDatabaseReaderExecutor.execute(runnable);
            } else {
                runnable.run();
            }
            this.conversations.add(conversation);
            updateConversationUi();
            return conversation;
        }
    }

    public Conversation findConversation(final Account account, final Jid jid, final boolean muc) {
        synchronized (this.conversations) {
            Conversation conversation = find(account, jid);
            if (conversation != null) {
                return conversation;
            }
            conversation = databaseBackend.findConversation(account, jid);
            final boolean loadMessagesFromDb;
            if (conversation != null) {
                conversation.setStatus(Conversation.STATUS_AVAILABLE);
                conversation.setAccount(account);
                if (muc) {
                    conversation.setMode(Conversation.MODE_MULTI);
                    conversation.setContactJid(jid);
                } else {
                    conversation.setMode(Conversation.MODE_SINGLE);
                    conversation.setContactJid(jid.asBareJid());
                }
                databaseBackend.updateConversation(conversation);
                loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
            } else {
                String conversationName;
                Contact contact = account.getRoster().getContact(jid);
                if (contact != null) {
                    conversationName = contact.getDisplayName();
                } else {
                    conversationName = jid.getLocal();
                }
                if (muc) {
                    conversation = new Conversation(conversationName, account, jid,
                            Conversation.MODE_MULTI);
                } else {
                    conversation = new Conversation(conversationName, account, jid.asBareJid(),
                            Conversation.MODE_SINGLE);
                }
                this.databaseBackend.createConversation(conversation);
                loadMessagesFromDb = false;
            }
            final Conversation c = conversation;
            mDatabaseReaderExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    if (loadMessagesFromDb) {
                        c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
                        updateConversationUi();
                        c.messagesLoaded.set(true);
                    }
                    checkDeletedFiles(c);
                }
            });
            updateConversationUi();
            return conversation;
        }
    }

    public void archiveConversation(Conversation conversation) {
        getNotificationService().clear(conversation);
        conversation.setStatus(Conversation.STATUS_ARCHIVED);
        conversation.setNextMessage(null);
        synchronized (this.conversations) {
            getMessageArchiveService().kill(conversation);
            if (conversation.getMode() == Conversation.MODE_MULTI) {
                if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
                    Bookmark bookmark = conversation.getBookmark();
                    if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
                        bookmark.setAutojoin(false);
                        pushBookmarks(bookmark.getAccount());
                    }
                }
                leaveMuc(conversation);
            } else {
                conversation.endOtrIfNeeded();
                if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
                    Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
                    sendPresencePacket(
                            conversation.getAccount(),
                            mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
                    );
                }
            }
            updateConversation(conversation);
            this.conversations.remove(conversation);
            updateConversationUi();
        }
    }

    public void createAccount(final Account account) {
        account.initAccountServices(this);
        databaseBackend.createAccount(account);
        this.accounts.add(account);
        this.reconnectAccountInBackground(account);
        updateAccountUi();
        syncEnabledAccountSetting();
        toggleForegroundService();
    }

    private void syncEnabledAccountSetting() {
        getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts()).apply();
    }

    public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
        new Thread(() -> {
            try {
                final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
                final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
                if (cert == null) {
                    callback.informUser(R.string.unable_to_parse_certificate);
                    return;
                }
                Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
                if (info == null) {
                    callback.informUser(R.string.certificate_does_not_contain_jid);
                    return;
                }
                if (findAccountByJid(info.first) == null) {
                    Account account = new Account(info.first, "");
                    account.setPrivateKeyAlias(alias);
                    account.setOption(Account.OPTION_DISABLED, true);
                    account.setDisplayName(info.second);
                    createAccount(account);
                    callback.onAccountCreated(account);
                    if (Config.X509_VERIFICATION) {
                        try {
                            getMemorizingTrustManager().getNonInteractive(account.getJid().getDomain()).checkClientTrusted(chain, "RSA");
                        } catch (CertificateException e) {
                            callback.informUser(R.string.certificate_chain_is_not_trusted);
                        }
                    }
                } else {
                    callback.informUser(R.string.account_already_exists);
                }
            } catch (Exception e) {
                e.printStackTrace();
                callback.informUser(R.string.unable_to_parse_certificate);
            }
        }).start();
    }

    public void updateKeyInAccount(final Account account, final String alias) {
        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
        try {
            X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
            Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
            Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
            if (info == null) {
                showErrorToastInUi(R.string.certificate_does_not_contain_jid);
                return;
            }
            if (account.getJid().asBareJid().equals(info.first)) {
                account.setPrivateKeyAlias(alias);
                account.setDisplayName(info.second);
                databaseBackend.updateAccount(account);
                if (Config.X509_VERIFICATION) {
                    try {
                        getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
                    } catch (CertificateException e) {
                        showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
                    }
                    account.getAxolotlService().regenerateKeys(true);
                }
            } else {
                showErrorToastInUi(R.string.jid_does_not_match_certificate);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean updateAccount(final Account account) {
        if (databaseBackend.updateAccount(account)) {
            account.setShowErrorNotification(true);
            this.statusListener.onStatusChanged(account);
            databaseBackend.updateAccount(account);
            reconnectAccountInBackground(account);
            updateAccountUi();
            getNotificationService().updateErrorNotification();
            toggleForegroundService();
            syncEnabledAccountSetting();
            return true;
        } else {
            return false;
        }
    }

    public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
        final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
        sendIqPacket(account, iq, (a, packet) -> {
            if (packet.getType() == IqPacket.TYPE.RESULT) {
                a.setPassword(newPassword);
                a.setOption(Account.OPTION_MAGIC_CREATE, false);
                databaseBackend.updateAccount(a);
                callback.onPasswordChangeSucceeded();
            } else {
                callback.onPasswordChangeFailed();
            }
        });
    }

    public void deleteAccount(final Account account) {
        synchronized (this.conversations) {
            for (final Conversation conversation : conversations) {
                if (conversation.getAccount() == account) {
                    if (conversation.getMode() == Conversation.MODE_MULTI) {
                        leaveMuc(conversation);
                    } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
                        conversation.endOtrIfNeeded();
                    }
                    conversations.remove(conversation);
                }
            }
            if (account.getXmppConnection() != null) {
                new Thread(() -> disconnect(account, true)).start();
            }
            final Runnable runnable = () -> {
                if (!databaseBackend.deleteAccount(account)) {
                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
                }
            };
            mDatabaseWriterExecutor.execute(runnable);
            this.accounts.remove(account);
            this.mRosterSyncTaskManager.clear(account);
            updateAccountUi();
            getNotificationService().updateErrorNotification();
            syncEnabledAccountSetting();
            toggleForegroundService();
        }
    }

    public void setOnConversationListChangedListener(OnConversationUpdate listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            remainingListeners = checkListeners();
            if (!this.mOnConversationUpdates.add(listener)) {
                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
            }
            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
        }
        if (remainingListeners) {
            switchToForeground();
        }
    }

    public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            this.mOnConversationUpdates.remove(listener);
            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
            remainingListeners = checkListeners();
        }
        if (remainingListeners) {
            switchToBackground();
        }
    }

    public void setOnShowErrorToastListener(OnShowErrorToast listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            remainingListeners = checkListeners();
            if (!this.mOnShowErrorToasts.add(listener)) {
                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
            }
        }
        if (remainingListeners) {
            switchToForeground();
        }
    }

    public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            this.mOnShowErrorToasts.remove(onShowErrorToast);
            remainingListeners = checkListeners();
        }
        if (remainingListeners) {
            switchToBackground();
        }
    }

    public void setOnAccountListChangedListener(OnAccountUpdate listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            remainingListeners = checkListeners();
            if (!this.mOnAccountUpdates.add(listener)) {
                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
            }
        }
        if (remainingListeners) {
            switchToForeground();
        }
    }

    public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            this.mOnAccountUpdates.remove(listener);
            remainingListeners = checkListeners();
        }
        if (remainingListeners) {
            switchToBackground();
        }
    }

    public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            remainingListeners = checkListeners();
            if (!this.mOnCaptchaRequested.add(listener)) {
                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
            }
        }
        if (remainingListeners) {
            switchToForeground();
        }
    }

    public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            this.mOnCaptchaRequested.remove(listener);
            remainingListeners = checkListeners();
        }
        if (remainingListeners) {
            switchToBackground();
        }
    }

    public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            remainingListeners = checkListeners();
            if (!this.mOnRosterUpdates.add(listener)) {
                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
            }
        }
        if (remainingListeners) {
            switchToForeground();
        }
    }

    public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            this.mOnRosterUpdates.remove(listener);
            remainingListeners = checkListeners();
        }
        if (remainingListeners) {
            switchToBackground();
        }
    }

    public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            remainingListeners = checkListeners();
            if (!this.mOnUpdateBlocklist.add(listener)) {
                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
            }
        }
        if (remainingListeners) {
            switchToForeground();
        }
    }

    public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            this.mOnUpdateBlocklist.remove(listener);
            remainingListeners = checkListeners();
        }
        if (remainingListeners) {
            switchToBackground();
        }
    }

    public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            remainingListeners = checkListeners();
            if (!this.mOnKeyStatusUpdated.add(listener)) {
                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
            }
        }
        if (remainingListeners) {
            switchToForeground();
        }
    }

    public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            this.mOnKeyStatusUpdated.remove(listener);
            remainingListeners = checkListeners();
        }
        if (remainingListeners) {
            switchToBackground();
        }
    }

    public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            remainingListeners = checkListeners();
            if (!this.mOnMucRosterUpdate.add(listener)) {
                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
            }
        }
        if (remainingListeners) {
            switchToForeground();
        }
    }

    public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
        final boolean remainingListeners;
        synchronized (LISTENER_LOCK) {
            this.mOnMucRosterUpdate.remove(listener);
            remainingListeners = checkListeners();
        }
        if (remainingListeners) {
            switchToBackground();
        }
    }

    public boolean checkListeners() {
        return (this.mOnAccountUpdates.size() == 0
                && this.mOnConversationUpdates.size() == 0
                && this.mOnRosterUpdates.size() == 0
                && this.mOnCaptchaRequested.size() == 0
                && this.mOnMucRosterUpdate.size() == 0
                && this.mOnUpdateBlocklist.size() == 0
                && this.mOnShowErrorToasts.size() == 0
                && this.mOnKeyStatusUpdated.size() == 0);
    }

    private void switchToForeground() {
        final boolean broadcastLastActivity = broadcastLastActivity();
        for (Conversation conversation : getConversations()) {
            if (conversation.getMode() == Conversation.MODE_MULTI) {
                conversation.getMucOptions().resetChatState();
            } else {
                conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
            }
        }
        for (Account account : getAccounts()) {
            if (account.getStatus() == Account.State.ONLINE) {
                account.deactivateGracePeriod();
                final XmppConnection connection = account.getXmppConnection();
                if (connection != null) {
                    if (connection.getFeatures().csi()) {
                        connection.sendActive();
                    }
                    if (broadcastLastActivity) {
                        sendPresence(account, false); //send new presence but don't include idle because we are not
                    }
                }
            }
        }
        Log.d(Config.LOGTAG, "app switched into foreground");
    }

    private void switchToBackground() {
        final boolean broadcastLastActivity = broadcastLastActivity();
        if (broadcastLastActivity) {
            mLastActivity = System.currentTimeMillis();
            final SharedPreferences.Editor editor = getPreferences().edit();
            editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
            editor.apply();
        }
        for (Account account : getAccounts()) {
            if (account.getStatus() == Account.State.ONLINE) {
                XmppConnection connection = account.getXmppConnection();
                if (connection != null) {
                    if (broadcastLastActivity) {
                        sendPresence(account, broadcastLastActivity);
                    }
                    if (connection.getFeatures().csi()) {
                        connection.sendInactive();
                    }
                }
            }
        }
        Log.d(Config.LOGTAG, "XmppConnectionService switchToBackground(): setIsInForeground = false");
        this.mNotificationService.setIsInForeground(false);
        Log.d(Config.LOGTAG, "app switched into background");
    }

    private void connectMultiModeConversations(Account account) {
        List<Conversation> conversations = getConversations();
        for (Conversation conversation : conversations) {
            if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
                joinMuc(conversation);
            }
        }
    }

    public void joinMuc(Conversation conversation) {
        joinMuc(conversation, null, false);
    }

    public void joinMuc(Conversation conversation, boolean followedInvite) {
        joinMuc(conversation, null, followedInvite);
    }

    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
        joinMuc(conversation, onConferenceJoined, false);
    }

    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
        Account account = conversation.getAccount();
        account.pendingConferenceJoins.remove(conversation);
        account.pendingConferenceLeaves.remove(conversation);
        if (account.getStatus() == Account.State.ONLINE) {

            //disabled for testing strange MUC leaves
            sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));

            conversation.resetMucOptions();
            if (onConferenceJoined != null) {
                conversation.getMucOptions().flagNoAutoPushConfiguration();
            }
            conversation.setHasMessagesLeftOnServer(false);
            fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {

                private void join(Conversation conversation) {
                    Account account = conversation.getAccount();
                    final MucOptions mucOptions = conversation.getMucOptions();
                    final Jid joinJid = mucOptions.getSelf().getFullJid();
                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
                    PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
                    packet.setTo(joinJid);
                    Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
                    if (conversation.getMucOptions().getPassword() != null) {
                        x.addChild("password").setContent(mucOptions.getPassword());
                    }

                    if (mucOptions.mamSupport()) {
                        // Use MAM instead of the limited muc history to get history
                        x.addChild("history").setAttribute("maxchars", "0");
                    } else {
                        // Fallback to muc history
                        x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
                    }
                    sendPresencePacket(account, packet);
                    if (onConferenceJoined != null) {
                        onConferenceJoined.onConferenceJoined(conversation);
                    }
                    if (!joinJid.equals(conversation.getJid())) {
                        conversation.setContactJid(joinJid);
                        databaseBackend.updateConversation(conversation);
                    }

                    if (mucOptions.mamSupport()) {
                        getMessageArchiveService().catchupMUC(conversation);
                    }
                    if (mucOptions.isPrivateAndNonAnonymous()) {
                        fetchConferenceMembers(conversation);
                        if (followedInvite && conversation.getBookmark() == null) {
                            saveConversationAsBookmark(conversation, null);
                        }
                    }
                    sendUnsentMessages(conversation);
                }

                @Override
                public void onConferenceConfigurationFetched(Conversation conversation) {
                    join(conversation);
                }

                @Override
                public void onFetchFailed(final Conversation conversation, Element error) {
                    if (error != null && "remote-server-not-found".equals(error.getName())) {
                        conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
                        updateConversationUi();
                    } else {
                        join(conversation);
                        fetchConferenceConfiguration(conversation);
                    }
                }
            });
            updateConversationUi();
        } else {
            account.pendingConferenceJoins.add(conversation);
            conversation.resetMucOptions();
            conversation.setHasMessagesLeftOnServer(false);
            updateConversationUi();
        }
    }

    private void fetchConferenceMembers(final Conversation conversation) {
        final Account account = conversation.getAccount();
        final AxolotlService axolotlService = account.getAxolotlService();
        final String[] affiliations = {"member", "admin", "owner"};
        OnIqPacketReceived callback = new OnIqPacketReceived() {

            private int i = 0;
            private boolean success = true;

            @Override
            public void onIqPacketReceived(Account account, IqPacket packet) {
                final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
                Element query = packet.query("http://jabber.org/protocol/muc#admin");
                if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
                    for (Element child : query.getChildren()) {
                        if ("item".equals(child.getName())) {
                            MucOptions.User user = AbstractParser.parseItem(conversation, child);
                            if (!user.realJidMatchesAccount()) {
                                boolean isNew = conversation.getMucOptions().updateUser(user);
                                Contact contact = user.getContact();
                                if (omemoEnabled
                                        && isNew
                                        && user.getRealJid() != null
                                        && (contact == null || !contact.mutualPresenceSubscription())
                                        && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
                                    axolotlService.fetchDeviceIds(user.getRealJid());
                                }
                            }
                        }
                    }
                } else {
                    success = false;
                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
                }
                ++i;
                if (i >= affiliations.length) {
                    List<Jid> members = conversation.getMucOptions().getMembers(true);
                    if (success) {
                        List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
                        boolean changed = false;
                        for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
                            Jid jid = iterator.next();
                            if (!members.contains(jid) && !members.contains(Jid.ofDomain(jid.getDomain()))) {
                                try {
                                    iterator.remove();
                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
                                    changed = true;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        if (changed) {
                            conversation.setAcceptedCryptoTargets(cryptoTargets);
                            updateConversation(conversation);
                        }
                    }
                    getAvatarService().clear(conversation);
                    updateMucRosterUi();
                    updateConversationUi();
                }
            }
        };
        for (String affiliation : affiliations) {
            sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
        }
        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
    }

    public void providePasswordForMuc(Conversation conversation, String password) {
        if (conversation.getMode() == Conversation.MODE_MULTI) {
            conversation.getMucOptions().setPassword(password);
            if (conversation.getBookmark() != null) {
                if (respectAutojoin()) {
                    conversation.getBookmark().setAutojoin(true);
                }
                pushBookmarks(conversation.getAccount());
            }
            updateConversation(conversation);
            joinMuc(conversation);
        }
    }

    private boolean hasEnabledAccounts() {
        if (this.accounts == null) {
            return false; // set to false if accounts could not be fetched - used for notifications
        }
        for (Account account : this.accounts) {
            if (account.isEnabled()) {
                return true;
            }
        }
        return false;
    }

    public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
        getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
    }

    public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
        getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
    }

    public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
        new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
    }

    public void persistSelfNick(MucOptions.User self) {
        final Conversation conversation = self.getConversation();
        Jid full = self.getFullJid();
        if (!full.equals(conversation.getJid())) {
            Log.d(Config.LOGTAG, "nick changed. updating");
            conversation.setContactJid(full);
            databaseBackend.updateConversation(conversation);
        }

        Bookmark bookmark = conversation.getBookmark();
        if (bookmark != null && !full.getResource().equals(bookmark.getNick())) {
            bookmark.setNick(full.getResource());
            pushBookmarks(bookmark.getAccount());
        }
    }

    public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
        final MucOptions options = conversation.getMucOptions();
        final Jid joinJid = options.createJoinJid(nick);
        if (joinJid == null) {
            return false;
        }
        if (options.online()) {
            Account account = conversation.getAccount();
            options.setOnRenameListener(new OnRenameListener() {

                @Override
                public void onSuccess() {
                    callback.success(conversation);
                }

                @Override
                public void onFailure() {
                    callback.error(R.string.nick_in_use, conversation);
                }
            });

            PresencePacket packet = new PresencePacket();
            packet.setTo(joinJid);
            packet.setFrom(conversation.getAccount().getJid());

            String sig = account.getPgpSignature();
            if (sig != null) {
                packet.addChild("status").setContent("online");
                packet.addChild("x", "jabber:x:signed").setContent(sig);
            }
            sendPresencePacket(account, packet);
        } else {
            conversation.setContactJid(joinJid);
            databaseBackend.updateConversation(conversation);
            if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
                Bookmark bookmark = conversation.getBookmark();
                if (bookmark != null) {
                    bookmark.setNick(nick);
                    pushBookmarks(bookmark.getAccount());
                }
                joinMuc(conversation);
            }
        }
        return true;
    }

    public void leaveMuc(Conversation conversation) {
        leaveMuc(conversation, false);
    }

    private void leaveMuc(Conversation conversation, boolean now) {
        Account account = conversation.getAccount();
        account.pendingConferenceJoins.remove(conversation);
        account.pendingConferenceLeaves.remove(conversation);
        if (account.getStatus() == Account.State.ONLINE || now) {
            sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
            conversation.getMucOptions().setOffline();
            Bookmark bookmark = conversation.getBookmark();
            if (bookmark != null) {
                bookmark.setConversation(null);
            }
            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
        } else {
            account.pendingConferenceLeaves.add(conversation);
        }
    }

    public String findConferenceServer(final Account account) {
        String server;
        if (account.getXmppConnection() != null) {
            server = account.getXmppConnection().getMucServer();
            if (server != null) {
                return server;
            }
        }
        for (Account other : getAccounts()) {
            if (other != account && other.getXmppConnection() != null) {
                server = other.getXmppConnection().getMucServer();
                if (server != null) {
                    return server;
                }
            }
        }
        return null;
    }

    public boolean createAdhocConference(final Account account,
                                         final String name,
                                         final Iterable<Jid> jids,
                                         final UiCallback<Conversation> callback) {
        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
        if (account.getStatus() == Account.State.ONLINE) {
            try {
                String server = findConferenceServer(account);
                if (server == null) {
                    if (callback != null) {
                        callback.error(R.string.no_conference_server_found, null);
                    }
                    return false;
                }
                final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
                final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
                joinMuc(conversation, new OnConferenceJoined() {
                    @Override
                    public void onConferenceJoined(final Conversation conversation) {
                        final Bundle configuration = IqGenerator.defaultRoomConfiguration();
                        if (!TextUtils.isEmpty(name)) {
                            configuration.putString("muc#roomconfig_roomname", name);
                        }
                        pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
                            @Override
                            public void onPushSucceeded() {
                                for (Jid invite : jids) {
                                    invite(conversation, invite);
                                }
                                if (account.countPresences() > 1) {
                                    directInvite(conversation, account.getJid().asBareJid());
                                }
                                saveConversationAsBookmark(conversation, name);
                                if (callback != null) {
                                    callback.success(conversation);
                                }
                            }

                            @Override
                            public void onPushFailed() {
                                archiveConversation(conversation);
                                if (callback != null) {
                                    callback.error(R.string.conference_creation_failed, conversation);
                                }
                            }
                        });
                    }
                });
                return true;
            } catch (IllegalArgumentException e) {
                if (callback != null) {
                    callback.error(R.string.conference_creation_failed, null);
                }
                return false;
            }
        } else {
            if (callback != null) {
                callback.error(R.string.not_connected_try_again, null);
            }
            return false;
        }
    }

    public void fetchConferenceConfiguration(final Conversation conversation) {
        fetchConferenceConfiguration(conversation, null);
    }

    public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
        request.setTo(conversation.getJid().asBareJid());
        request.query("http://jabber.org/protocol/disco#info");
        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
            @Override
            public void onIqPacketReceived(Account account, IqPacket packet) {
                if (packet.getType() == IqPacket.TYPE.RESULT) {
                    final MucOptions mucOptions = conversation.getMucOptions();
                    final Bookmark bookmark = conversation.getBookmark();
                    final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());

                    if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
                        updateConversation(conversation);
                    }

                    if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
                        if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
                            pushBookmarks(account);
                        }
                    }

                    if (callback != null) {
                        callback.onConferenceConfigurationFetched(conversation);
                    }

                    updateConversationUi();
                } else if (packet.getType() == IqPacket.TYPE.ERROR) {
                    if (callback != null) {
                        callback.onFetchFailed(conversation, packet.getError());
                    }
                }
            }
        });
    }

    public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
        Log.d(Config.LOGTAG, "pushing node configuration");
        pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
    }

    public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
        sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
            @Override
            public void onIqPacketReceived(Account account, IqPacket packet) {
                if (packet.getType() == IqPacket.TYPE.RESULT) {
                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
                    Element configuration = pubsub == null ? null : pubsub.findChild("configure");
                    Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
                    if (x != null) {
                        Data data = Data.parse(x);
                        data.submit(options);
                        sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
                            @Override
                            public void onIqPacketReceived(Account account, IqPacket packet) {
                                if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
                                    callback.onPushSucceeded();
                                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
                                    callback.onPushFailed();
                                }
                            }
                        });
                    } else if (callback != null) {
                        callback.onPushFailed();
                    }
                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
                    callback.onPushFailed();
                }
            }
        });
    }

    public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
        request.setTo(conversation.getJid().asBareJid());
        request.query("http://jabber.org/protocol/muc#owner");
        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
            @Override
            public void onIqPacketReceived(Account account, IqPacket packet) {
                if (packet.getType() == IqPacket.TYPE.RESULT) {
                    Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
                    data.submit(options);
                    IqPacket set = new IqPacket(IqPacket.TYPE.SET);
                    set.setTo(conversation.getJid().asBareJid());
                    set.query("http://jabber.org/protocol/muc#owner").addChild(data);
                    sendIqPacket(account, set, new OnIqPacketReceived() {
                        @Override
                        public void onIqPacketReceived(Account account, IqPacket packet) {
                            if (callback != null) {
                                if (packet.getType() == IqPacket.TYPE.RESULT) {
                                    callback.onPushSucceeded();
                                } else {
                                    callback.onPushFailed();
                                }
                            }
                        }
                    });
                } else {
                    if (callback != null) {
                        callback.onPushFailed();
                    }
                }
            }
        });
    }

    public void pushSubjectToConference(final Conversation conference, final String subject) {
        MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
        this.sendMessagePacket(conference.getAccount(), packet);
    }

    public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
        final Jid jid = user.asBareJid();
        IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
        sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
            @Override
            public void onIqPacketReceived(Account account, IqPacket packet) {
                if (packet.getType() == IqPacket.TYPE.RESULT) {
                    conference.getMucOptions().changeAffiliation(jid, affiliation);
                    getAvatarService().clear(conference);
                    callback.onAffiliationChangedSuccessful(jid);
                } else {
                    callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
                }
            }
        });
    }

    public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
        List<Jid> jids = new ArrayList<>();
        for (MucOptions.User user : conference.getMucOptions().getUsers()) {
            if (user.getAffiliation() == before && user.getRealJid() != null) {
                jids.add(user.getRealJid());
            }
        }
        IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
        sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
    }

    public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
        IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
        Log.d(Config.LOGTAG, request.toString());
        sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
            @Override
            public void onIqPacketReceived(Account account, IqPacket packet) {
                Log.d(Config.LOGTAG, packet.toString());
                if (packet.getType() == IqPacket.TYPE.RESULT) {
                    callback.onRoleChangedSuccessful(nick);
                } else {
                    callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
                }
            }
        });
    }

    public void destroyMuc(final Conversation mSelectedConversation) {
        destroyConference(mSelectedConversation, new XmppConnectionService.OnDestroyMuc() {
            @Override
            public void OnDestroyMucSuccessful(int resId) {
                Log.d(Config.LOGTAG, "Destroy succeed");
                showErrorToastInUi(resId);
            }

            @Override
            public void OnDestroyMucFailed(int resId) {
                Log.d(Config.LOGTAG, "Destroy failed");
                showErrorToastInUi(resId);
            }
        });
    }

    public void destroyConference(final Conversation conference, final OnDestroyMuc callback) {
        IqPacket request = this.mIqGenerator.destroyConference(conference);
        sendIqPacket(conference.getAccount(), request, (account, packet) -> {
            if (packet.getType() == IqPacket.TYPE.RESULT) {
                callback.OnDestroyMucSuccessful(R.string.destroy_muc_succeed);
            } else {
                callback.OnDestroyMucFailed(R.string.destroy_muc_failed);
            }
        });
    }

    private void disconnect(Account account, boolean force) {
        if ((account.getStatus() == Account.State.ONLINE)
                || (account.getStatus() == Account.State.DISABLED)) {
            final XmppConnection connection = account.getXmppConnection();
            if (!force) {
                List<Conversation> conversations = getConversations();
                for (Conversation conversation : conversations) {
                    if (conversation.getAccount() == account) {
                        if (conversation.getMode() == Conversation.MODE_MULTI) {
                            leaveMuc(conversation, true);
                        } else {
                            if (conversation.endOtrIfNeeded()) {
                                Log.d(Config.LOGTAG, account.getJid().asBareJid()
                                        + ": ended otr session with "
                                        + conversation.getJid());
                            }
                        }
                    }
                }
                sendOfflinePresence(account);
            }
            connection.disconnect(force);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public void updateMessage(Message message) {
        updateMessage(message, true);
    }

    public void updateMessage(Message message, boolean includeBody) {
        databaseBackend.updateMessage(message, includeBody);
        updateConversationUi();
    }

    public void updateMessage(Message message, String uuid) {
        databaseBackend.updateMessage(message, uuid);
        updateConversationUi();
    }

    protected void syncDirtyContacts(Account account) {
        for (Contact contact : account.getRoster().getContacts()) {
            if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
                pushContactToServer(contact);
            }
            if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
                deleteContactOnServer(contact);
            }
        }
    }

    public void createContact(Contact contact, boolean autoGrant) {
        if (autoGrant) {
            contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
            contact.setOption(Contact.Options.ASKING);
        }
        pushContactToServer(contact);
    }

    public void onOtrSessionEstablished(Conversation conversation) {
        final Account account = conversation.getAccount();
        final Session otrSession = conversation.getOtrSession();
        Log.d(Config.LOGTAG,
                account.getJid().asBareJid() + " otr session established with "
                        + conversation.getJid() + "/"
                        + otrSession.getSessionID().getUserID());
        conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {

            @Override
            public void onMessageFound(Message message) {
                SessionID id = otrSession.getSessionID();
                try {
                    message.setCounterpart(Jid.of(id.getAccountID() + "/" + id.getUserID()));
                } catch (IllegalArgumentException e) {
                    return;
                }
                if (message.needsUploading()) {
                    mJingleConnectionManager.createNewConnection(message);
                } else {
                    MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
                    if (outPacket != null) {
                        mMessageGenerator.addDelay(outPacket, message.getTimeSent());
                        message.setStatus(Message.STATUS_SEND);
                        databaseBackend.updateMessage(message, false);
                        sendMessagePacket(account, outPacket);
                    }
                }
                updateConversationUi();
            }
        });
    }

    public boolean renewSymmetricKey(Conversation conversation) {
        Account account = conversation.getAccount();
        byte[] symmetricKey = new byte[32];
        this.mRandom.nextBytes(symmetricKey);
        Session otrSession = conversation.getOtrSession();
        if (otrSession != null) {
            MessagePacket packet = new MessagePacket();
            packet.setType(MessagePacket.TYPE_CHAT);
            packet.setFrom(account.getJid());
            MessageGenerator.addMessageHints(packet);
            packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
                    + otrSession.getSessionID().getUserID());
            try {
                packet.setBody(otrSession
                        .transformSending(CryptoHelper.FILETRANSFER
                                + CryptoHelper.bytesToHex(symmetricKey))[0]);
                sendMessagePacket(account, packet);
                conversation.setSymmetricKey(symmetricKey);
                return true;
            } catch (OtrException e) {
                return false;
            }
        }
        return false;
    }

    public void pushContactToServer(final Contact contact) {
        contact.resetOption(Contact.Options.DIRTY_DELETE);
        contact.setOption(Contact.Options.DIRTY_PUSH);
        final Account account = contact.getAccount();
        if (account.getStatus() == Account.State.ONLINE) {
            final boolean ask = contact.getOption(Contact.Options.ASKING);
            final boolean sendUpdates = contact
                    .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
                    && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
            final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
            iq.query(Namespace.ROSTER).addChild(contact.asElement());
            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
            if (sendUpdates) {
                sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
            }
            if (ask) {
                sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
            }
        } else {
            syncRoster(contact.getAccount());
        }
    }

    public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
        new Thread(() -> {
            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
            final int size = Config.AVATAR_SIZE;
            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
            if (avatar != null) {
                if (!getFileBackend().save(avatar)) {
                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
                    return;
                }
                avatar.owner = conversation.getJid().asBareJid();
                publishMucAvatar(conversation, avatar, callback);
            } else {
                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
            }
        }).start();
    }

    public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
        new Thread(() -> {
            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
            final int size = Config.AVATAR_SIZE;
            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
            if (avatar != null) {
                if (!getFileBackend().save(avatar)) {
                    Log.d(Config.LOGTAG, "unable to save vcard");
                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
                    return;
                }
                publishAvatar(account, avatar, callback);
            } else {
                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
            }
        }).start();
    }

    private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
        final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
        sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
            boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
            if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
                Element vcard = response.findChild("vCard", "vcard-temp");
                if (vcard == null) {
                    vcard = new Element("vCard", "vcard-temp");
                }
                Element photo = vcard.findChild("PHOTO");
                if (photo == null) {
                    photo = vcard.addChild("PHOTO");
                }
                photo.clearChildren();
                photo.addChild("TYPE").setContent(avatar.type);
                photo.addChild("BINVAL").setContent(avatar.image);
                IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
                publication.setTo(conversation.getJid().asBareJid());
                publication.addChild(vcard);
                sendIqPacket(account, publication, (a1, publicationResponse) -> {
                    if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
                        callback.onAvatarPublicationSucceeded();
                    } else {
                        Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
                    }
                });
            } else {
                Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
            }
        });
    }

    public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
        IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
        this.sendIqPacket(account, packet, new OnIqPacketReceived() {

            @Override
            public void onIqPacketReceived(Account account, IqPacket result) {
                if (result.getType() == IqPacket.TYPE.RESULT) {
                    final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
                    sendIqPacket(account, packet, new OnIqPacketReceived() {
                        @Override
                        public void onIqPacketReceived(Account account, IqPacket result) {
                            if (result.getType() == IqPacket.TYPE.RESULT) {
                                if (account.setAvatar(avatar.getFilename())) {
                                    getAvatarService().clear(account);
                                    databaseBackend.updateAccount(account);
                                }
                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
                                if (callback != null) {
                                    callback.onAvatarPublicationSucceeded();
                                }
                            } else {
                                if (callback != null) {
                                    callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
                                }
                            }
                        }
                    });
                } else {
                    Element error = result.findChild("error");
                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
                    if (callback != null) {
                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
                    }
                }
            }
        });
    }

    public void republishAvatarIfNeeded(Account account) {
        if (account.getAxolotlService().isPepBroken()) {
            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
            return;
        }
        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
        this.sendIqPacket(account, packet, new OnIqPacketReceived() {

            private Avatar parseAvatar(IqPacket packet) {
                Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
                if (pubsub != null) {
                    Element items = pubsub.findChild("items");
                    if (items != null) {
                        return Avatar.parseMetadata(items);
                    }
                }
                return null;
            }

            private boolean errorIsItemNotFound(IqPacket packet) {
                Element error = packet.findChild("error");
                return packet.getType() == IqPacket.TYPE.ERROR
                        && error != null
                        && error.hasChild("item-not-found");
            }

            @Override
            public void onIqPacketReceived(Account account, IqPacket packet) {
                if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
                    Avatar serverAvatar = parseAvatar(packet);
                    if (serverAvatar == null && account.getAvatar() != null) {
                        Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
                        if (avatar != null) {
                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
                            publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
                        } else {
                            Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
                        }
                    }
                }
            }
        });
    }

    public void fetchAvatar(Account account, Avatar avatar) {
        fetchAvatar(account, avatar, null);
    }

    public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
        final String KEY = generateFetchKey(account, avatar);
        synchronized (this.mInProgressAvatarFetches) {
            if (!this.mInProgressAvatarFetches.contains(KEY)) {
                switch (avatar.origin) {
                    case PEP:
                        this.mInProgressAvatarFetches.add(KEY);
                        fetchAvatarPep(account, avatar, callback);
                        break;
                    case VCARD:
                        this.mInProgressAvatarFetches.add(KEY);
                        fetchAvatarVcard(account, avatar, callback);
                        break;
                }
            }
        }
    }

    private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
        IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
        sendIqPacket(account, packet, (a, result) -> {
            synchronized (mInProgressAvatarFetches) {
                mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
            }
            final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
            if (result.getType() == IqPacket.TYPE.RESULT) {
                avatar.image = mIqParser.avatarData(result);
                if (avatar.image != null) {
                    if (getFileBackend().save(avatar)) {
                        if (a.getJid().asBareJid().equals(avatar.owner)) {
                            if (a.setAvatar(avatar.getFilename())) {
                                databaseBackend.updateAccount(a);
                            }
                            getAvatarService().clear(a);
                            updateConversationUi();
                            updateAccountUi();
                        } else {
                            Contact contact = a.getRoster().getContact(avatar.owner);
                            if (contact.setAvatar(avatar)) {
                                syncRoster(account);
                                getAvatarService().clear(contact);
                                updateConversationUi();
                                updateRosterUi();
                            }
                        }
                        if (callback != null) {
                            callback.success(avatar);
                        }
                        Log.d(Config.LOGTAG, a.getJid().asBareJid()
                                + ": successfully fetched pep avatar for " + avatar.owner);
                        return;
                    }
                } else {
                    Log.d(Config.LOGTAG, ERROR + "(parsing error)");
                }
            } else {
                Element error = result.findChild("error");
                if (error == null) {
                    Log.d(Config.LOGTAG, ERROR + "(server error)");
                } else {
                    Log.d(Config.LOGTAG, ERROR + error.toString());
                }
            }
            if (callback != null) {
                callback.error(0, null);
            }
        });
    }

    private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
        IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
            @Override
            public void onIqPacketReceived(Account account, IqPacket packet) {
                synchronized (mInProgressAvatarFetches) {
                    mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
                }
                if (packet.getType() == IqPacket.TYPE.RESULT) {
                    Element vCard = packet.findChild("vCard", "vcard-temp");
                    Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
                    String image = photo != null ? photo.findChildContent("BINVAL") : null;
                    if (image != null) {
                        avatar.image = image;
                        if (getFileBackend().save(avatar)) {
                            Log.d(Config.LOGTAG, account.getJid().asBareJid()
                                    + ": successfully fetched vCard avatar for " + avatar.owner);
                            if (avatar.owner.isBareJid()) {
                                if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
                                    account.setAvatar(avatar.getFilename());
                                    databaseBackend.updateAccount(account);
                                    getAvatarService().clear(account);
                                    updateAccountUi();
                                } else {
                                    Contact contact = account.getRoster().getContact(avatar.owner);
                                    if (contact.setAvatar(avatar)) {
                                        syncRoster(account);
                                        getAvatarService().clear(contact);
                                        updateRosterUi();
                                    }
                                }
                                updateConversationUi();
                            } else {
                                Conversation conversation = find(account, avatar.owner.asBareJid());
                                if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
                                    MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
                                    if (user != null) {
                                        if (user.setAvatar(avatar)) {
                                            getAvatarService().clear(user);
                                            updateConversationUi();
                                            updateMucRosterUi();
                                        }
                                        if (user.getRealJid() != null) {
                                            Contact contact = account.getRoster().getContact(user.getRealJid());
                                            if (contact.setAvatar(avatar)) {
                                                syncRoster(account);
                                                getAvatarService().clear(contact);
                                                updateRosterUi();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
        this.sendIqPacket(account, packet, new OnIqPacketReceived() {

            @Override
            public void onIqPacketReceived(Account account, IqPacket packet) {
                if (packet.getType() == IqPacket.TYPE.RESULT) {
                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
                    if (pubsub != null) {
                        Element items = pubsub.findChild("items");
                        if (items != null) {
                            Avatar avatar = Avatar.parseMetadata(items);
                            if (avatar != null) {
                                avatar.owner = account.getJid().asBareJid();
                                if (fileBackend.isAvatarCached(avatar)) {
                                    if (account.setAvatar(avatar.getFilename())) {
                                        databaseBackend.updateAccount(account);
                                    }
                                    getAvatarService().clear(account);
                                    callback.success(avatar);
                                } else {
                                    fetchAvatarPep(account, avatar, callback);
                                }
                                return;
                            }
                        }
                    }
                }
                callback.error(0, null);
            }
        });
    }

    public void deleteContactOnServer(Contact contact) {
        contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
        contact.resetOption(Contact.Options.DIRTY_PUSH);
        contact.setOption(Contact.Options.DIRTY_DELETE);
        Account account = contact.getAccount();
        if (account.getStatus() == Account.State.ONLINE) {
            IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
            Element item = iq.query(Namespace.ROSTER).addChild("item");
            item.setAttribute("jid", contact.getJid().toString());
            item.setAttribute("subscription", "remove");
            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
        }
    }

    public void updateConversation(final Conversation conversation) {
        mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
    }

    private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
        synchronized (account) {
            XmppConnection connection = account.getXmppConnection();
            if (connection == null) {
                connection = createConnection(account);
                account.setXmppConnection(connection);
            }
            boolean hasInternet = hasInternetConnection();
            if (account.isEnabled() && hasInternet) {
                if (!force) {
                    disconnect(account, false);
                }
                Thread thread = new Thread(connection);
                connection.setInteractive(interactive);
                connection.prepareNewConnection();
                connection.interrupt();
                thread.start();
                scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
            } else {
                disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
                account.getRoster().clearPresences();
                connection.resetEverything();
                final AxolotlService axolotlService = account.getAxolotlService();
                if (axolotlService != null) {
                    axolotlService.resetBrokenness();
                }
                if (!hasInternet) {
                    account.setStatus(Account.State.NO_INTERNET);
                }
            }
        }
    }

    public void reconnectAccountInBackground(final Account account) {
        new Thread(() -> reconnectAccount(account, false, true)).start();
    }

    public void invite(Conversation conversation, Jid contact) {
        Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
        MessagePacket packet = mMessageGenerator.invite(conversation, contact);
        sendMessagePacket(conversation.getAccount(), packet);
    }

    public void directInvite(Conversation conversation, Jid jid) {
        MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
        sendMessagePacket(conversation.getAccount(), packet);
    }

    public void resetSendingToWaiting(Account account) {
        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": reset 'sending' messages to 'waiting'");
        for (Conversation conversation : getConversations()) {
            if (conversation.getAccount() == account) {
                conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
            }
        }
    }

    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
        return markMessage(account, recipient, uuid, status, null);
    }

    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
        if (uuid == null) {
            return null;
        }
        for (Conversation conversation : getConversations()) {
            if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
                final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
                if (message != null) {
                    markMessage(message, status, errorMessage);
                }
                return message;
            }
        }
        return null;
    }

    public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
        if (uuid == null) {
            return false;
        } else {
            Message message = conversation.findSentMessageWithUuid(uuid);
            if (message != null) {
                if (message.getServerMsgId() == null) {
                    message.setServerMsgId(serverMessageId);
                }
                markMessage(message, status);
                return true;
            } else {
                return false;
            }
        }
    }

    public void markMessage(Message message, int status) {
        markMessage(message, status, null);
    }

    public void markMessage(Message message, int status, String errorMessage) {
        final int c = message.getStatus();
        if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
            return;
        }
        if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
            return;
        }
        message.setErrorMessage(errorMessage);
        message.setStatus(status);
        databaseBackend.updateMessage(message, false);
        updateConversationUi();
    }

    public SharedPreferences getPreferences() {
        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    }

    public long getAutomaticMessageDeletionDate() {
        final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
        return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
    }

    public long getLongPreference(String name, @IntegerRes int res) {
        long defaultValue = getResources().getInteger(res);
        try {
            return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    public boolean getBooleanPreference(String name, @BoolRes int res) {
        return getPreferences().getBoolean(name, getResources().getBoolean(res));
    }

    public boolean confirmMessages() {
        return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
    }

    public boolean allowMessageCorrection() {
        return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
    }

    public boolean sendChatStates() {
        return getBooleanPreference("chat_states", R.bool.chat_states);
    }

    private boolean respectAutojoin() {
        return getBooleanPreference("autojoin", R.bool.autojoin);
    }

    public boolean indicateReceived() {
        return getBooleanPreference("indicate_received", R.bool.indicate_received);
    }

    public boolean useTorToConnect() {
        return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
    }

    public boolean showExtendedConnectionOptions() {
        return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
    }

    public boolean warnUnecryptedChat() {
        return getBooleanPreference(SettingsActivity.WARN_UNENCRYPTED_CHAT, R.bool.warn_unencrypted_chat);
    }

    public boolean broadcastLastActivity() {
        return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
    }

    public boolean multipleAccounts() {
        return getBooleanPreference("enable_multi_accounts", R.bool.enable_multi_accounts);
    }

    public int unreadCount() {
        int count = 0;
        for (Conversation conversation : getConversations()) {
            count += conversation.unreadCount();
        }
        return count;
    }

    public void vibrate() {
        Log.d(Config.LOGTAG, "Notification: short vibrate");
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(100);
    }

    private <T> List<T> threadSafeList(Set<T> set) {
        synchronized (LISTENER_LOCK) {
            return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
        }
    }

    public void showErrorToastInUi(int resId) {
        for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
            listener.onShowErrorToast(resId);
        }
    }

    public void updateConversationUi() {
        for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
            listener.onConversationUpdate();
        }
    }

    public void updateAccountUi() {
        for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
            listener.onAccountUpdate();
        }
    }

    public void updateRosterUi() {
        for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
            listener.onRosterUpdate();
        }
    }

    public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
        if (mOnCaptchaRequested.size() > 0) {
            DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
            Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
                    (int) (captcha.getHeight() * metrics.scaledDensity), false);
            for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
                listener.onCaptchaRequested(account, id, data, scaled);
            }
            return true;
        }
        return false;
    }

    public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
        for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
            listener.OnUpdateBlocklist(status);
        }
    }

    public void updateMucRosterUi() {
        for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
            listener.onMucRosterUpdate();
        }
    }

    public void keyStatusUpdated(AxolotlService.FetchStatus report) {
        for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
            listener.onKeyStatusUpdated(report);
        }
    }

    public Account findAccountByJid(final Jid accountJid) {
        for (Account account : this.accounts) {
            if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
                return account;
            }
        }
        return null;
    }

    public Account findAccountByUuid(final String uuid) {
        for (Account account : this.accounts) {
            if (account.getUuid().equals(uuid)) {
                return account;
            }
        }
        return null;
    }

    public Conversation findConversationByUuid(String uuid) {
        for (Conversation conversation : getConversations()) {
            if (conversation.getUuid().equals(uuid)) {
                return conversation;
            }
        }
        return null;
    }

    public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
        List<Conversation> findings = new ArrayList<>();
        for (Conversation c : getConversations()) {
            if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
                findings.add(c);
            }
        }
        return findings.size() == 1 ? findings.get(0) : null;
    }

    public boolean markRead(final Conversation conversation, boolean dismiss) {
        return markRead(conversation, null, dismiss).size() > 0;
    }

    public void markRead(final Conversation conversation) {
        markRead(conversation, null, true);
    }

    public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
        if (dismiss) {
            mNotificationService.clear(conversation);
        }
        final List<Message> readMessages = conversation.markRead(upToUuid);
        if (readMessages.size() > 0) {
            Runnable runnable = () -> {
                for (Message message : readMessages) {
                    databaseBackend.updateMessage(message, false);
                }
            };
            mDatabaseWriterExecutor.execute(runnable);
            updateUnreadCountBadge();
            return readMessages;
        } else {
            return readMessages;
        }
    }

    public synchronized void updateUnreadCountBadge() {
        new Thread(() -> {
            int count = unreadCount();
            if (unreadCount != count) {
                Log.d(Config.LOGTAG, "update unread count to " + count);
                if (count > 0) {
                    ShortcutBadger.applyCount(getApplicationContext(), count);
                } else {
                    ShortcutBadger.removeCount(getApplicationContext());
                }
                unreadCount = count;
            }
        }).start();
    }

    public void sendReadMarker(final Conversation conversation, String upToUuid) {
        final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
        final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
        if (readMessages.size() > 0) {
            updateConversationUi();
        }
        final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
        if (confirmMessages()
                && markable != null
                && (markable.trusted() || isPrivateAndNonAnonymousMuc)
                && markable.getRemoteMsgId() != null) {
            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
            Account account = conversation.getAccount();
            final Jid to = markable.getCounterpart();
            final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
            MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
            this.sendMessagePacket(conversation.getAccount(), packet);
        }
    }

    public SecureRandom getRNG() {
        return this.mRandom;
    }

    public MemorizingTrustManager getMemorizingTrustManager() {
        return this.mMemorizingTrustManager;
    }

    public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
        this.mMemorizingTrustManager = trustManager;
    }

    public void updateMemorizingTrustmanager() {
        final MemorizingTrustManager tm;
        final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
        if (dontTrustSystemCAs) {
            tm = new MemorizingTrustManager(getApplicationContext(), null);
        } else {
            tm = new MemorizingTrustManager(getApplicationContext());
        }
        setMemorizingTrustManager(tm);
    }

    public LruCache<String, Bitmap> getBitmapCache() {
        return this.mBitmapCache;
    }

    public void syncRosterToDisk(final Account account) {
        Runnable runnable = () -> databaseBackend.writeRoster(account.getRoster());
        mDatabaseWriterExecutor.execute(runnable);
    }

    public Collection<String> getKnownHosts() {
        final Set<String> hosts = new HashSet<>();
        for (final Account account : getAccounts()) {
            hosts.add(account.getServer());
            for (final Contact contact : account.getRoster().getContacts()) {
                if (contact.showInRoster()) {
                    final String server = contact.getServer();
                    if (server != null && !hosts.contains(server)) {
                        hosts.add(server);
                    }
                }
            }
        }
        if (Config.DOMAIN_LOCK != null) {
            hosts.add(Config.DOMAIN_LOCK);
        }
        if (Config.MAGIC_CREATE_DOMAIN != null) {
            hosts.add(Config.MAGIC_CREATE_DOMAIN);
        }
        return hosts;
    }

    public Collection<String> getKnownConferenceHosts() {
        final Set<String> mucServers = new HashSet<>();
        for (final Account account : accounts) {
            if (account.getXmppConnection() != null) {
                mucServers.addAll(account.getXmppConnection().getMucServers());
                for (Bookmark bookmark : account.getBookmarks()) {
                    final Jid jid = bookmark.getJid();
                    final String s = jid == null ? null : jid.getDomain();
                    if (s != null) {
                        mucServers.add(s);
                    }
                }
            }
        }
        return mucServers;
    }

    public void sendMessagePacket(Account account, MessagePacket packet) {
        XmppConnection connection = account.getXmppConnection();
        if (connection != null) {
            connection.sendMessagePacket(packet);
        }
    }

    public void sendPresencePacket(Account account, PresencePacket packet) {
        XmppConnection connection = account.getXmppConnection();
        if (connection != null) {
            connection.sendPresencePacket(packet);
        }
    }

    public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
        final XmppConnection connection = account.getXmppConnection();
        if (connection != null) {
            IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
            connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
        }
    }

    public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
        final XmppConnection connection = account.getXmppConnection();
        if (connection != null) {
            connection.sendIqPacket(packet, callback);
        } else if (callback != null) {
            callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
        }
    }

    public void sendPresence(final Account account) {
        sendPresence(account, checkListeners() && broadcastLastActivity());
    }

    public void sendPresence(final Account account, final boolean includeIdleTimestamp) {
        Presence.Status status;
        if (manuallyChangePresence()) {
            status = account.getPresenceStatus();
        } else {
            status = getTargetPresence();
        }
        PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
        String message = account.getPresenceStatusMessage();
        if (message != null && !message.isEmpty()) {
            packet.addChild(new Element("status").setContent(message));
        }
        if (mLastActivity > 0 && includeIdleTimestamp) {
            long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
            packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
        }
        sendPresencePacket(account, packet);
    }

    private void deactivateGracePeriod() {
        for (Account account : getAccounts()) {
            account.deactivateGracePeriod();
        }
    }

    public void refreshAllPresences() {
        boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
        for (Account account : getAccounts()) {
            if (account.isEnabled()) {
                sendPresence(account, includeIdleTimestamp);
            }
        }
    }

    private void refreshAllFcmTokens() {
        for (Account account : getAccounts()) {
            if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
                mPushManagementService.registerPushTokenOnServer(account);
            }
        }
    }

    private void sendOfflinePresence(final Account account) {
        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
        sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
    }

    public MessageGenerator getMessageGenerator() {
        return this.mMessageGenerator;
    }

    public PresenceGenerator getPresenceGenerator() {
        return this.mPresenceGenerator;
    }

    public IqGenerator getIqGenerator() {
        return this.mIqGenerator;
    }

    public IqParser getIqParser() {
        return this.mIqParser;
    }

    public JingleConnectionManager getJingleConnectionManager() {
        return this.mJingleConnectionManager;
    }

    public MessageArchiveService getMessageArchiveService() {
        return this.mMessageArchiveService;
    }

    public QuickConversationsService getQuickConversationsService() {
        return this.mQuickConversationsService;
    }

    public List<Contact> findContacts(Jid jid, String accountJid) {
        ArrayList<Contact> contacts = new ArrayList<>();
        for (Account account : getAccounts()) {
            if ((account.isEnabled() || accountJid != null)
                    && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
                Contact contact = account.getRoster().getContactFromRoster(jid);
                if (contact != null) {
                    contacts.add(contact);
                }
            }
        }
        return contacts;
    }

    public Conversation findFirstMuc(Jid jid) {
        for (Conversation conversation : getConversations()) {
            if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
                return conversation;
            }
        }
        return null;
    }

    public NotificationService getNotificationService() {
        return this.mNotificationService;
    }

    public HttpConnectionManager getHttpConnectionManager() {
        return this.mHttpConnectionManager;
    }

    public void resendFailedMessages(final Message message) {
        final Collection<Message> messages = new ArrayList<>();
        Message current = message;
        while (current.getStatus() == Message.STATUS_SEND_FAILED) {
            messages.add(current);
            if (current.mergeable(current.next())) {
                current = current.next();
            } else {
                break;
            }
        }
        for (final Message msg : messages) {
            msg.setTime(System.currentTimeMillis());
            markMessage(msg, Message.STATUS_WAITING);
            this.resendMessage(msg, false);
        }
        if (message.getConversation() instanceof Conversation) {
            ((Conversation) message.getConversation()).sort();
        }
        updateConversationUi();
    }

    public void deleteMessage(final Conversation conversation, Message message) {
        conversation.deleteMessage(message);
        Runnable runnable = () -> {
            databaseBackend.deleteMessageInConversation(message);
            databaseBackend.updateConversation(conversation);

        };
        mDatabaseWriterExecutor.execute(runnable);
    }

    public void clearConversationHistory(final Conversation conversation) {
        final long clearDate;
        final String reference;
        if (conversation.countMessages() > 0) {
            Message latestMessage = conversation.getLatestMessage();
            clearDate = latestMessage.getTimeSent() + 1000;
            reference = latestMessage.getServerMsgId();
        } else {
            clearDate = System.currentTimeMillis();
            reference = null;
        }
        conversation.clearMessages();
        conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
        conversation.setLastClearHistory(clearDate, reference);
        Runnable runnable = () -> {
            databaseBackend.deleteMessagesInConversation(conversation);
            databaseBackend.updateConversation(conversation);

        };
        mDatabaseWriterExecutor.execute(runnable);
    }

    public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
        if (blockable != null && blockable.getBlockedJid() != null) {
            final Jid jid = blockable.getBlockedJid();
            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {

                @Override
                public void onIqPacketReceived(final Account account, final IqPacket packet) {
                    if (packet.getType() == IqPacket.TYPE.RESULT) {
                        account.getBlocklist().add(jid);
                        updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
                    }
                }
            });
            if (removeBlockedConversations(blockable.getAccount(), jid)) {
                updateConversationUi();
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
        boolean removed = false;
        synchronized (this.conversations) {
            boolean domainJid = blockedJid.getLocal() == null;
            for (Conversation conversation : this.conversations) {
                boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
                        || blockedJid.equals(conversation.getJid().asBareJid());
                if (conversation.getAccount() == account
                        && conversation.getMode() == Conversation.MODE_SINGLE
                        && jidMatches) {
                    this.conversations.remove(conversation);
                    markRead(conversation);
                    conversation.setStatus(Conversation.STATUS_ARCHIVED);
                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
                    updateConversation(conversation);
                    removed = true;
                }
            }
        }
        return removed;
    }

    public void sendUnblockRequest(final Blockable blockable) {
        if (blockable != null && blockable.getJid() != null) {
            final Jid jid = blockable.getBlockedJid();
            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
                @Override
                public void onIqPacketReceived(final Account account, final IqPacket packet) {
                    if (packet.getType() == IqPacket.TYPE.RESULT) {
                        account.getBlocklist().remove(jid);
                        updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
                    }
                }
            });
        }
    }

    public void publishDisplayName(Account account) {
        String displayName = account.getDisplayName();
        if (displayName != null && !displayName.isEmpty()) {
            IqPacket publish = mIqGenerator.publishNick(displayName);
            sendIqPacket(account, publish, (account1, packet) -> {
                if (packet.getType() == IqPacket.TYPE.ERROR) {
                    Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": could not publish nick");
                }
            });
        }
    }

    public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
        ServiceDiscoveryResult result = discoCache.get(key);
        if (result != null) {
            return result;
        } else {
            result = databaseBackend.findDiscoveryResult(key.first, key.second);
            if (result != null) {
                discoCache.put(key, result);
            }
            return result;
        }
    }

    public void fetchCaps(Account account, final Jid jid, final Presence presence) {
        final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
        ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
        if (disco != null) {
            presence.setServiceDiscoveryResult(disco);
        } else {
            if (!account.inProgressDiscoFetches.contains(key)) {
                account.inProgressDiscoFetches.add(key);
                IqPacket request = new IqPacket(IqPacket.TYPE.GET);
                request.setTo(jid);
                final String node = presence.getNode();
                final String ver = presence.getVer();
                final Element query = request.query("http://jabber.org/protocol/disco#info");
                if (node != null && ver != null) {
                    query.setAttribute("node", node + "#" + ver);
                }
                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
                sendIqPacket(account, request, (a, response) -> {
                    if (response.getType() == IqPacket.TYPE.RESULT) {
                        ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
                        if (presence.getVer().equals(discoveryResult.getVer())) {
                            databaseBackend.insertDiscoveryResult(discoveryResult);
                            injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
                        } else {
                            Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
                        }
                    }
                    a.inProgressDiscoFetches.remove(key);
                });
            }
        }
    }

    private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
        for (Contact contact : roster.getContacts()) {
            for (Presence presence : contact.getPresences().getPresences().values()) {
                if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
                    presence.setServiceDiscoveryResult(disco);
                }
            }
        }
    }

    public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
        final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
        request.addChild("prefs", version.namespace);
        sendIqPacket(account, request, (account1, packet) -> {
            Element prefs = packet.findChild("prefs", version.namespace);
            if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
                callback.onPreferencesFetched(prefs);
            } else {
                callback.onPreferencesFetchFailed();
            }
        });
    }

    public PushManagementService getPushManagementService() {
        return mPushManagementService;
    }

    public void changeStatus(Account account, PresenceTemplate template, String signature) {
        if (!template.getStatusMessage().isEmpty()) {
            databaseBackend.insertPresenceTemplate(template);
        }
        account.setPgpSignature(signature);
        account.setPresenceStatus(template.getStatus());
        account.setPresenceStatusMessage(template.getStatusMessage());
        databaseBackend.updateAccount(account);
        sendPresence(account);
    }

    public List<PresenceTemplate> getPresenceTemplates(Account account) {
        List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
        for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
            if (!templates.contains(template)) {
                templates.add(0, template);
            }
        }
        return templates;
    }

    public void saveConversationAsBookmark(Conversation conversation, String name) {
        Account account = conversation.getAccount();
        Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
        if (!conversation.getJid().isBareJid()) {
            bookmark.setNick(conversation.getJid().getResource());
        }
        if (!TextUtils.isEmpty(name)) {
            bookmark.setBookmarkName(name);
        }
        bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
        account.getBookmarks().add(bookmark);
        pushBookmarks(account);
        bookmark.setConversation(conversation);
    }

    public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
        boolean needsRosterWrite = false;
        boolean performedVerification = false;
        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
        for (XmppUri.Fingerprint fp : fingerprints) {
            if (fp.type == XmppUri.FingerprintType.OTR) {
                performedVerification |= contact.addOtrFingerprint(fp.fingerprint);
                needsRosterWrite |= performedVerification;
            } else if (fp.type == XmppUri.FingerprintType.OMEMO) {
                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
                if (fingerprintStatus != null) {
                    if (!fingerprintStatus.isVerified()) {
                        performedVerification = true;
                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
                    }
                } else {
                    axolotlService.preVerifyFingerprint(contact, fingerprint);
                }
            }
        }
        if (needsRosterWrite) {
            syncRosterToDisk(contact.getAccount());
        }
        return performedVerification;
    }

    public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
        final AxolotlService axolotlService = account.getAxolotlService();
        boolean verifiedSomething = false;
        for (XmppUri.Fingerprint fp : fingerprints) {
            if (fp.type == XmppUri.FingerprintType.OMEMO) {
                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
                Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
                if (fingerprintStatus != null) {
                    if (!fingerprintStatus.isVerified()) {
                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
                        verifiedSomething = true;
                    }
                } else {
                    axolotlService.preVerifyFingerprint(account, fingerprint);
                    verifiedSomething = true;
                }
            }
        }
        return verifiedSomething;
    }

    public boolean blindTrustBeforeVerification() {
        return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
    }

    public void ScheduleAutomaticExport() {
        //start export log service every day at given time
        if (Config.ExportLogs) {
            if (Config.ExportLogs_Hour >= 0 && Config.ExportLogs_Hour <= 23 && Config.ExportLogs_Minute >= 0 && Config.ExportLogs_Minute <= 59) {
                Calendar now = Calendar.getInstance();
                now.setTimeInMillis(System.currentTimeMillis());
                Calendar timetoexport = Calendar.getInstance();
                timetoexport.setTimeInMillis(System.currentTimeMillis());
                Intent intent = new Intent(this, AlarmReceiver.class);
                intent.setAction("exportlogs");
                Log.d(Config.LOGTAG, "Schedule automatic export logs at " + Config.ExportLogs_Hour + ":" + Config.ExportLogs_Minute);
                timetoexport.set(Calendar.HOUR_OF_DAY, Config.ExportLogs_Hour);
                timetoexport.set(Calendar.MINUTE, Config.ExportLogs_Minute);
                if (timetoexport.before(now)) {
                    SimpleDateFormat newDate = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
                    timetoexport.add(Calendar.DAY_OF_YEAR, 1); //DATE or DAY_OF_MONTH
                    Log.d(Config.LOGTAG, "Schedule automatic export logs, for today, the export time is in the past, scheduling first export run for the next day (" + newDate.format(timetoexport.getTimeInMillis()) + ").");
                }
                final PendingIntent ScheduleExportIntent = PendingIntent.getBroadcast(this, AlarmReceiver.SCHEDULE_ALARM_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                ((AlarmManager) getSystemService(ALARM_SERVICE)).setInexactRepeating(AlarmManager.RTC_WAKEUP, timetoexport.getTimeInMillis(), AlarmManager.INTERVAL_DAY, ScheduleExportIntent);
            }
        }
    }

    public void CancelAutomaticExport(boolean force) {
        if (!Config.ExportLogs || force) {
            Log.d(Config.LOGTAG, "Cancel scheduled automatic export");
            Intent intent = new Intent(this, AlarmReceiver.class);
            final PendingIntent ScheduleExportIntent = PendingIntent.getBroadcast(this, AlarmReceiver.SCHEDULE_ALARM_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            ((AlarmManager) this.getSystemService(ALARM_SERVICE)).cancel(ScheduleExportIntent);
        }
    }

    public String installedFrom() {
        final PackageManager packageManager = this.getPackageManager();
        final String packageID = BuildConfig.APPLICATION_ID;
        final String installedFrom = packageManager.getInstallerPackageName(packageID);
        Log.d(Config.LOGTAG, "Messenger installed from " + installedFrom);
        if (installedFrom != null) {
            return installedFrom;
        } else {
            return null;
        }
    }

    public ShortcutService getShortcutService() {
        return mShortcutService;
    }

    public void pushMamPreferences(Account account, Element prefs) {
        IqPacket set = new IqPacket(IqPacket.TYPE.SET);
        set.addChild(prefs);
        sendIqPacket(account, set, null);
    }

    public interface OnMamPreferencesFetched {
        void onPreferencesFetched(Element prefs);

        void onPreferencesFetchFailed();
    }

    public interface OnAccountCreated {
        void onAccountCreated(Account account);

        void informUser(int r);
    }

    public interface OnMoreMessagesLoaded {
        void onMoreMessagesLoaded(int count, Conversation conversation);

        void informUser(int r);
    }

    public interface OnAccountPasswordChanged {
        void onPasswordChangeSucceeded();

        void onPasswordChangeFailed();
    }

    public interface OnAffiliationChanged {
        void onAffiliationChangedSuccessful(Jid jid);

        void onAffiliationChangeFailed(Jid jid, int resId);
    }

    public interface OnRoleChanged {
        void onRoleChangedSuccessful(String nick);

        void onRoleChangeFailed(String nick, int resid);
    }

    public interface OnDestroyMuc {
        void OnDestroyMucSuccessful(int resId);

        void OnDestroyMucFailed(int resId);
    }

    public interface OnConversationUpdate {
        void onConversationUpdate();
    }

    public interface OnAccountUpdate {
        void onAccountUpdate();
    }

    public interface OnCaptchaRequested {
        void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
    }

    public interface OnRosterUpdate {
        void onRosterUpdate();
    }

    public interface OnMucRosterUpdate {
        void onMucRosterUpdate();
    }

    public interface OnConferenceConfigurationFetched {
        void onConferenceConfigurationFetched(Conversation conversation);

        void onFetchFailed(Conversation conversation, Element error);
    }

    public interface OnConferenceJoined {
        void onConferenceJoined(Conversation conversation);
    }

    public interface OnConfigurationPushed {
        void onPushSucceeded();

        void onPushFailed();
    }

    public interface OnShowErrorToast {
        void onShowErrorToast(int resId);
    }

    public class XmppConnectionBinder extends Binder {
        public XmppConnectionService getService() {
            return XmppConnectionService.this;
        }
    }

    private class InternalEventReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            onStartCommand(intent, 0, 0);
        }
    }
}