summaryrefslogtreecommitdiff
path: root/TelepathyQt/account.cpp
blob: 52025a4cfa63cfc82b3d81d9f19213e30ec1f187 (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
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
/**
 * This file is part of TelepathyQt
 *
 * @copyright Copyright (C) 2008-2012 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2008 Nokia Corporation
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt/Account>

#include "TelepathyQt/_gen/account.moc.hpp"
#include "TelepathyQt/_gen/cli-account.moc.hpp"
#include "TelepathyQt/_gen/cli-account-body.hpp"

#include "TelepathyQt/debug-internal.h"

#include "TelepathyQt/connection-internal.h"

#include <TelepathyQt/AccountManager>
#include <TelepathyQt/Channel>
#include <TelepathyQt/ChannelDispatcherInterface>
#include <TelepathyQt/ConnectionCapabilities>
#include <TelepathyQt/ConnectionLowlevel>
#include <TelepathyQt/ConnectionManager>
#include <TelepathyQt/PendingChannel>
#include <TelepathyQt/PendingChannelRequest>
#include <TelepathyQt/PendingFailure>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/PendingStringList>
#include <TelepathyQt/PendingVariant>
#include <TelepathyQt/PendingVoid>
#include <TelepathyQt/Profile>
#include <TelepathyQt/ReferencedHandles>
#include <TelepathyQt/Constants>
#include <TelepathyQt/Debug>

#include <QQueue>
#include <QRegExp>
#include <QSharedPointer>
#include <QTimer>
#include <QPointer>

#include <string.h>

namespace Tp
{

namespace
{

struct PresenceStatusInfo
{
    QString name;
    Tp::SimpleStatusSpec spec;
};

Tp::ConnectionPresenceType presenceTypeForStatus(const QString &status, bool &maySetOnSelf)
{
    static PresenceStatusInfo statuses[] = {
        { QLatin1String("available"), { Tp::ConnectionPresenceTypeAvailable, true, true } },
        { QLatin1String("chat"), { Tp::ConnectionPresenceTypeAvailable, true, true } },
        { QLatin1String("chatty"), { Tp::ConnectionPresenceTypeAvailable, true, true } },
        { QLatin1String("away"), { Tp::ConnectionPresenceTypeAway, true, true } },
        { QLatin1String("brb"), { Tp::ConnectionPresenceTypeAway, true, true } },
        { QLatin1String("out-to-lunch"), { Tp::ConnectionPresenceTypeAway, true, true } },
        { QLatin1String("xa"), { Tp::ConnectionPresenceTypeExtendedAway, true, true } },
        { QLatin1String("hidden"), { Tp::ConnectionPresenceTypeHidden, true, true } },
        { QLatin1String("invisible"), { Tp::ConnectionPresenceTypeHidden, true, true } },
        { QLatin1String("offline"), { Tp::ConnectionPresenceTypeOffline, true, false } },
        { QLatin1String("unknown"), { Tp::ConnectionPresenceTypeUnknown, false, false } },
        { QLatin1String("error"), { Tp::ConnectionPresenceTypeError, false, false } }
    };

    for (uint i = 0; i < sizeof(statuses) / sizeof(PresenceStatusInfo); ++i) {
        if (status == statuses[i].name) {
            maySetOnSelf = statuses[i].spec.maySetOnSelf;
            return (Tp::ConnectionPresenceType) statuses[i].spec.type;
        }
    }

    // fallback to type away if we don't know status
    maySetOnSelf = true;
    return Tp::ConnectionPresenceTypeAway;
}

Tp::PresenceSpec presenceSpecForStatus(const QString &status, bool canHaveStatusMessage)
{
    Tp::SimpleStatusSpec spec;
    spec.type = presenceTypeForStatus(status, spec.maySetOnSelf);
    spec.canHaveMessage = canHaveStatusMessage;
    return Tp::PresenceSpec(status, spec);
}

QVariantMap textChatCommonRequest()
{
    QVariantMap request;
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                   TP_QT_IFACE_CHANNEL_TYPE_TEXT);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                   (uint) Tp::HandleTypeContact);
    return request;
}

QVariantMap textChatRequest(const QString &contactIdentifier)
{
    QVariantMap request = textChatCommonRequest();
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"),
                   contactIdentifier);
    return request;
}

QVariantMap textChatRequest(const Tp::ContactPtr &contact)
{
    QVariantMap request = textChatCommonRequest();
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle"),
                   contact ? contact->handle().at(0) : (uint) 0);
    return request;
}

QVariantMap textChatroomRequest(const QString &roomName)
{
    QVariantMap request;
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                   TP_QT_IFACE_CHANNEL_TYPE_TEXT);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                   (uint) Tp::HandleTypeRoom);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"),
                   roomName);
    return request;
}

QVariantMap callCommonRequest(bool withAudio, const QString &audioName,
        bool withVideo, const QString &videoName)
{
    QVariantMap request;
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                   TP_QT_IFACE_CHANNEL_TYPE_CALL);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                   (uint) Tp::HandleTypeContact);

    if (withAudio) {
        request.insert(TP_QT_IFACE_CHANNEL_TYPE_CALL + QLatin1String(".InitialAudio"),
                       true);
        if (!audioName.isEmpty()) {
            request.insert(TP_QT_IFACE_CHANNEL_TYPE_CALL + QLatin1String(".InitialAudioName"),
                           audioName);
        }
    }

    if (withVideo) {
        request.insert(TP_QT_IFACE_CHANNEL_TYPE_CALL + QLatin1String(".InitialVideo"),
                       true);
        if (!videoName.isEmpty()) {
            request.insert(TP_QT_IFACE_CHANNEL_TYPE_CALL + QLatin1String(".InitialVideoName"),
                           videoName);
        }
    }

    return request;
}

QVariantMap audioCallRequest(const QString &contactIdentifier, const QString &contentName)
{
    QVariantMap request = callCommonRequest(true, contentName, false, QString());
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"),
                   contactIdentifier);
    return request;
}

QVariantMap audioCallRequest(const Tp::ContactPtr &contact, const QString &contentName)
{
    QVariantMap request = callCommonRequest(true, contentName, false, QString());
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle"),
                   contact ? contact->handle().at(0) : (uint) 0);
    return request;
}

QVariantMap videoCallRequest(const QString &contactIdentifier, const QString &contentName)
{
    QVariantMap request = callCommonRequest(false, QString(), true, contentName);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"),
                   contactIdentifier);
    return request;
}

QVariantMap videoCallRequest(const Tp::ContactPtr &contact, const QString &contentName)
{
    QVariantMap request = callCommonRequest(false, QString(), true, contentName);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle"),
                   contact ? contact->handle().at(0) : (uint) 0);
    return request;
}

QVariantMap audioVideoCallRequest(const QString &contactIdentifier,
        const QString &audioName,
        const QString &videoName)
{
    QVariantMap request = callCommonRequest(true, audioName, true, videoName);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"),
                   contactIdentifier);
    return request;
}

QVariantMap audioVideoCallRequest(const Tp::ContactPtr &contact,
        const QString &audioName,
        const QString &videoName)
{
    QVariantMap request = callCommonRequest(true, audioName, true, videoName);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle"),
                   contact ? contact->handle().at(0) : (uint) 0);
    return request;
}

QVariantMap streamedMediaCallCommonRequest()
{
    QVariantMap request;
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                   TP_QT_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                   (uint) Tp::HandleTypeContact);
    return request;
}

QVariantMap streamedMediaCallRequest(const QString &contactIdentifier)
{
    QVariantMap request = streamedMediaCallCommonRequest();
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"),
                   contactIdentifier);
    return request;
}

QVariantMap streamedMediaCallRequest(const Tp::ContactPtr &contact)
{
    QVariantMap request = streamedMediaCallCommonRequest();
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle"),
                   contact ? contact->handle().at(0) : (uint) 0);
    return request;
}

QVariantMap streamedMediaAudioCallRequest(const QString &contactIdentifier)
{
    QVariantMap request = streamedMediaCallRequest(contactIdentifier);
    request.insert(TP_QT_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialAudio"),
                   true);
    return request;
}

QVariantMap streamedMediaAudioCallRequest(const Tp::ContactPtr &contact)
{
    QVariantMap request = streamedMediaCallRequest(contact);
    request.insert(TP_QT_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialAudio"),
                   true);
    return request;
}

QVariantMap streamedMediaVideoCallRequest(const QString &contactIdentifier, bool withAudio)
{
    QVariantMap request = streamedMediaCallRequest(contactIdentifier);
    request.insert(TP_QT_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialVideo"),
                   true);
    if (withAudio) {
        request.insert(TP_QT_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialAudio"),
                       true);
    }
    return request;
}

QVariantMap streamedMediaVideoCallRequest(const Tp::ContactPtr &contact, bool withAudio)
{
    QVariantMap request = streamedMediaCallRequest(contact);
    request.insert(TP_QT_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialVideo"),
                   true);
    if (withAudio) {
        request.insert(TP_QT_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialAudio"),
                       true);
    }
    return request;
}

QVariantMap fileTransferCommonRequest(const Tp::FileTransferChannelCreationProperties &properties)
{
    if (!properties.isValid()) {
        warning() << "Invalid file transfer creation properties";
        return QVariantMap();
    }

    QVariantMap request;
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                   TP_QT_IFACE_CHANNEL_TYPE_FILE_TRANSFER);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                   (uint) Tp::HandleTypeContact);

    request.insert(TP_QT_IFACE_CHANNEL_TYPE_FILE_TRANSFER + QLatin1String(".Filename"),
                   properties.suggestedFileName());
    request.insert(TP_QT_IFACE_CHANNEL_TYPE_FILE_TRANSFER + QLatin1String(".ContentType"),
                   properties.contentType());
    request.insert(TP_QT_IFACE_CHANNEL_TYPE_FILE_TRANSFER + QLatin1String(".Size"),
                   properties.size());

    if (properties.hasContentHash()) {
        request.insert(TP_QT_IFACE_CHANNEL_TYPE_FILE_TRANSFER + QLatin1String(".ContentHashType"),
                       (uint) properties.contentHashType());
        request.insert(TP_QT_IFACE_CHANNEL_TYPE_FILE_TRANSFER + QLatin1String(".ContentHash"),
                       properties.contentHash());
    }

    if (properties.hasDescription()) {
        request.insert(TP_QT_IFACE_CHANNEL_TYPE_FILE_TRANSFER + QLatin1String(".Description"),
                       properties.description());
    }

    if (properties.hasLastModificationTime()) {
        request.insert(TP_QT_IFACE_CHANNEL_TYPE_FILE_TRANSFER + QLatin1String(".Date"),
                       (qulonglong) properties.lastModificationTime().toTime_t());
    }

    if (properties.hasUri()) {
        request.insert(TP_QT_IFACE_CHANNEL_TYPE_FILE_TRANSFER + QLatin1String(".URI"),
                       properties.uri());
    }

    return request;
}

QVariantMap fileTransferRequest(const QString &contactIdentifier,
        const Tp::FileTransferChannelCreationProperties &properties)
{
    QVariantMap request = fileTransferCommonRequest(properties);

    if  (!request.isEmpty()) {
        request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"),
                       contactIdentifier);
    }

    return request;
}

QVariantMap fileTransferRequest(const Tp::ContactPtr &contact,
        const Tp::FileTransferChannelCreationProperties &properties)
{
    QVariantMap request = fileTransferCommonRequest(properties);

    if  (!request.isEmpty()) {
        request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle"),
                       contact ? contact->handle().at(0) : (uint) 0);
    }

    return request;
}

QVariantMap streamTubeCommonRequest(const QString &service)
{
    QVariantMap request;
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                   TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                   (uint) Tp::HandleTypeContact);
    request.insert(TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE + QLatin1String(".Service"),
                   service);
    return request;
}

QVariantMap streamTubeRequest(const QString &contactIdentifier, const QString &service)
{
    QVariantMap request = streamTubeCommonRequest(service);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"),
                   contactIdentifier);
    return request;
}

QVariantMap streamTubeRequest(const Tp::ContactPtr &contact, const QString &service)
{
    QVariantMap request = streamTubeCommonRequest(service);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle"),
                   contact ? contact->handle().at(0) : (uint) 0);
    return request;
}

QVariantMap dbusTubeCommonRequest(const QString &serviceName)
{
    QVariantMap request;
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                   TP_QT_IFACE_CHANNEL_TYPE_DBUS_TUBE);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                   (uint) Tp::HandleTypeContact);
    request.insert(TP_QT_IFACE_CHANNEL_TYPE_DBUS_TUBE + QLatin1String(".ServiceName"),
                   serviceName);
    return request;
}

QVariantMap dbusTubeRequest(const QString &contactIdentifier, const QString &serviceName)
{
    QVariantMap request = dbusTubeCommonRequest(serviceName);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"),
                   contactIdentifier);
    return request;
}

QVariantMap dbusTubeRequest(const Tp::ContactPtr &contact, const QString &serviceName)
{
    QVariantMap request = dbusTubeCommonRequest(serviceName);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle"),
                   contact ? contact->handle().at(0) : (uint) 0);
    return request;
}

QVariantMap dbusTubeRoomRequest(const QString &roomName, const QString &serviceName)
{
    QVariantMap request;
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                   TP_QT_IFACE_CHANNEL_TYPE_DBUS_TUBE);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                   (uint) Tp::HandleTypeRoom);
    request.insert(TP_QT_IFACE_CHANNEL_TYPE_DBUS_TUBE + QLatin1String(".ServiceName"),
                   serviceName);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"),
                   roomName);
    return request;
}

QVariantMap conferenceCommonRequest(const QString &channelType, Tp::HandleType targetHandleType,
        const QList<Tp::ChannelPtr> &channels)
{
    QVariantMap request;
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                   channelType);
    if (targetHandleType != Tp::HandleTypeNone) {
        request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                       (uint) targetHandleType);
    }

    Tp::ObjectPathList objectPaths;
    foreach (const Tp::ChannelPtr &channel, channels) {
        objectPaths << QDBusObjectPath(channel->objectPath());
    }

    request.insert(TP_QT_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"),
            qVariantFromValue(objectPaths));
    return request;
}

QVariantMap conferenceRequest(const QString &channelType, Tp::HandleType targetHandleType,
        const QList<Tp::ChannelPtr> &channels, const QStringList &initialInviteeContactsIdentifiers)
{
    QVariantMap request = conferenceCommonRequest(channelType, targetHandleType, channels);
    if (!initialInviteeContactsIdentifiers.isEmpty()) {
        request.insert(TP_QT_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeIDs"),
                initialInviteeContactsIdentifiers);
    }
    return request;
}

QVariantMap conferenceRequest(const QString &channelType, Tp::HandleType targetHandleType,
        const QList<Tp::ChannelPtr> &channels, const QList<Tp::ContactPtr> &initialInviteeContacts)
{
    QVariantMap request = conferenceCommonRequest(channelType, targetHandleType, channels);
    if (!initialInviteeContacts.isEmpty()) {
        Tp::UIntList handles;
        foreach (const Tp::ContactPtr &contact, initialInviteeContacts) {
            if (!contact) {
                continue;
            }
            handles << contact->handle()[0];
        }
        if (!handles.isEmpty()) {
            request.insert(TP_QT_IFACE_CHANNEL_INTERFACE_CONFERENCE +
                        QLatin1String(".InitialInviteeHandles"), qVariantFromValue(handles));
        }
    }
    return request;
}

QVariantMap conferenceTextChatRequest(const QList<Tp::ChannelPtr> &channels,
        const QStringList &initialInviteeContactsIdentifiers)
{
    QVariantMap request = conferenceRequest(TP_QT_IFACE_CHANNEL_TYPE_TEXT,
            Tp::HandleTypeNone, channels, initialInviteeContactsIdentifiers);
    return request;
}

QVariantMap conferenceTextChatRequest(const QList<Tp::ChannelPtr> &channels,
        const QList<Tp::ContactPtr> &initialInviteeContacts)
{
    QVariantMap request = conferenceRequest(TP_QT_IFACE_CHANNEL_TYPE_TEXT,
            Tp::HandleTypeNone, channels, initialInviteeContacts);
    return request;
}

QVariantMap conferenceTextChatroomRequest(const QString &roomName,
        const QList<Tp::ChannelPtr> &channels,
        const QStringList &initialInviteeContactsIdentifiers)
{
    QVariantMap request = conferenceRequest(TP_QT_IFACE_CHANNEL_TYPE_TEXT,
            Tp::HandleTypeRoom, channels, initialInviteeContactsIdentifiers);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"), roomName);
    return request;
}

QVariantMap conferenceTextChatroomRequest(const QString &roomName,
        const QList<Tp::ChannelPtr> &channels,
        const QList<Tp::ContactPtr> &initialInviteeContacts)
{
    QVariantMap request = conferenceRequest(TP_QT_IFACE_CHANNEL_TYPE_TEXT,
            Tp::HandleTypeRoom, channels, initialInviteeContacts);
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"), roomName);
    return request;
}

QVariantMap conferenceStreamedMediaCallRequest(const QList<Tp::ChannelPtr> &channels,
        const QStringList &initialInviteeContactsIdentifiers)
{
    QVariantMap request = conferenceRequest(TP_QT_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
            Tp::HandleTypeNone, channels, initialInviteeContactsIdentifiers);
    return request;
}

QVariantMap conferenceStreamedMediaCallRequest(const QList<Tp::ChannelPtr> &channels,
        const QList<Tp::ContactPtr> &initialInviteeContacts)
{
    QVariantMap request = conferenceRequest(TP_QT_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
            Tp::HandleTypeNone, channels, initialInviteeContacts);
    return request;
}

QVariantMap contactSearchRequest(const ConnectionCapabilities &capabilities,
        const QString &server, uint limit)
{
    QVariantMap request;
    request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                   TP_QT_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);
    if (capabilities.contactSearchesWithSpecificServer()) {
        request.insert(TP_QT_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(".Server"),
                       server);
    } else if (!server.isEmpty()) {
        warning() << "Ignoring Server parameter for contact search, since the protocol does not support it.";
    }
    if (capabilities.contactSearchesWithLimit()) {
        request.insert(TP_QT_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(".Limit"), limit);
    } else if (limit > 0) {
        warning() << "Ignoring Limit parameter for contact search, since the protocol does not support it.";
    }
    return request;
}

} // anonymous namespace

struct TP_QT_NO_EXPORT Account::Private
{
    Private(Account *parent, const ConnectionFactoryConstPtr &connFactory,
            const ChannelFactoryConstPtr &chanFactory,
            const ContactFactoryConstPtr &contactFactory);
    ~Private();

    void init();

    static void introspectMain(Private *self);
    static void introspectAvatar(Private *self);
    static void introspectProtocolInfo(Private *self);
    static void introspectCapabilities(Private *self);

    void updateProperties(const QVariantMap &props);
    void retrieveAvatar();
    bool processConnQueue();

    bool checkCapabilitiesChanged(bool profileChanged);

    QString connectionObjectPath() const;

    // Public object
    Account *parent;

    // Factories
    ConnectionFactoryConstPtr connFactory;
    ChannelFactoryConstPtr chanFactory;
    ContactFactoryConstPtr contactFactory;

    // Instance of generated interface class
    Client::AccountInterface *baseInterface;

    // Mandatory properties interface proxy
    Client::DBus::PropertiesInterface *properties;

    ReadinessHelper *readinessHelper;

    // Introspection
    QVariantMap parameters;
    bool valid;
    bool enabled;
    bool connectsAutomatically;
    bool hasBeenOnline;
    bool changingPresence;
    QString cmName;
    QString protocolName;
    QString serviceName;
    ProfilePtr profile;
    QString displayName;
    QString nickname;
    QString iconName;
    QQueue<QString> connObjPathQueue;
    ConnectionPtr connection;
    bool mayFinishCore, coreFinished;
    QString normalizedName;
    Avatar avatar;
    ConnectionManagerPtr cm;
    ConnectionStatus connectionStatus;
    ConnectionStatusReason connectionStatusReason;
    QString connectionError;
    Connection::ErrorDetails connectionErrorDetails;
    Presence automaticPresence;
    Presence currentPresence;
    Presence requestedPresence;
    bool usingConnectionCaps;
    ConnectionCapabilities customCaps;

    // The contexts should never be removed from the map, to guarantee O(1) CD introspections per bus
    struct DispatcherContext;
    static QHash<QString, QSharedPointer<DispatcherContext> > dispatcherContexts;
    QSharedPointer<DispatcherContext> dispatcherContext;
};

struct Account::Private::DispatcherContext
{
    DispatcherContext(const QDBusConnection &bus)
        : iface(new Client::ChannelDispatcherInterface(bus, TP_QT_CHANNEL_DISPATCHER_BUS_NAME, TP_QT_CHANNEL_DISPATCHER_OBJECT_PATH)),
          introspected(false), supportsHints(false)
    {
    }

    ~DispatcherContext()
    {
        delete iface;
    }

    Client::ChannelDispatcherInterface *iface;

    bool introspected, supportsHints;
    QPointer<PendingVariant> introspectOp;

private:
    DispatcherContext(const DispatcherContext &);
    void operator=(const DispatcherContext &);
};

Account::Private::Private(Account *parent, const ConnectionFactoryConstPtr &connFactory,
        const ChannelFactoryConstPtr &chanFactory, const ContactFactoryConstPtr &contactFactory)
    : parent(parent),
      connFactory(connFactory),
      chanFactory(chanFactory),
      contactFactory(contactFactory),
      baseInterface(new Client::AccountInterface(parent)),
      properties(parent->interface<Client::DBus::PropertiesInterface>()),
      readinessHelper(parent->readinessHelper()),
      valid(false),
      enabled(false),
      connectsAutomatically(false),
      hasBeenOnline(false),
      changingPresence(false),
      mayFinishCore(false),
      coreFinished(false),
      connectionStatus(ConnectionStatusDisconnected),
      connectionStatusReason(ConnectionStatusReasonNoneSpecified),
      usingConnectionCaps(false),
      dispatcherContext(dispatcherContexts.value(parent->dbusConnection().name()))
{
    // FIXME: QRegExp probably isn't the most efficient possible way to parse
    //        this :-)
    QRegExp rx(QLatin1String("^") + TP_QT_ACCOUNT_OBJECT_PATH_BASE +
                QLatin1String("/([_A-Za-z][_A-Za-z0-9]*)"  // cap(1) is the CM
                "/([_A-Za-z][_A-Za-z0-9]*)"  // cap(2) is the protocol
                "/([_A-Za-z][_A-Za-z0-9]*)"  // account-specific part
                ));

    if (rx.exactMatch(parent->objectPath())) {
        cmName = rx.cap(1);
        protocolName = rx.cap(2).replace(QLatin1Char('_'), QLatin1Char('-'));
    } else {
        warning() << "Account object path is not spec-compliant, "
            "trying again with a different account-specific part check";

        rx = QRegExp(QLatin1String("^") + TP_QT_ACCOUNT_OBJECT_PATH_BASE +
                    QLatin1String("/([_A-Za-z][_A-Za-z0-9]*)"  // cap(1) is the CM
                    "/([_A-Za-z][_A-Za-z0-9]*)"  // cap(2) is the protocol
                    "/([_A-Za-z0-9]*)"  // account-specific part
                    ));
        if (rx.exactMatch(parent->objectPath())) {
            cmName = rx.cap(1);
            protocolName = rx.cap(2).replace(QLatin1Char('_'), QLatin1Char('-'));
        } else {
            warning() << "Not a valid Account object path:" <<
                parent->objectPath();
        }
    }

    ReadinessHelper::Introspectables introspectables;

    // As Account does not have predefined statuses let's simulate one (0)
    ReadinessHelper::Introspectable introspectableCore(
        QSet<uint>() << 0,                                                      // makesSenseForStatuses
        Features(),                                                             // dependsOnFeatures
        QStringList(),                                                          // dependsOnInterfaces
        (ReadinessHelper::IntrospectFunc) &Private::introspectMain,
        this);
    introspectables[FeatureCore] = introspectableCore;

    ReadinessHelper::Introspectable introspectableAvatar(
        QSet<uint>() << 0,                                                            // makesSenseForStatuses
        Features() << FeatureCore,                                                    // dependsOnFeatures (core)
        QStringList() << TP_QT_IFACE_ACCOUNT_INTERFACE_AVATAR, // dependsOnInterfaces
        (ReadinessHelper::IntrospectFunc) &Private::introspectAvatar,
        this);
    introspectables[FeatureAvatar] = introspectableAvatar;

    ReadinessHelper::Introspectable introspectableProtocolInfo(
        QSet<uint>() << 0,                                                      // makesSenseForStatuses
        Features() << FeatureCore,                                              // dependsOnFeatures (core)
        QStringList(),                                                          // dependsOnInterfaces
        (ReadinessHelper::IntrospectFunc) &Private::introspectProtocolInfo,
        this);
    introspectables[FeatureProtocolInfo] = introspectableProtocolInfo;

    ReadinessHelper::Introspectable introspectableCapabilities(
        QSet<uint>() << 0,                                                      // makesSenseForStatuses
        Features() << FeatureCore << FeatureProtocolInfo << FeatureProfile,     // dependsOnFeatures
        QStringList(),                                                          // dependsOnInterfaces
        (ReadinessHelper::IntrospectFunc) &Private::introspectCapabilities,
        this);
    introspectables[FeatureCapabilities] = introspectableCapabilities;

    readinessHelper->addIntrospectables(introspectables);

    if (connFactory->dbusConnection().name() != parent->dbusConnection().name()) {
        warning() << "  The D-Bus connection in the conn factory is not the proxy connection for"
            << parent->objectPath();
    }

    if (chanFactory->dbusConnection().name() != parent->dbusConnection().name()) {
        warning() << "  The D-Bus connection in the channel factory is not the proxy connection for"
            << parent->objectPath();
    }

    if (!dispatcherContext) {
        dispatcherContext = QSharedPointer<DispatcherContext>(new DispatcherContext(parent->dbusConnection()));
        dispatcherContexts.insert(parent->dbusConnection().name(), dispatcherContext);
    }

    init();
}

Account::Private::~Private()
{
}

bool Account::Private::checkCapabilitiesChanged(bool profileChanged)
{
    /* when the capabilities changed:
     *
     * - We were using the connection caps and now we don't have connection or
     *   the connection we have is not connected (changed to CM caps)
     * - We were using the CM caps and now we have a connected connection
     *   (changed to new connection caps)
     */
    bool changed = false;

    if (usingConnectionCaps &&
        (parent->connection().isNull() ||
         connection->status() != ConnectionStatusConnected)) {
        usingConnectionCaps = false;
        changed = true;
    } else if (!usingConnectionCaps &&
        !parent->connection().isNull() &&
        connection->status() == ConnectionStatusConnected) {
        usingConnectionCaps = true;
        changed = true;
    } else if (!usingConnectionCaps && profileChanged) {
        changed = true;
    }

    if (changed && parent->isReady(FeatureCapabilities)) {
        emit parent->capabilitiesChanged(parent->capabilities());
    }

    return changed;
}

QString Account::Private::connectionObjectPath() const
{
    return !connection.isNull() ? connection->objectPath() : QString();
}

QHash<QString, QSharedPointer<Account::Private::DispatcherContext> > Account::Private::dispatcherContexts;

/**
 * \class Account
 * \ingroup clientaccount
 * \headerfile TelepathyQt/account.h <TelepathyQt/Account>
 *
 * \brief The Account class represents a Telepathy account.
 *
 * The remote object accessor functions on this object (isValidAccount(),
 * isEnabled(), and so on) don't make any D-Bus calls; instead, they return/use
 * values cached from a previous introspection run. The introspection process
 * populates their values in the most efficient way possible based on what the
 * service implements.
 *
 * To avoid unnecessary D-Bus traffic, some accessors only return valid
 * information after specific features have been enabled.
 * For instance, to retrieve the account protocol information, it is necessary to
 * enable the feature Account::FeatureProtocolInfo.
 * See the individual methods descriptions for more details.
 *
 * Account features can be enabled by constructing an AccountFactory and enabling
 * the desired features, and passing it to AccountManager or ClientRegistrar
 * when creating them as appropriate. However, if a particular
 * feature is only ever used in a specific circumstance, such as an user opening
 * some settings dialog separate from the general view of the application,
 * features can be later enabled as needed by calling becomeReady() with the additional
 * features, and waiting for the resulting PendingOperation to finish.
 *
 * As an addition to accessors, signals are emitted to indicate that properties have
 * changed, for example displayNameChanged(), iconNameChanged(), etc.
 *
 * Convenience methods to create channels using the channel dispatcher such as
 * ensureTextChat(), createFileTransfer() are also provided.
 *
 * If the account is deleted from the AccountManager, this object
 * will not be deleted automatically; however, it will emit invalidated()
 * with error code #TP_QT_ERROR_OBJECT_REMOVED and will cease to
 * be useful.
 *
 * \section account_usage_sec Usage
 *
 * \subsection account_create_sec Creating an account object
 *
 * The easiest way to create account objects is through AccountManager. One can
 * just use the AccountManager convenience methods such as
 * AccountManager::validAccounts() to get a list of account objects representing
 * valid accounts.
 *
 * If you already know the object path, you can just call create().
 * For example:
 *
 * \code AccountPtr acc = Account::create(busName, objectPath); \endcode
 *
 * An AccountPtr object is returned, which will automatically keep
 * track of object lifetime.
 *
 * You can also provide a D-Bus connection as a QDBusConnection:
 *
 * \code
 *
 * AccountPtr acc = Account::create(QDBusConnection::sessionBus(),
 *         busName, objectPath);
 *
 * \endcode
 *
 * \subsection account_ready_sec Making account ready to use
 *
 * An Account object needs to become ready before usage, meaning that the
 * introspection process finished and the object accessors can be used.
 *
 * To make the object ready, use becomeReady() and wait for the
 * PendingOperation::finished() signal to be emitted.
 *
 * \code
 *
 * class MyClass : public QObject
 * {
 *     QOBJECT
 *
 * public:
 *     MyClass(QObject *parent = 0);
 *     ~MyClass() { }
 *
 * private Q_SLOTS:
 *     void onAccountReady(Tp::PendingOperation*);
 *
 * private:
 *     AccountPtr acc;
 * };
 *
 * MyClass::MyClass(const QString &busName, const QString &objectPath,
 *         QObject *parent)
 *     : QObject(parent)
 *       acc(Account::create(busName, objectPath))
 * {
 *     connect(acc->becomeReady(),
 *             SIGNAL(finished(Tp::PendingOperation*)),
 *             SLOT(onAccountReady(Tp::PendingOperation*)));
 * }
 *
 * void MyClass::onAccountReady(Tp::PendingOperation *op)
 * {
 *     if (op->isError()) {
 *         qWarning() << "Account cannot become ready:" <<
 *             op->errorName() << "-" << op->errorMessage();
 *         return;
 *     }
 *
 *     // Account is now ready
 *     qDebug() << "Display name:" << acc->displayName();
 * }
 *
 * \endcode
 *
 * See \ref async_model, \ref shared_ptr
 */

/**
 * Feature representing the core that needs to become ready to make the Account
 * object usable.
 *
 * Note that this feature must be enabled in order to use most Account methods.
 * See specific methods documentation for more details.
 *
 * When calling isReady(), becomeReady(), this feature is implicitly added
 * to the requested features.
 */
const Feature Account::FeatureCore = Feature(QLatin1String(Account::staticMetaObject.className()), 0, true);

/**
 * Feature used in order to access account avatar info.
 *
 * See avatar specific methods' documentation for more details.
 *
 * \sa avatar(), avatarChanged()
 */
const Feature Account::FeatureAvatar = Feature(QLatin1String(Account::staticMetaObject.className()), 1);

/**
 * Feature used in order to access account protocol info.
 *
 * See protocol info specific methods' documentation for more details.
 *
 * \sa protocolInfo()
 */
const Feature Account::FeatureProtocolInfo = Feature(QLatin1String(Account::staticMetaObject.className()), 2);

/**
 * Feature used in order to access account capabilities.
 *
 * Enabling this feature will also enable FeatureProtocolInfo and FeatureProfile.
 *
 * See capabilities specific methods' documentation for more details.
 *
 * \sa capabilities(), capabilitiesChanged()
 */
const Feature Account::FeatureCapabilities = Feature(QLatin1String(Account::staticMetaObject.className()), 3);

/**
 * Feature used in order to access account profile info.
 *
 * See profile specific methods' documentation for more details.
 *
 * \sa profile(), profileChanged()
 */
const Feature Account::FeatureProfile = FeatureProtocolInfo;
// FeatureProfile is the same as FeatureProtocolInfo for now, as it only needs
// the protocol info, cm name and protocol name to build a fake profile. Make it
// a full-featured feature if needed later.

/**
 * Create a new Account object using QDBusConnection::sessionBus() and the given factories.
 *
 * A warning is printed if the factories are not for QDBusConnection::sessionBus().
 *
 * \param busName The account well-known bus name (sometimes called a "service
 *                name"). This is usually the same as the account manager
 *                bus name #TP_QT_ACCOUNT_MANAGER_BUS_NAME.
 * \param objectPath The account object path.
 * \param connectionFactory The connection factory to use.
 * \param channelFactory The channel factory to use.
 * \param contactFactory The contact factory to use.
 * \return An AccountPtr object pointing to the newly created Account object.
 */
AccountPtr Account::create(const QString &busName, const QString &objectPath,
        const ConnectionFactoryConstPtr &connectionFactory,
        const ChannelFactoryConstPtr &channelFactory,
        const ContactFactoryConstPtr &contactFactory)
{
    return AccountPtr(new Account(QDBusConnection::sessionBus(), busName, objectPath,
                connectionFactory, channelFactory, contactFactory, Account::FeatureCore));
}

/**
 * Create a new Account object using the given \a bus and the given factories.
 *
 * A warning is printed if the factories are not for \a bus.
 *
 * \param bus QDBusConnection to use.
 * \param busName The account well-known bus name (sometimes called a "service
 *                name"). This is usually the same as the account manager
 *                bus name #TP_QT_ACCOUNT_MANAGER_BUS_NAME.
 * \param objectPath The account object path.
 * \param connectionFactory The connection factory to use.
 * \param channelFactory The channel factory to use.
 * \param contactFactory The contact factory to use.
 * \return An AccountPtr object pointing to the newly created Account object.
 */
AccountPtr Account::create(const QDBusConnection &bus,
        const QString &busName, const QString &objectPath,
        const ConnectionFactoryConstPtr &connectionFactory,
        const ChannelFactoryConstPtr &channelFactory,
        const ContactFactoryConstPtr &contactFactory)
{
    return AccountPtr(new Account(bus, busName, objectPath, connectionFactory, channelFactory,
                contactFactory, Account::FeatureCore));
}

/**
 * Construct a new Account object using the given \a bus and the given factories.
 *
 * A warning is printed if the factories are not for \a bus.
 *
 * \param bus QDBusConnection to use.
 * \param busName The account well-known bus name (sometimes called a "service
 *                name"). This is usually the same as the account manager
 *                bus name #TP_QT_ACCOUNT_MANAGER_BUS_NAME.
 * \param objectPath The account object path.
 * \param connectionFactory The connection factory to use.
 * \param channelFactory The channel factory to use.
 * \param contactFactory The contact factory to use.
 * \param coreFeature The core feature of the Account subclass. The corresponding introspectable
 * should depend on Account::FeatureCore.
 */
Account::Account(const QDBusConnection &bus,
        const QString &busName, const QString &objectPath,
        const ConnectionFactoryConstPtr &connectionFactory,
        const ChannelFactoryConstPtr &channelFactory,
        const ContactFactoryConstPtr &contactFactory,
        const Feature &coreFeature)
    : StatelessDBusProxy(bus, busName, objectPath, coreFeature),
      OptionalInterfaceFactory<Account>(this),
      mPriv(new Private(this, connectionFactory, channelFactory, contactFactory))
{
}

/**
 * Class destructor.
 */
Account::~Account()
{
    delete mPriv;
}

/**
 * Return the connection factory used by this account.
 *
 * Only read access is provided. This allows constructing object instances and examining the object
 * construction settings, but not changing settings. Allowing changes would lead to tricky
 * situations where objects constructed at different times by the account would have unpredictably
 * different construction settings (eg. subclass).
 *
 * \return A read-only pointer to the ConnectionFactory object.
 */
ConnectionFactoryConstPtr Account::connectionFactory() const
{
    return mPriv->connFactory;
}

/**
 * Return the channel factory used by this account.
 *
 * Only read access is provided. This allows constructing object instances and examining the object
 * construction settings, but not changing settings. Allowing changes would lead to tricky
 * situations where objects constructed at different times by the account would have unpredictably
 * different construction settings (eg. subclass).
 *
 * \return A read-only pointer to the ChannelFactory object.
 */
ChannelFactoryConstPtr Account::channelFactory() const
{
    return mPriv->chanFactory;
}

/**
 * Return the contact factory used by this account.
 *
 * Only read access is provided. This allows constructing object instances and examining the object
 * construction settings, but not changing settings. Allowing changes would lead to tricky
 * situations where objects constructed at different times by the account would have unpredictably
 * different construction settings (eg. subclass).
 *
 * \return A read-only pointer to the ContactFactory object.
 */
ContactFactoryConstPtr Account::contactFactory() const
{
    return mPriv->contactFactory;
}

/**
 * Return whether this account is valid.
 *
 * If \c true, this account is considered by the account manager to be complete
 * and usable. If \c false, user action is required to make it usable, and it will
 * never attempt to connect. For instance, this might be caused by the absence
 * or misconfiguration of a required parameter, in which case updateParameters()
 * may be used to properly set the parameters values.
 *
 * Change notification is via the validityChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return \c true if valid, \c false otherwise.
 * \sa validityChanged(), updateParameters()
 */
bool Account::isValidAccount() const
{
    return mPriv->valid;
}

/**
 * Return whether this account is enabled.
 *
 * Change notification is via the stateChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return \c true if enabled, \c false otherwise.
 * \sa stateChanged(), setEnabled()
 */
bool Account::isEnabled() const
{
    return mPriv->enabled;
}

/**
 * Set whether this account should be enabled or disabled.
 *
 * This gives users the possibility to prevent an account from
 * being used.
 *
 * Note that changing this property won't change the validity of the account.
 *
 * \param value Whether this account should be enabled or disabled.
 * \return A PendingOperation which will emit PendingOperation::finished
 *         when the request has been made.
 * \sa stateChanged(), isEnabled()
 */
PendingOperation *Account::setEnabled(bool value)
{
    return new PendingVoid(
            mPriv->properties->Set(
                TP_QT_IFACE_ACCOUNT,
                QLatin1String("Enabled"),
                QDBusVariant(value)),
            AccountPtr(this));
}

/**
 * Return the connection manager name of this account.
 *
 * \return The connection manager name.
 */
QString Account::cmName() const
{
    return mPriv->cmName;
}

/**
 * Return the protocol name of this account.
 *
 * \return The protocol name.
 */
QString Account::protocolName() const
{
    return mPriv->protocolName;
}

/**
 * Return the service name of this account.
 *
 * Note that this method will fallback to protocolName() if service name
 * is not known.
 *
 * Change notification is via the serviceNameChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The service name.
 * \sa serviceNameChanged(), setServiceName(), protocolName()
 */
QString Account::serviceName() const
{
    if (mPriv->serviceName.isEmpty()) {
        return mPriv->protocolName;
    }
    return mPriv->serviceName;
}

/**
 * Set the service name of this account.
 *
 * Some protocols, like XMPP and SIP, are used by various different user-recognised brands,
 * such as Google Talk. On accounts for such services, this method can be used
 * to set the name describing the service, which must consist only of ASCII letters, numbers and
 * hyphen/minus signs, and start with a letter.
 * For the jabber protocol, one of the following service names should be used if possible:
 *
 *   google-talk (for Google's IM service)
 *   facebook (for Facebook's IM service)
 *   lj-talk (for LiveJournal's IM service)
 *
 * The service name may also be set, if appropriate, when creating the account. See
 * AccountManager::createAccount() for more details.
 *
 * Note that changing this property may also change the profile() used by this account,
 * in which case profileChanged() will be emitted in addition to serviceNameChanged(), if
 * Account::FeatureProfile is enabled.
 *
 * \param value The service name of this account.
 * \return A PendingOperation which will emit PendingOperation::finished
 *         when the request has been made.
 * \sa serviceNameChanged(), serviceName()
 */
PendingOperation *Account::setServiceName(const QString &value)
{
    return new PendingVoid(
            mPriv->properties->Set(
                TP_QT_IFACE_ACCOUNT,
                QLatin1String("Service"),
                QDBusVariant(value)),
            AccountPtr(this));
}

/**
 * Return the profile used by this account.
 *
 * Profiles are intended to describe variants of the basic protocols supported by Telepathy
 * connection managers.
 * An example of this would be Google Talk vs Facebook chat vs Jabber/XMPP. Google Talk is a
 * specific case of XMPP with well-known capabilities, quirks and settings, and Facebook chat is
 * a subset of the standard XMPP offering.
 *
 * This method will return the profile for this account based on the service used by it.
 *
 * Note that if a profile for serviceName() is not available, a fake profile
 * (Profile::isFake() is \c true) will be returned in case protocolInfo() is valid.
 *
 * The fake profile will contain the following info:
 *  - Profile::type() will return "IM"
 *  - Profile::provider() will return an empty string
 *  - Profile::serviceName() will return "cmName()-serviceName()"
 *  - Profile::name() and Profile::protocolName() will return protocolName()
 *  - Profile::iconName() will return "im-protocolName()"
 *  - Profile::cmName() will return cmName()
 *  - Profile::parameters() will return a list matching CM default parameters for protocol with name
 *    protocolName()
 *  - Profile::presences() will return an empty list and
 *    Profile::allowOtherPresences() will return \c true, meaning that CM
 *    presences should be used
 *  - Profile::unsupportedChannelClassSpecs() will return an empty list
 *
 * Change notification is via the profileChanged() signal.
 *
 * This method requires Account::FeatureProfile to be ready.
 *
 * \return A pointer to the Profile object.
 * \sa profileChanged(), serviceName()
 */
ProfilePtr Account::profile() const
{
    if (!isReady(FeatureProfile)) {
        warning() << "Account::profile() requires Account::FeatureProfile to be ready";
        return ProfilePtr();
    }

    if (!mPriv->profile) {
        mPriv->profile = Profile::createForServiceName(serviceName());
        if (!mPriv->profile->isValid()) {
            if (protocolInfo().isValid()) {
                mPriv->profile = ProfilePtr(new Profile(
                            QString(QLatin1String("%1-%2")).arg(mPriv->cmName).arg(serviceName()),
                            mPriv->cmName,
                            mPriv->protocolName,
                            protocolInfo()));
            } else {
                warning() << "Cannot create profile as neither a .profile is installed for service" <<
                    serviceName() << "nor protocol info can be retrieved";
            }
        }
    }
    return mPriv->profile;
}

/**
 * Return the display name of this account.
 *
 * Change notification is via the displayNameChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The display name.
 * \sa displayNameChanged(), setDisplayName()
 */
QString Account::displayName() const
{
    return mPriv->displayName;
}

/**
 * Set the display name of this account.
 *
 * The display name is the user-visible name of this account.
 * This is usually chosen by the user at account creation time.
 * See AccountManager::createAccount() for more details.
 *
 * \param value The display name of this account.
 * \return A PendingOperation which will emit PendingOperation::finished
 *         when the request has been made.
 * \sa displayNameChanged(), displayName()
 */
PendingOperation *Account::setDisplayName(const QString &value)
{
    return new PendingVoid(
            mPriv->properties->Set(
                TP_QT_IFACE_ACCOUNT,
                QLatin1String("DisplayName"),
                QDBusVariant(value)),
            AccountPtr(this));
}

/**
 * Return the icon name of this account.
 *
 * If the account has no icon, and Account::FeatureProfile is enabled, the icon from the result of
 * profile() will be used.
 *
 * If neither the account nor the profile has an icon, and Account::FeatureProtocolInfo is
 * enabled, the icon from protocolInfo() will be used if set.
 *
 * As a last resort, "im-" + protocolName() will be returned.
 *
 * This matches the fallbacks recommended by the \telepathy_spec.
 *
 * Change notification is via the iconNameChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The icon name.
 * \sa iconNameChanged(), setIconName()
 */
QString Account::iconName() const
{
    if (mPriv->iconName.isEmpty()) {
        if (isReady(FeatureProfile)) {
            ProfilePtr pr = profile();
            if (pr && pr->isValid()) {
                QString iconName = pr->iconName();
                if (!iconName.isEmpty()) {
                    return iconName;
                }
            }
        }

        if (isReady(FeatureProtocolInfo) && protocolInfo().isValid()) {
            return protocolInfo().iconName();
        }

        return QString(QLatin1String("im-%1")).arg(protocolName());
    }

    return mPriv->iconName;
}

/**
 * Set the icon name of this account.
 *
 * \param value The icon name of this account.
 * \return A PendingOperation which will emit PendingOperation::finished
 *         when the request has been made.
 * \sa iconNameChanged(), iconName()
 */
PendingOperation *Account::setIconName(const QString &value)
{
    return new PendingVoid(
            mPriv->properties->Set(
                TP_QT_IFACE_ACCOUNT,
                QLatin1String("Icon"),
                QDBusVariant(value)),
            AccountPtr(this));
}

/**
 * Return the nickname of this account.
 *
 * Change notification is via the nicknameChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The nickname.
 * \sa nicknameChanged(), setNickname()
 */
QString Account::nickname() const
{
    return mPriv->nickname;
}

/**
 * Set the nickname of this account as seen to other contacts.
 *
 * \param value The nickname of this account.
 * \return A PendingOperation which will emit PendingOperation::finished
 *         when the request has been made.
 * \sa nicknameChanged(), nickname()
 */
PendingOperation *Account::setNickname(const QString &value)
{
    return new PendingVoid(
            mPriv->properties->Set(
                TP_QT_IFACE_ACCOUNT,
                QLatin1String("Nickname"),
                QDBusVariant(value)),
            AccountPtr(this));
}

/**
 * Return the avatar requirements (size limits, supported MIME types, etc)
 * for avatars passed to setAvatar() on this account.
 *
 * For now this method will only return the avatar requirements found in protocolInfo() if
 * Account::FeatureProtocolInfo is ready, otherwise an invalid AvatarSpec instance is returned.
 *
 * \return The requirements as an AvatarSpec object.
 * \sa avatar(), setAvatar()
 */
AvatarSpec Account::avatarRequirements() const
{
    // TODO Once connection has support for avatar requirements use it if the connection is usable
    ProtocolInfo pi = protocolInfo();
    if (pi.isValid()) {
        return pi.avatarRequirements();
    }
    return AvatarSpec();
}

/**
 * Return the avatar of this account.
 *
 * Change notification is via the avatarChanged() signal.
 *
 * This method requires Account::FeatureAvatar to be ready.
 *
 * \return The avatar as an Avatar object.
 * \sa avatarChanged(), setAvatar()
 */
const Avatar &Account::avatar() const
{
    if (!isReady(Features() << FeatureAvatar)) {
        warning() << "Trying to retrieve avatar from account, but "
                     "avatar is not supported or was not requested. "
                     "Use becomeReady(FeatureAvatar)";
    }

    return mPriv->avatar;
}

/**
 * Set avatar of this account as seen to other contacts.
 *
 * Note that \a avatar must match the requirements as returned by avatarRequirements().
 *
 * \param avatar The avatar of this account.
 * \return A PendingOperation which will emit PendingOperation::finished
 *         when the request has been made.
 * \sa avatarChanged(), avatar(), avatarRequirements()
 */
PendingOperation *Account::setAvatar(const Avatar &avatar)
{
    if (!interfaces().contains(TP_QT_IFACE_ACCOUNT_INTERFACE_AVATAR)) {
        return new PendingFailure(
                TP_QT_ERROR_NOT_IMPLEMENTED,
                QLatin1String("Account does not support Avatar"),
                AccountPtr(this));
    }

    return new PendingVoid(
            mPriv->properties->Set(
                TP_QT_IFACE_ACCOUNT_INTERFACE_AVATAR,
                QLatin1String("Avatar"),
                QDBusVariant(QVariant::fromValue(avatar))),
            AccountPtr(this));
}

/**
 * Return the parameters of this account.
 *
 * The account parameters are represented as a map from connection manager parameter names
 * to their values.
 *
 * Change notification is via the parametersChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The parameters as QVariantMap.
 * \sa parametersChanged(), updateParameters()
 */
QVariantMap Account::parameters() const
{
    return mPriv->parameters;
}

/**
 * Update this account parameters.
 *
 * On success, the PendingOperation returned by this method will produce a
 * list of strings, which are the names of parameters whose changes will not
 * take effect until the account is disconnected and reconnected (for instance
 * by calling reconnect()).
 *
 * \param set Parameters to set.
 * \param unset Parameters to unset.
 * \return A PendingStringList which will emit PendingStringList::finished
 *         when the request has been made
 * \sa parametersChanged(), parameters(), reconnect()
 */
PendingStringList *Account::updateParameters(const QVariantMap &set,
        const QStringList &unset)
{
    return new PendingStringList(
            baseInterface()->UpdateParameters(set, unset),
            AccountPtr(this));
}

/**
 * Return the protocol info of this account protocol.
 *
 * This method requires Account::FeatureProtocolInfo to be ready.
 *
 * \return The protocol info as a ProtocolInfo object.
 */
ProtocolInfo Account::protocolInfo() const
{
    if (!isReady(Features() << FeatureProtocolInfo)) {
        warning() << "Trying to retrieve protocol info from account, but "
                     "protocol info is not supported or was not requested. "
                     "Use becomeReady(FeatureProtocolInfo)";
        return ProtocolInfo();
    }

    return mPriv->cm->protocol(mPriv->protocolName);
}

/**
 * Return the capabilities for this account.
 *
 * Note that this method will return the connection() capabilities if the
 * account is online and ready. If the account is disconnected, it will fallback
 * to return the subtraction of the protocolInfo() capabilities and the profile() unsupported
 * capabilities.
 *
 * Change notification is via the capabilitiesChanged() signal.
 *
 * This method requires Account::FeatureCapabilities to be ready.
 *
 * \return The capabilities as a ConnectionCapabilities object.
 * \sa capabilitiesChanged(), protocolInfo(), profile()
 */
ConnectionCapabilities Account::capabilities() const
{
    if (!isReady(FeatureCapabilities)) {
        warning() << "Trying to retrieve capabilities from account, but "
                     "FeatureCapabilities was not requested. "
                     "Use becomeReady(FeatureCapabilities)";
        return ConnectionCapabilities();
    }

    // if the connection is online and ready use its caps
    if (mPriv->connection &&
        mPriv->connection->status() == ConnectionStatusConnected) {
        return mPriv->connection->capabilities();
    }

    // if we are here it means FeatureProtocolInfo and FeatureProfile are ready, as
    // FeatureCapabilities depend on them, so let's use the subtraction of protocol info caps rccs
    // and profile unsupported rccs.
    //
    // However, if we failed to introspect the CM (eg. this is a test), then let's not try to use
    // the protocolInfo because it'll be NULL! Profile may also be NULL in case a .profile for
    // serviceName() is not present and protocolInfo is NULL.
    ProtocolInfo pi = protocolInfo();
    if (!pi.isValid()) {
        return ConnectionCapabilities();
    }
    ProfilePtr pr;
    if (isReady(FeatureProfile)) {
        pr = profile();
    }
    if (!pr || !pr->isValid()) {
        return pi.capabilities();
    }

    RequestableChannelClassSpecList piClassSpecs = pi.capabilities().allClassSpecs();
    RequestableChannelClassSpecList prUnsupportedClassSpecs = pr->unsupportedChannelClassSpecs();
    RequestableChannelClassSpecList classSpecs;
    bool unsupported;
    foreach (const RequestableChannelClassSpec &piClassSpec, piClassSpecs) {
        unsupported = false;
        foreach (const RequestableChannelClassSpec &prUnsuportedClassSpec, prUnsupportedClassSpecs) {
            // Here we check the following:
            // - If the unsupported spec has no allowed property it means it does not support any
            // class whose fixed properties match.
            //   E.g: Doesn't support any media calls, be it audio or video.
            // - If the unsupported spec has allowed properties it means it does not support a
            // specific class whose fixed properties and allowed properties should match.
            //   E.g: Doesn't support video calls but does support audio calls.
            if (prUnsuportedClassSpec.allowedProperties().isEmpty()) {
                if (piClassSpec.fixedProperties() == prUnsuportedClassSpec.fixedProperties()) {
                    unsupported = true;
                    break;
                }
            } else {
                if (piClassSpec == prUnsuportedClassSpec) {
                    unsupported = true;
                    break;
                }
            }
        }
        if (!unsupported) {
            classSpecs.append(piClassSpec);
        }
    }
    mPriv->customCaps = ConnectionCapabilities(classSpecs);
    return mPriv->customCaps;
}

/**
 * Return whether this account should be put online automatically whenever
 * possible.
 *
 * Change notification is via the connectsAutomaticallyPropertyChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return \c true if it should try to connect automatically, \c false
 *         otherwise.
 * \sa connectsAutomaticallyPropertyChanged(), setConnectsAutomatically()
 */
bool Account::connectsAutomatically() const
{
    return mPriv->connectsAutomatically;
}

/**
 * Set whether this account should be put online automatically whenever
 * possible.
 *
 * \param value Value indicating if this account should be put online whenever
 *              possible.
 * \return A PendingOperation which will emit PendingOperation::finished
 *         when the request has been made.
 * \sa connectsAutomaticallyPropertyChanged(), connectsAutomatically()
 */
PendingOperation *Account::setConnectsAutomatically(bool value)
{
    return new PendingVoid(
            mPriv->properties->Set(
                TP_QT_IFACE_ACCOUNT,
                QLatin1String("ConnectAutomatically"),
                QDBusVariant(value)),
            AccountPtr(this));
}

/**
 * Return whether this account has ever been put online successfully.
 *
 * This property cannot change from \c true to \c false, only from \c false to \c true.
 * When the account successfully goes online for the first time, or when it
 * is detected that this has already happened, the firstOnline() signal is
 * emitted.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return \c true if ever been online, \c false otherwise.
 */
bool Account::hasBeenOnline() const
{
    return mPriv->hasBeenOnline;
}

/**
 * Return the status of this account connection.
 *
 * Note that this method may return a different value from the one returned by Connection::status()
 * on this account connection. This happens because this value will change whenever the connection
 * status of this account connection changes and won't consider the Connection introspection
 * process. The same rationale also applies to connectionStatusReason() and
 * connectionErrorDetails().
 *
 * A valid use case for this is for account creation UIs that wish to display the accounts
 * connection status and nothing else on the connections (e.g. retrieve the contact list).
 *
 * Change notification is via the connectionStatusChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The connection status as #ConnectionStatus.
 * \sa connectionStatusChanged(), connectionStatusReason(), connectionError(),
 *     connectionErrorDetails()
 */
ConnectionStatus Account::connectionStatus() const
{
    return mPriv->connectionStatus;
}

/**
 * Return the reason for this account connection status.
 *
 * This represents the reason for the last change to connectionStatus().
 *
 * Note that this method may return a different value from the one returned by
 * Connection::statusReason() on this account connection.
 * See connectionStatus() for more details.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The connection status reason as #ConnectionStatusReason.
 * \sa connectionStatusChanged(), connectionStatus(), connectionError(), connectionErrorDetails()
 */
ConnectionStatusReason Account::connectionStatusReason() const
{
    return mPriv->connectionStatusReason;
}

/**
 * Return the D-Bus error name for the last disconnection or connection failure,
 * (in particular, #TP_QT_ERROR_CANCELLED if it was disconnected by user
 * request), or an empty string if the account is connected.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The D-Bus error name for the last disconnection or connection failure.
 * \sa connectionErrorDetails(), connectionStatus(), connectionStatusReason(),
 *     connectionStatusChanged()
 */
QString Account::connectionError() const
{
    return mPriv->connectionError;
}

/**
 * Return detailed information related to connectionError().
 *
 * Note that this method may return a different value from the one returned by
 * Connection::errorDetails() on this account connection.
 * See connectionStatus() for more details.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The connection error details as a Connection::ErrorDetails object.
 * \sa connectionError(), connectionStatus(), connectionStatusReason(), connectionStatusChanged(),
 *     Connection::ErrorDetails.
 */
Connection::ErrorDetails Account::connectionErrorDetails() const
{
    return mPriv->connectionErrorDetails;
}

/**
 * Return the object representing the connection of this account.
 *
 * Note that the Connection object returned by this method will have the
 * features set in the connectionFactory() used by this account ready.
 *
 * Change notification is via the connectionChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return A pointer to the Connection object, or a null ConnectionPtr if
 *         there is no connection currently or if an error occurred.
 * \sa connectionChanged()
 */
ConnectionPtr Account::connection() const
{
    return mPriv->connection;
}

/**
 * Return whether this account connection is changing presence.
 *
 * Change notification is via the changingPresence() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return \c true if changing presence, \c false otherwise.
 * \sa changingPresence(), currentPresenceChanged(), setRequestedPresence()
 */
bool Account::isChangingPresence() const
{
    return mPriv->changingPresence;
}

/**
 * Return a list of presences allowed by a connection to this account.
 *
 * In particular, for the statuses reported here it can be assumed that setting them as the
 * requested presence via setRequestedPresence() will eventually result in currentPresence()
 * changing to exactly said presence. Other statuses are only guaranteed to be matched as closely as
 * possible.
 *
 * The statuses can be also used for the automatic presence, as set by setAutomaticPresence(), with
 * the exception of any status specifications for which Presence::type() is
 * Tp::ConnectionPresenceTypeOffline for the Presence returned by PresenceSpec::presence().
 *
 * However, the optional parameter can be used to allow reporting also other possible presence
 * statuses on this protocol besides the others that can be set on yourself. These are purely
 * informatory, for e.g. adjusting an UI to allow all possible remote contact statuses to be
 * displayed.
 *
 * An offline presence status is always included, because it's always valid to make an account
 * offline by setting the requested presence to an offline status.
 *
 * Full functionality requires Account::FeatureProtocolInfo and Account::FeatureProfile to be ready
 * as well as connection with Connection::FeatureSimplePresence enabled. If the connection is online
 * and Connection::FeatureSimplePresence is enabled, it will return the connection allowed statuses,
 * otherwise it will return a list os statuses based on profile() and protocolInfo() information
 * if the corresponding features are enabled.
 *
 * If there's a mismatch between the presence status info provided in the .profile file and/or the
 * .manager file and what an online Connection actually reports (for example, the said data files
 * are missing or too old to include presence information), the returned value can change, in
 * particular when connectionChanged() is emitted with a connection for which Connection::status()
 * is Tp::ConnectionStatusConnected.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \param includeAllStatuses Whether the returned list will include all statuses or just the ones
 *                           that can be settable using setRequestedPresence().
 * \return The allowed statuses as a list of PresenceSpec objects.
 */
PresenceSpecList Account::allowedPresenceStatuses(bool includeAllStatuses) const
{
    QHash<QString, PresenceSpec> specMap;

    // if the connection is online and ready use it
    if (mPriv->connection &&
        mPriv->connection->status() == ConnectionStatusConnected &&
        mPriv->connection->actualFeatures().contains(Connection::FeatureSimplePresence)) {
        SimpleStatusSpecMap connectionAllowedPresences =
            mPriv->connection->lowlevel()->allowedPresenceStatuses();
        SimpleStatusSpecMap::const_iterator i = connectionAllowedPresences.constBegin();
        SimpleStatusSpecMap::const_iterator end = connectionAllowedPresences.constEnd();
        for (; i != end; ++i) {
            PresenceSpec presence = PresenceSpec(i.key(), i.value());
            specMap.insert(i.key(), presence);
        }
    } else {
        ProtocolInfo pi = protocolInfo();
        if (pi.isValid()) {
            // add all ProtocolInfo presences to the returned map
            foreach (const PresenceSpec &piPresence, pi.allowedPresenceStatuses()) {
                QString piStatus = piPresence.presence().status();
                specMap.insert(piStatus, piPresence);
            }
        }

        ProfilePtr pr;
        if (isReady(FeatureProfile)) {
            pr = profile();
        }
        if (pr && pr->isValid()) {
            // add all Profile presences to the returned map
            foreach (const Profile::Presence &prPresence, pr->presences()) {
                QString prStatus = prPresence.id();
                if (specMap.contains(prStatus)) {
                    // we already got the presence from ProtocolInfo, just update
                    // canHaveStatusMessage if needed
                    PresenceSpec presence = specMap.value(prStatus);
                    if (presence.canHaveStatusMessage() != prPresence.canHaveStatusMessage()) {
                        SimpleStatusSpec spec;
                        spec.type = presence.presence().type();
                        spec.maySetOnSelf = presence.maySetOnSelf();
                        spec.canHaveMessage = prPresence.canHaveStatusMessage();
                        specMap.insert(prStatus, PresenceSpec(prStatus, spec));
                    }
                } else {
                    // presence not found in ProtocolInfo, adding it
                    specMap.insert(prStatus, presenceSpecForStatus(prStatus,
                                prPresence.canHaveStatusMessage()));
                }
            }

            // now remove all presences that are not in the Profile, if it does
            // not allow other presences, and the ones that are disabled
            QHash<QString, PresenceSpec>::iterator i = specMap.begin();
            QHash<QString, PresenceSpec>::iterator end = specMap.end();
            while (i != end) {
                PresenceSpec presence = i.value();
                QString status = presence.presence().status();
                bool hasPresence = pr->hasPresence(status);
                Profile::Presence prPresence = pr->presence(status);
                if ((!hasPresence && !pr->allowOtherPresences()) || (hasPresence && prPresence.isDisabled())) {
                     i = specMap.erase(i);
                } else {
                     ++i;
                }
            }
        }
    }

    // filter out presences that may not be set on self if includeAllStatuses is false
    if (!includeAllStatuses) {
        QHash<QString, PresenceSpec>::iterator i = specMap.begin();
        QHash<QString, PresenceSpec>::iterator end = specMap.end();
        while (i != end) {
            PresenceSpec presence = i.value();
            if (!presence.maySetOnSelf()) {
                i = specMap.erase(i);
            } else {
                ++i;
            }
        }
    }

    if (!specMap.size()) {
        // If we didn't discover any statuses, either the protocol doesn't really support presence,
        // or we lack information (e.g. features not enabled or info not provided in the .manager or
        // .profile files). "available" - just the fact that you're online in the first place, is at
        // least a valid option for any protocol, so we'll include it as a fallback.

        specMap.insert(QLatin1String("available"),
                presenceSpecForStatus(QLatin1String("available"), false));
    }

    // We'll always include "offline". It is always valid to make an account offline via
    // setRequestedPresence().
    if (!specMap.contains(QLatin1String("offline"))) {
        specMap.insert(QLatin1String("offline"),
                presenceSpecForStatus(QLatin1String("offline"), false));
    }

    return specMap.values();
}

/**
 * Return the maximum length for a presence status message.
 *
 * If a status message set using setRequestedPresence() (or setAutomaticPresence()) is longer than
 * the maximum length allowed, the message will be truncated and
 * currentPresenceChanged() will be emitted (if setting the presence worked)
 * with the truncated message.
 *
 * Full functionality requires Connection with Connection::FeatureSimplePresence
 * enabled. If the connection is online and Connection::FeatureSimplePresence is
 * enabled, it will return the connection maximum status message length,
 * otherwise it will return 0.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The maximum length, or 0 if there is no limit.
 */
uint Account::maxPresenceStatusMessageLength() const
{
    // if the connection is online and ready use it
    if (mPriv->connection &&
        mPriv->connection->status() == ConnectionStatusConnected &&
        mPriv->connection->actualFeatures().contains(Connection::FeatureSimplePresence)) {
        return mPriv->connection->lowlevel()->maxPresenceStatusMessageLength();
    }

    return 0;
}

/**
 * Return the presence status that this account will have set on it by the
 * account manager if it brings it online automatically.
 *
 * Change notification is via the automaticPresenceChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The automatic presence as a Presence object.
 * \sa automaticPresenceChanged(), setAutomaticPresence()
 */
Presence Account::automaticPresence() const
{
    return mPriv->automaticPresence;
}

/**
 * Set the presence status that this account should have if it is brought
 * online automatically by the account manager.
 *
 * Note that changing this property won't actually change the account's status
 * until the next time it is (re)connected for some reason.
 *
 * The value of this property must be one that would be acceptable for setRequestedPresence(),
 * as returned by allowedPresenceStatuses(), with the additional restriction that the offline
 * presence cannot be used.
 *
 * \param presence The presence to set when this account is brought
 *                 online automatically by the account manager.
 * \return A PendingOperation which will emit PendingOperation::finished
 *         when the request has been made.
 * \sa automaticPresenceChanged(), automaticPresence(), setRequestedPresence()
 */
PendingOperation *Account::setAutomaticPresence(const Presence &presence)
{
    return new PendingVoid(
            mPriv->properties->Set(
                TP_QT_IFACE_ACCOUNT,
                QLatin1String("AutomaticPresence"),
                QDBusVariant(QVariant::fromValue(presence.barePresence()))),
            AccountPtr(this));
}

/**
 * Return the actual presence of this account.
 *
 * Change notification is via the currentPresenceChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The current presence as a Presence object.
 * \sa currentPresenceChanged(), setRequestedPresence(), requestedPresence(), automaticPresence()
 */
Presence Account::currentPresence() const
{
    return mPriv->currentPresence;
}

/**
 * Return the requested presence of this account.
 *
 * Change notification is via the requestedPresenceChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The requested presence as a Presence object.
 * \sa requestedPresenceChanged(), setRequestedPresence(), currentPresence(), automaticPresence()
 */
Presence Account::requestedPresence() const
{
    return mPriv->requestedPresence;
}

/**
 * Set the requested presence of this account.
 *
 * When the requested presence is changed, the account manager will attempt to
 * manipulate the connection to make currentPresence() match requestedPresence()
 * as closely as possible.
 *
 * \param presence The requested presence.
 * \return A PendingOperation which will emit PendingOperation::finished
 *         when the request has been made.
 * \sa requestedPresenceChanged(), currentPresence(), automaticPresence(), setAutomaticPresence()
 */
PendingOperation *Account::setRequestedPresence(const Presence &presence)
{
    return new PendingVoid(
            mPriv->properties->Set(
                TP_QT_IFACE_ACCOUNT,
                QLatin1String("RequestedPresence"),
                QDBusVariant(QVariant::fromValue(presence.barePresence()))),
            AccountPtr(this));
}

/**
 * Return whether this account is online.
 *
 * Change notification is via the onlinenessChanged() signal.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return \c true if online, otherwise \c false.
 * \sa onlinenessChanged()
 */
bool Account::isOnline() const
{
    return mPriv->currentPresence.type() != ConnectionPresenceTypeOffline;
}

/**
 * Return the unique identifier of this account.
 *
 * \return The unique identifier.
 */
QString Account::uniqueIdentifier() const
{
    QString path = objectPath();
    return path.right(path.length() -
            strlen("/org/freedesktop/Telepathy/Account/"));
}

/**
 * Return the normalized user ID of the local user of this account.
 *
 * It is unspecified whether this user ID is globally unique.
 *
 * As currently implemented, IRC user IDs are only unique within the same
 * IRCnet. On some saner protocols, the user ID includes a DNS name which
 * provides global uniqueness.
 *
 * If this value is not known yet (which will always be the case for accounts
 * that have never been online), it will be an empty string.
 *
 * It is possible that this value will change if the connection manager's
 * normalization algorithm changes.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return The normalized user ID of the local user.
 * \sa normalizedNameChanged()
 */
QString Account::normalizedName() const
{
    return mPriv->normalizedName;
}

/**
 * If this account is currently connected, disconnect and reconnect it. If it
 * is currently trying to connect, cancel the attempt to connect and start
 * another. If it is currently disconnected, do nothing.
 *
 * \return A PendingOperation which will emit PendingOperation::finished
 *         when the request has been made.
 */
PendingOperation *Account::reconnect()
{
    return new PendingVoid(baseInterface()->Reconnect(), AccountPtr(this));
}

/**
 * Delete this account.
 *
 * \return A PendingOperation which will emit PendingOperation::finished
 *         when the request has been made.
 * \sa removed()
 */
PendingOperation *Account::remove()
{
    return new PendingVoid(baseInterface()->Remove(), AccountPtr(this));
}

/**
 * Return whether passing hints on channel requests on this account is known to be supported.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return \c true if supported, \c false otherwise.
 */
bool Account::supportsRequestHints() const
{
    return mPriv->dispatcherContext->supportsHints;
}

/**
 * Return whether the ChannelRequest::succeeded(const Tp::ChannelPtr &channel) signal is expected to
 * be emitted with a non-NULL channel parameter for requests made using this account.
 *
 * This can be used as a run-time check for the Channel Dispatcher implementation being new enough.
 * In particular, similarly old Channel Dispatchers don't support request hints either, so the
 * return value for this function and Account::supportsRequestHints() will bet he same.
 *
 * This method requires Account::FeatureCore to be ready.
 *
 * \return \c true if supported, \c false otherwise.
 */
bool Account::requestsSucceedWithChannel() const
{
    return supportsRequestHints();
}

/**
 * Start a request to ensure that a text channel with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * \param contactIdentifier The identifier of the contact to chat with.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureTextChat(
        const QString &contactIdentifier,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = textChatRequest(contactIdentifier);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that a text channel with the given
 * contact \a contact exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * \param contact The contact to chat with.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureTextChat(
        const ContactPtr &contact,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = textChatRequest(contact);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that a text chat room with the given
 * room name \a roomName exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * \param roomName The name of the chat room.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureTextChatroom(
        const QString &roomName,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = textChatroomRequest(roomName);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that an audio call channel with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * \param contactIdentifier The identifier of the contact to call.
 * \param initialAudioContentName The name of the initial CallContent that will
 *                                be automatically added on the channel.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureAudioCall(
        const QString &contactIdentifier,
        const QString &initialAudioContentName,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = audioCallRequest(contactIdentifier, initialAudioContentName);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that an audio call channel with the given
 * contact \a contact exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * \param contact The contact to call.
 * \param initialAudioContentName The name of the initial audio CallContent that
 *                                will be automatically added on the channel.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest* Account::ensureAudioCall(
        const ContactPtr &contact,
        const QString &initialAudioContentName,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = audioCallRequest(contact, initialAudioContentName);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that a video call channel with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * \param contactIdentifier The identifier of the contact to call.
 * \param initialVideoContentName The name of the initial video CallContent that
 *                                will be automatically added on the channel.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureVideoCall(
        const QString &contactIdentifier,
        const QString &initialVideoContentName,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = videoCallRequest(contactIdentifier, initialVideoContentName);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that a video call channel with the given
 * contact \a contact exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * \param contact The contact to call.
 * \param initialVideoContentName The name of the initial video CallContent that
 *                                will be automatically added on the channel.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureVideoCall(
        const ContactPtr &contact,
        const QString &initialVideoContentName,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = videoCallRequest(contact, initialVideoContentName);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that an audio/video call channel with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * \param contactIdentifier The identifier of the contact to call.
 * \param initialAudioContentName The name of the initial audio CallContent that
 *                                will be automatically added on the channel.
 * \param initialVideoContentName The name of the initial video CallContent that
 *                                will be automatically added on the channel.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureAudioVideoCall(
        const QString &contactIdentifier,
        const QString &initialAudioContentName,
        const QString &initialVideoContentName,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = audioVideoCallRequest(contactIdentifier,
            initialAudioContentName, initialVideoContentName);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that an audio/video call channel with the given
 * contact \a contact exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * \param contact The contact to call.
 * \param initialAudioContentName The name of the initial audio CallContent that
 *                                will be automatically added on the channel.
 * \param initialVideoContentName The name of the initial video CallContent that
 *                                will be automatically added on the channel.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureAudioVideoCall(
        const ContactPtr &contact,
        const QString &initialAudioContentName,
        const QString &initialVideoContentName,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = audioVideoCallRequest(contact,
            initialAudioContentName, initialVideoContentName);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that a media channel with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * \param contactIdentifier The identifier of the contact to call.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureStreamedMediaCall(
        const QString &contactIdentifier,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = streamedMediaCallRequest(contactIdentifier);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that a media channel with the given
 * contact \a contact exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * \param contact The contact to call.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureStreamedMediaCall(
        const ContactPtr &contact,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = streamedMediaCallRequest(contact);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that an audio call with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * This will only work on relatively modern connection managers,
 * like telepathy-gabble 0.9.0 or later.
 *
 * \param contactIdentifier The identifier of the contact to call.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureStreamedMediaAudioCall(
        const QString &contactIdentifier,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = streamedMediaAudioCallRequest(contactIdentifier);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that an audio call with the given
 * contact \a contact exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * This will only work on relatively modern connection managers,
 * like telepathy-gabble 0.9.0 or later.
 *
 * \param contact The contact to call.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureStreamedMediaAudioCall(
        const ContactPtr &contact,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = streamedMediaAudioCallRequest(contact);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that a video call with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * This will only work on relatively modern connection managers,
 * like telepathy-gabble 0.9.0 or later.
 *
 * \param contactIdentifier The identifier of the contact to call.
 * \param withAudio true if both audio and video are required, false for a
 *                  video-only call.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureStreamedMediaVideoCall(
        const QString &contactIdentifier,
        bool withAudio,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = streamedMediaVideoCallRequest(contactIdentifier, withAudio);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to ensure that a video call with the given
 * contact \a contact exists, creating it if necessary.
 *
 * See ensureChannel() for more details.
 *
 * This will only work on relatively modern connection managers,
 * like telepathy-gabble 0.9.0 or later.
 *
 * \param contact The contact to call.
 * \param withAudio true if both audio and video are required, false for a
 *                  video-only call.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::ensureStreamedMediaVideoCall(
        const ContactPtr &contact,
        bool withAudio,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = streamedMediaVideoCallRequest(contact, withAudio);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to create a file transfer channel with the given
 * contact \a contact.
 *
 * \param contactIdentifier The identifier of the contact to send a file.
 * \param properties The desired properties.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::createFileTransfer(
        const QString &contactIdentifier,
        const FileTransferChannelCreationProperties &properties,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = fileTransferRequest(contactIdentifier, properties);

    if (request.isEmpty()) {
        return new PendingChannelRequest(AccountPtr(this), TP_QT_ERROR_INVALID_ARGUMENT,
                QLatin1String("Cannot create a file transfer with invalid parameters"));
    }

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

/**
 * Start a request to create a file transfer channel with the given
 * contact \a contact.
 *
 * \param contact The contact to send a file.
 * \param properties The desired properties.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::createFileTransfer(
        const ContactPtr &contact,
        const FileTransferChannelCreationProperties &properties,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = fileTransferRequest(contact, properties);

    if (request.isEmpty()) {
        return new PendingChannelRequest(AccountPtr(this), TP_QT_ERROR_INVALID_ARGUMENT,
                QLatin1String("Cannot create a file transfer with invalid parameters"));
    }

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

/**
 * Start a request to create a stream tube channel with the given
 * contact identifier \a contactIdentifier.
 *
 * \param contactIdentifier The identifier of the contact to open a stream tube with.
 * \param service The stream tube service.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::createStreamTube(
        const QString &contactIdentifier,
        const QString &service,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = streamTubeRequest(contactIdentifier, service);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

/**
 * Start a request to create a stream tube channel with the given
 * contact \a contact.
 *
 * \param contact The contact to open a stream tube with.
 * \param service The stream tube service.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::createStreamTube(
        const ContactPtr &contact,
        const QString &service,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = streamTubeRequest(contact, service);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

/**
 * Start a request to create a DBus tube channel with the given
 * contact \a contactIdentifier.
 *
 * \param contactIdentifier The contact identifier of the contact to open a DBus tube with.
 * \param serviceName the service name that will be used over the
 *                    tube. It should be a well-known D-Bus service name, of the form
 *                    \c com.example.ServiceName
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the call has finished.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::createDBusTube(
        const QString &contactIdentifier,
        const QString &serviceName,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = dbusTubeRequest(contactIdentifier, serviceName);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}


/**
 * Start a request to create a DBus tube channel with the given
 * contact \a contact.
 *
 * \param contact The contact to open a DBus tube with.
 * \param serviceName the service name that will be used over the
 *                    tube. It should be a well-known D-Bus service name, of the form
 *                    \c com.example.ServiceName
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the call has finished.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest* Account::createDBusTube(
        const Tp::ContactPtr& contact,
        const QString& serviceName,
        const QDateTime& userActionTime,
        const QString& preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = dbusTubeRequest(contact, serviceName);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

PendingChannelRequest* Account::createDBusTubeRoom(
        const QString &room,
        const QString &serviceName,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = dbusTubeRoomRequest(room, serviceName);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
        preferredHandler, true, hints);
}

/**
 * Start a request to create a conference media call with the given
 * channels \a channels.
 *
 * \param channels The conference channels.
 * \param initialInviteeContactsIdentifiers A list of additional contacts
 *                                          identifiers to be invited to this
 *                                          conference when it is created.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::createConferenceStreamedMediaCall(
        const QList<ChannelPtr> &channels,
        const QStringList &initialInviteeContactsIdentifiers,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = conferenceStreamedMediaCallRequest(channels,
            initialInviteeContactsIdentifiers);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

/**
 * Start a request to create a conference media call with the given
 * channels \a channels.
 *
 * \param channels The conference channels.
 * \param initialInviteeContacts A list of additional contacts
 *                               to be invited to this
 *                               conference when it is created.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::createConferenceStreamedMediaCall(
        const QList<ChannelPtr> &channels,
        const QList<ContactPtr> &initialInviteeContacts,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = conferenceStreamedMediaCallRequest(channels, initialInviteeContacts);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

/**
 * Start a request to create a conference text chat with the given
 * channels \a channels.
 *
 * \param channels The conference channels.
 * \param initialInviteeContactsIdentifiers A list of additional contacts
 *                                          identifiers to be invited to this
 *                                          conference when it is created.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::createConferenceTextChat(
        const QList<ChannelPtr> &channels,
        const QStringList &initialInviteeContactsIdentifiers,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = conferenceTextChatRequest(channels, initialInviteeContactsIdentifiers);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

/**
 * Start a request to create a conference text chat with the given
 * channels \a channels.
 *
 * \param channels The conference channels.
 * \param initialInviteeContacts A list of additional contacts
 *                               to be invited to this
 *                               conference when it is created.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::createConferenceTextChat(
        const QList<ChannelPtr> &channels,
        const QList<ContactPtr> &initialInviteeContacts,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = conferenceTextChatRequest(channels, initialInviteeContacts);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

/**
 * Start a request to create a conference text chat room with the given
 * channels \a channels and room name \a roomName.
 *
 * \param roomName The room name.
 * \param channels The conference channels.
 * \param initialInviteeContactsIdentifiers A list of additional contacts
 *                                          identifiers to be invited to this
 *                                          conference when it is created.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::createConferenceTextChatroom(
        const QString &roomName,
        const QList<ChannelPtr> &channels,
        const QStringList &initialInviteeContactsIdentifiers,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = conferenceTextChatroomRequest(roomName, channels,
            initialInviteeContactsIdentifiers);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

/**
 * Start a request to create a conference text chat room with the given
 * channels \a channels and room name \a roomName.
 *
 * \param roomName The room name.
 * \param channels The conference channels.
 * \param initialInviteeContacts A list of additional contacts
 *                               to be invited to this
 *                               conference when it is created.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa ensureChannel(), createChannel()
 */
PendingChannelRequest *Account::createConferenceTextChatroom(
        const QString &roomName,
        const QList<ChannelPtr> &channels,
        const QList<ContactPtr> &initialInviteeContacts,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = conferenceTextChatroomRequest(roomName, channels,
            initialInviteeContacts);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

/**
 * Start a request to create a contact search channel with the given
 * server \a server and limit \a limit.
 *
 * \param server For protocols which support searching for contacts on multiple servers with
 *               different DNS names (like XMPP), the DNS name of the server to be searched,
 *               e.g. "characters.shakespeare.lit". Otherwise, an empty string.
 * \param limit The desired maximum number of results that should be returned by a doing a search.
 *              If the protocol does not support specifying a limit for the number of results
 *              returned at a time, this will be ignored.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa createChannel()
 */
PendingChannelRequest *Account::createContactSearch(
        const QString &server,
        uint limit,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    QVariantMap request = contactSearchRequest(capabilities(), server, limit);

    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

/**
 * Start a request to ensure that a text channel with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contactIdentifier The identifier of the contact to chat with.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleTextChat(
        const QString &contactIdentifier,
        const QDateTime &userActionTime)
{
    QVariantMap request = textChatRequest(contactIdentifier);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that a text channel with the given
 * contact \a contact exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contact The contact to chat with.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleTextChat(
        const ContactPtr &contact,
        const QDateTime &userActionTime)
{
    QVariantMap request = textChatRequest(contact);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that a text chat room with the given
 * room name \a roomName exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param roomName The name of the chat room.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleTextChatroom(
        const QString &roomName,
        const QDateTime &userActionTime)
{
    QVariantMap request = textChatroomRequest(roomName);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that an audio call channel with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contactIdentifier The identifier of the contact to call.
 * \param initialAudioContentName The name of the initial audio CallContent that
 *                                will be automatically added on the channel.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleAudioCall(
        const QString &contactIdentifier,
        const QString &initialAudioContentName,
        const QDateTime &userActionTime)
{
    QVariantMap request = audioCallRequest(contactIdentifier, initialAudioContentName);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that an audio call channel with the given
 * contact \a contact exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contact The contact to call.
 * \param initialAudioContentName The name of the initial audio CallContent that
 *                                will be automatically added on the channel.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleAudioCall(
        const ContactPtr &contact,
        const QString &initialAudioContentName,
        const QDateTime &userActionTime)
{
    QVariantMap request = audioCallRequest(contact, initialAudioContentName);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that a video call channel with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contactIdentifier The identifier of the contact to call.
 * \param initialVideoContentName The name of the initial video CallContent that
 *                                will be automatically added on the channel.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleVideoCall(
        const QString &contactIdentifier,
        const QString &initialVideoContentName,
        const QDateTime &userActionTime)
{
    QVariantMap request = videoCallRequest(contactIdentifier, initialVideoContentName);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that a video call channel with the given
 * contact \a contact exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contact The contact to call.
 * \param initialVideoContentName The name of the initial video CallContent that
 *                                will be automatically added on the channel.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleVideoCall(
        const ContactPtr &contact,
        const QString &initialVideoContentName,
        const QDateTime &userActionTime)
{
    QVariantMap request = videoCallRequest(contact, initialVideoContentName);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that an audio/video call channel with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contactIdentifier The identifier of the contact to call.
 * \param initialAudioContentName The name of the initial audio CallContent that
 *                                will be automatically added on the channel.
 * \param initialVideoContentName The name of the initial video CallContent that
 *                                will be automatically added on the channel.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleAudioVideoCall(
        const QString &contactIdentifier,
        const QString &initialAudioContentName,
        const QString &initialVideoContentName,
        const QDateTime &userActionTime)
{
    QVariantMap request = audioVideoCallRequest(contactIdentifier,
            initialAudioContentName, initialVideoContentName);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that an audio/video call channel with the given
 * contact \a contact exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contact The contact to call.
 * \param initialAudioContentName The name of the initial audio CallContent that
 *                                will be automatically added on the channel.
 * \param initialVideoContentName The name of the initial video CallContent that
 *                                will be automatically added on the channel.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleAudioVideoCall(
        const ContactPtr &contact,
        const QString &initialAudioContentName,
        const QString &initialVideoContentName,
        const QDateTime &userActionTime)
{
    QVariantMap request = audioVideoCallRequest(contact,
            initialAudioContentName, initialVideoContentName);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that a media channel with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contactIdentifier The identifier of the contact to call.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleStreamedMediaCall(
        const QString &contactIdentifier,
        const QDateTime &userActionTime)
{
    QVariantMap request = streamedMediaCallRequest(contactIdentifier);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that a media channel with the given
 * contact \a contact exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contact The contact to call.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleStreamedMediaCall(
        const ContactPtr &contact,
        const QDateTime &userActionTime)
{
    QVariantMap request = streamedMediaCallRequest(contact);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that an audio call with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * This will only work on relatively modern connection managers,
 * like telepathy-gabble 0.9.0 or later.
 *
 * \param contactIdentifier The identifier of the contact to call.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleStreamedMediaAudioCall(
        const QString &contactIdentifier,
        const QDateTime &userActionTime)
{
    QVariantMap request = streamedMediaAudioCallRequest(contactIdentifier);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that an audio call with the given
 * contact \a contact exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * This will only work on relatively modern connection managers,
 * like telepathy-gabble 0.9.0 or later.
 *
 * \param contact The contact to call.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleStreamedMediaAudioCall(
        const ContactPtr &contact,
        const QDateTime &userActionTime)
{
    QVariantMap request = streamedMediaAudioCallRequest(contact);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that a video call with the given
 * contact \a contactIdentifier exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * This will only work on relatively modern connection managers,
 * like telepathy-gabble 0.9.0 or later.
 *
 * \param contactIdentifier The identifier of the contact to call.
 * \param withAudio true if both audio and video are required, false for a
 *                  video-only call.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleStreamedMediaVideoCall(
        const QString &contactIdentifier,
        bool withAudio,
        const QDateTime &userActionTime)
{
    QVariantMap request = streamedMediaVideoCallRequest(contactIdentifier, withAudio);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to ensure that a video call with the given
 * contact \a contact exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * This will only work on relatively modern connection managers,
 * like telepathy-gabble 0.9.0 or later.
 *
 * \param contact The contact to call.
 * \param withAudio true if both audio and video are required, false for a
 *                  video-only call.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleStreamedMediaVideoCall(
        const ContactPtr &contact,
        bool withAudio,
        const QDateTime &userActionTime)
{
    QVariantMap request = streamedMediaVideoCallRequest(contact, withAudio);

    return ensureAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a file transfer channel with the given
 * contact \a contactIdentifier.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contactIdentifier The identifier of the contact to send a file.
 * \param properties The desired properties.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleFileTransfer(
        const QString &contactIdentifier,
        const FileTransferChannelCreationProperties &properties,
        const QDateTime &userActionTime)
{
    QVariantMap request = fileTransferRequest(contactIdentifier, properties);

    if (request.isEmpty()) {
        return new PendingChannel(TP_QT_ERROR_INVALID_ARGUMENT,
                QLatin1String("Cannot create a file transfer with invalid parameters"));
    }

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a file transfer channel with the given
 * contact \a contact.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contact The contact to send a file.
 * \param properties The desired properties.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleFileTransfer(
        const ContactPtr &contact,
        const FileTransferChannelCreationProperties &properties,
        const QDateTime &userActionTime)
{
    QVariantMap request = fileTransferRequest(contact, properties);

    if (request.isEmpty()) {
        return new PendingChannel(TP_QT_ERROR_INVALID_ARGUMENT,
                QLatin1String("Cannot create a file transfer with invalid parameters"));
    }

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a stream tube channel with the given
 * contact identifier \a contactIdentifier.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contactIdentifier The identifier of the contact to open a stream tube with.
 * \param service The stream tube service.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleStreamTube(
        const QString &contactIdentifier,
        const QString &service,
        const QDateTime &userActionTime)
{
    QVariantMap request = streamTubeRequest(contactIdentifier, service);

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a stream tube channel with the given
 * contact \a contact.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contact The contact to open a stream tube with.
 * \param service The stream tube service.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleStreamTube(
        const ContactPtr &contact,
        const QString &service,
        const QDateTime &userActionTime)
{
    QVariantMap request = streamTubeRequest(contact, service);

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a DBus tube channel with the given
 * contact identifier \a contactIdentifier.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contactIdentifier The identifier of the contact to open a DBus tube with.
 * \param serviceName The DBus tube service name.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleDBusTube(
        const QString &contactIdentifier,
        const QString &serviceName,
        const QDateTime &userActionTime)
{
    QVariantMap request = dbusTubeRequest(contactIdentifier, serviceName);

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a DBus tube channel with the given
 * contact \a contact.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param contact The contact to open a DBus tube with.
 * \param service The DBus tube service name.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleDBusTube(
        const ContactPtr &contact,
        const QString &serviceName,
        const QDateTime &userActionTime)
{
    QVariantMap request = dbusTubeRequest(contact, serviceName);

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a conference text chat with the given
 * channels \a channels.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param channels The conference channels.
 * \param initialInviteeContactsIdentifiers A list of additional contacts
 *                                          identifiers to be invited to this
 *                                          conference when it is created.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleConferenceTextChat(
        const QList<ChannelPtr> &channels,
        const QStringList &initialInviteeContactsIdentifiers,
        const QDateTime &userActionTime)
{
    QVariantMap request = conferenceTextChatRequest(channels, initialInviteeContactsIdentifiers);

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a conference text chat with the given
 * channels \a channels.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param channels The conference channels.
 * \param initialInviteeContacts A list of additional contacts
 *                               to be invited to this
 *                               conference when it is created.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleConferenceTextChat(
        const QList<ChannelPtr> &channels,
        const QList<ContactPtr> &initialInviteeContacts,
        const QDateTime &userActionTime)
{
    QVariantMap request = conferenceTextChatRequest(channels, initialInviteeContacts);

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a conference text chat room with the given
 * channels \a channels and room name \a roomName.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param roomName The room name.
 * \param channels The conference channels.
 * \param initialInviteeContactsIdentifiers A list of additional contacts
 *                                          identifiers to be invited to this
 *                                          conference when it is created.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleConferenceTextChatroom(
        const QString &roomName,
        const QList<ChannelPtr> &channels,
        const QStringList &initialInviteeContactsIdentifiers,
        const QDateTime &userActionTime)
{
    QVariantMap request = conferenceTextChatroomRequest(roomName, channels,
            initialInviteeContactsIdentifiers);

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a conference text chat room with the given
 * channels \a channels and room name \a roomName.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param roomName The room name.
 * \param channels The conference channels.
 * \param initialInviteeContacts A list of additional contacts
 *                               to be invited to this
 *                               conference when it is created.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleConferenceTextChatroom(
        const QString &roomName,
        const QList<ChannelPtr> &channels,
        const QList<ContactPtr> &initialInviteeContacts,
        const QDateTime &userActionTime)
{
    QVariantMap request = conferenceTextChatroomRequest(roomName, channels,
            initialInviteeContacts);

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a conference media call with the given
 * channels \a channels.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param channels The conference channels.
 * \param initialInviteeContactsIdentifiers A list of additional contacts
 *                                          identifiers to be invited to this
 *                                          conference when it is created.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleConferenceStreamedMediaCall(
        const QList<ChannelPtr> &channels,
        const QStringList &initialInviteeContactsIdentifiers,
        const QDateTime &userActionTime)
{
    QVariantMap request = conferenceStreamedMediaCallRequest(channels,
            initialInviteeContactsIdentifiers);

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a conference media call with the given
 * channels \a channels.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param channels The conference channels.
 * \param initialInviteeContacts A list of additional contacts
 *                               to be invited to this
 *                               conference when it is created.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleConferenceStreamedMediaCall(
        const QList<ChannelPtr> &channels,
        const QList<ContactPtr> &initialInviteeContacts,
        const QDateTime &userActionTime)
{
    QVariantMap request = conferenceStreamedMediaCallRequest(channels, initialInviteeContacts);

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a contact search channel with the given
 * server \a server and limit \a limit.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * \param server For protocols which support searching for contacts on multiple servers with
 *               different DNS names (like XMPP), the DNS name of the server to be searched,
 *               e.g. "characters.shakespeare.lit". Otherwise, an empty string.
 *               If the protocol does not support specifying a search server, this will be ignored.
 * \param limit The desired maximum number of results that should be returned by a doing a search.
 *              If the protocol does not support specifying a limit for the number of results
 *              returned at a time, this will be ignored.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel(), createAndHandleChannel()
 */
PendingChannel *Account::createAndHandleContactSearch(
        const QString &server,
        uint limit,
        const QDateTime &userActionTime)
{
    QVariantMap request = contactSearchRequest(capabilities(), server, limit);

    return createAndHandleChannel(request, userActionTime);
}

/**
 * Start a request to create a channel.
 * This initially just creates a PendingChannelRequest object,
 * which can be used to track the success or failure of the request,
 * or to cancel it.
 *
 * Helper methods for text chat, text chat room, media call and conference are
 * provided and should be used if appropriate.
 *
 * \param request A dictionary containing desirable properties.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa createChannel()
 */
PendingChannelRequest *Account::createChannel(
        const QVariantMap &request,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, true, hints);
}

/**
 * Start a request to ensure that a channel exists, creating it if necessary.
 * This initially just creates a PendingChannelRequest object,
 * which can be used to track the success or failure of the request,
 * or to cancel it.
 *
 * Helper methods for text chat, text chat room, media call and conference are
 * provided and should be used if appropriate.
 *
 * \param request A dictionary containing desirable properties.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param hints Arbitrary metadata which will be relayed to the handler if supported,
 *              as indicated by supportsRequestHints().
 * \return A PendingChannelRequest which will emit PendingChannelRequest::finished
 *         when the request has been made.
 * \sa createChannel()
 */
PendingChannelRequest *Account::ensureChannel(
        const QVariantMap &request,
        const QDateTime &userActionTime,
        const QString &preferredHandler,
        const ChannelRequestHints &hints)
{
    return new PendingChannelRequest(AccountPtr(this), request, userActionTime,
            preferredHandler, false, hints);
}

/**
 * Start a request to create channel.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * Helper methods for text chat, text chat room, media call and conference are
 * provided and should be used if appropriate.
 *
 * The caller is responsible for closing the channel with
 * Channel::requestClose() or Channel::requestLeave() when it has finished handling it.
 *
 * A possible error returned by this method is #TP_QT_ERROR_NOT_AVAILABLE, in case a conflicting
 * channel that matches \a request already exists.
 *
 * \param request A dictionary containing desirable properties.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa ensureAndHandleChannel()
 */
PendingChannel *Account::createAndHandleChannel(
        const QVariantMap &request,
        const QDateTime &userActionTime)
{
    return new PendingChannel(AccountPtr(this), request, userActionTime, true);
}

/**
 * Start a request to ensure that a channel exists, creating it if necessary.
 * This initially just creates a PendingChannel object,
 * which can be used to track the success or failure of the request.
 *
 * Helper methods for text chat, text chat room, media call and conference are
 * provided and should be used if appropriate.
 *
 * The caller is responsible for closing the channel with
 * Channel::requestClose() or Channel::requestLeave() when it has finished handling it.
 *
 * A possible error returned by this method is #TP_QT_ERROR_NOT_YOURS, in case somebody else is
 * already handling a channel that matches \a request.
 *
 * \param request A dictionary containing desirable properties.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \return A PendingChannel which will emit PendingChannel::finished
 *         successfully, when the Channel is available for handling using
 *         PendingChannel::channel(), or with an error if one has been encountered.
 * \sa createAndHandleChannel()
 */
PendingChannel *Account::ensureAndHandleChannel(
        const QVariantMap &request,
        const QDateTime &userActionTime)
{
    return new PendingChannel(AccountPtr(this), request, userActionTime, false);
}

/**
 * Return the Client::AccountInterface interface proxy object for this account.
 * This method is protected since the convenience methods provided by this
 * class should generally be used instead of calling D-Bus methods
 * directly.
 *
 * \return A pointer to the existing Client::AccountInterface object for this
 *         Account object.
 */
Client::AccountInterface *Account::baseInterface() const
{
    return mPriv->baseInterface;
}

/**
 * Return the Client::ChannelDispatcherInterface interface proxy object to use for requesting
 * channels on this account.
 *
 * This method is protected since the convenience methods provided by this
 * class should generally be used instead of calling D-Bus methods
 * directly.
 *
 * \return A pointer to the existing Client::ChannelDispatcherInterface object for this
 *         Account object.
 */
Client::ChannelDispatcherInterface *Account::dispatcherInterface() const
{
    return mPriv->dispatcherContext->iface;
}

/**** Private ****/
void Account::Private::init()
{
    if (!parent->isValid()) {
        return;
    }

    parent->connect(baseInterface,
            SIGNAL(Removed()),
            SLOT(onRemoved()));
    parent->connect(baseInterface,
            SIGNAL(AccountPropertyChanged(QVariantMap)),
            SLOT(onPropertyChanged(QVariantMap)));
}

void Account::Private::introspectMain(Account::Private *self)
{
    if (self->dispatcherContext->introspected) {
        self->parent->onDispatcherIntrospected(0);
        return;
    }

    if (!self->dispatcherContext->introspectOp) {
        debug() << "Discovering if the Channel Dispatcher supports request hints";
        self->dispatcherContext->introspectOp =
            self->dispatcherContext->iface->requestPropertySupportsRequestHints();
    }

    connect(self->dispatcherContext->introspectOp.data(),
            SIGNAL(finished(Tp::PendingOperation*)),
            self->parent,
            SLOT(onDispatcherIntrospected(Tp::PendingOperation*)));
}

void Account::Private::introspectAvatar(Account::Private *self)
{
    debug() << "Calling GetAvatar(Account)";
    // we already checked if avatar interface exists, so bypass avatar interface
    // checking
    Client::AccountInterfaceAvatarInterface *iface =
        self->parent->interface<Client::AccountInterfaceAvatarInterface>();

    // If we are here it means the user cares about avatar, so
    // connect to avatar changed signal, so we update the avatar
    // when it changes.
    self->parent->connect(iface,
            SIGNAL(AvatarChanged()),
            SLOT(onAvatarChanged()));

    self->retrieveAvatar();
}

void Account::Private::introspectProtocolInfo(Account::Private *self)
{
    Q_ASSERT(!self->cm);

    self->cm = ConnectionManager::create(
            self->parent->dbusConnection(), self->cmName,
            self->connFactory, self->chanFactory, self->contactFactory);
    self->parent->connect(self->cm->becomeReady(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onConnectionManagerReady(Tp::PendingOperation*)));
}

void Account::Private::introspectCapabilities(Account::Private *self)
{
    if (!self->connection) {
        // there is no connection, just make capabilities ready
        self->readinessHelper->setIntrospectCompleted(FeatureCapabilities, true);
        return;
    }

    self->parent->connect(self->connection->becomeReady(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onConnectionReady(Tp::PendingOperation*)));
}

void Account::Private::updateProperties(const QVariantMap &props)
{
    debug() << "Account::updateProperties: changed:";

    if (props.contains(QLatin1String("Interfaces"))) {
        parent->setInterfaces(qdbus_cast<QStringList>(props[QLatin1String("Interfaces")]));
        debug() << " Interfaces:" << parent->interfaces();
    }

    QString oldIconName = parent->iconName();
    bool serviceNameChanged = false;
    bool profileChanged = false;
    if (props.contains(QLatin1String("Service")) &&
        serviceName != qdbus_cast<QString>(props[QLatin1String("Service")])) {
        serviceNameChanged = true;
        serviceName = qdbus_cast<QString>(props[QLatin1String("Service")]);
        debug() << " Service Name:" << parent->serviceName();
        /* use parent->serviceName() here as if the service name is empty we are going to use the
         * protocol name */
        emit parent->serviceNameChanged(parent->serviceName());
        parent->notify("serviceName");

        /* if we had a profile and the service changed, it means the profile also changed */
        if (parent->isReady(Account::FeatureProfile)) {
            /* service name changed, let's recreate profile */
            profileChanged = true;
            profile.reset();
            emit parent->profileChanged(parent->profile());
            parent->notify("profile");
        }
    }

    if (props.contains(QLatin1String("DisplayName")) &&
        displayName != qdbus_cast<QString>(props[QLatin1String("DisplayName")])) {
        displayName = qdbus_cast<QString>(props[QLatin1String("DisplayName")]);
        debug() << " Display Name:" << displayName;
        emit parent->displayNameChanged(displayName);
        parent->notify("displayName");
    }

    if ((props.contains(QLatin1String("Icon")) &&
         oldIconName != qdbus_cast<QString>(props[QLatin1String("Icon")])) ||
        serviceNameChanged) {

        if (props.contains(QLatin1String("Icon"))) {
            iconName = qdbus_cast<QString>(props[QLatin1String("Icon")]);
        }

        QString newIconName = parent->iconName();
        if (oldIconName != newIconName) {
            debug() << " Icon:" << newIconName;
            emit parent->iconNameChanged(newIconName);
            parent->notify("iconName");
        }
    }

    if (props.contains(QLatin1String("Nickname")) &&
        nickname != qdbus_cast<QString>(props[QLatin1String("Nickname")])) {
        nickname = qdbus_cast<QString>(props[QLatin1String("Nickname")]);
        debug() << " Nickname:" << nickname;
        emit parent->nicknameChanged(nickname);
        parent->notify("nickname");
    }

    if (props.contains(QLatin1String("NormalizedName")) &&
        normalizedName != qdbus_cast<QString>(props[QLatin1String("NormalizedName")])) {
        normalizedName = qdbus_cast<QString>(props[QLatin1String("NormalizedName")]);
        debug() << " Normalized Name:" << normalizedName;
        emit parent->normalizedNameChanged(normalizedName);
        parent->notify("normalizedName");
    }

    if (props.contains(QLatin1String("Valid")) &&
        valid != qdbus_cast<bool>(props[QLatin1String("Valid")])) {
        valid = qdbus_cast<bool>(props[QLatin1String("Valid")]);
        debug() << " Valid:" << (valid ? "true" : "false");
        emit parent->validityChanged(valid);
        parent->notify("valid");
    }

    if (props.contains(QLatin1String("Enabled")) &&
        enabled != qdbus_cast<bool>(props[QLatin1String("Enabled")])) {
        enabled = qdbus_cast<bool>(props[QLatin1String("Enabled")]);
        debug() << " Enabled:" << (enabled ? "true" : "false");
        emit parent->stateChanged(enabled);
        parent->notify("enabled");
    }

    if (props.contains(QLatin1String("ConnectAutomatically")) &&
        connectsAutomatically !=
                qdbus_cast<bool>(props[QLatin1String("ConnectAutomatically")])) {
        connectsAutomatically =
                qdbus_cast<bool>(props[QLatin1String("ConnectAutomatically")]);
        debug() << " Connects Automatically:" << (connectsAutomatically ? "true" : "false");
        emit parent->connectsAutomaticallyPropertyChanged(connectsAutomatically);
        parent->notify("connectsAutomatically");
    }

    if (props.contains(QLatin1String("HasBeenOnline")) &&
        !hasBeenOnline &&
        qdbus_cast<bool>(props[QLatin1String("HasBeenOnline")])) {
        hasBeenOnline = true;
        debug() << " HasBeenOnline changed to true";
        // don't emit firstOnline unless we're already ready, that would be
        // misleading - we'd emit it just before any already-used account
        // became ready
        if (parent->isReady(Account::FeatureCore)) {
            emit parent->firstOnline();
        }
        parent->notify("hasBeenOnline");
    }

    if (props.contains(QLatin1String("Parameters")) &&
        parameters != qdbus_cast<QVariantMap>(props[QLatin1String("Parameters")])) {
        parameters = qdbus_cast<QVariantMap>(props[QLatin1String("Parameters")]);
        emit parent->parametersChanged(parameters);
        parent->notify("parameters");
    }

    if (props.contains(QLatin1String("AutomaticPresence")) &&
        automaticPresence.barePresence() != qdbus_cast<SimplePresence>(
                props[QLatin1String("AutomaticPresence")])) {
        automaticPresence = Presence(qdbus_cast<SimplePresence>(
                props[QLatin1String("AutomaticPresence")]));
        debug() << " Automatic Presence:" << automaticPresence.type() <<
            "-" << automaticPresence.status();
        emit parent->automaticPresenceChanged(automaticPresence);
        parent->notify("automaticPresence");
    }

    if (props.contains(QLatin1String("CurrentPresence")) &&
        currentPresence.barePresence() != qdbus_cast<SimplePresence>(
                props[QLatin1String("CurrentPresence")])) {
        currentPresence = Presence(qdbus_cast<SimplePresence>(
                props[QLatin1String("CurrentPresence")]));
        debug() << " Current Presence:" << currentPresence.type() <<
            "-" << currentPresence.status();
        emit parent->currentPresenceChanged(currentPresence);
        parent->notify("currentPresence");
        emit parent->onlinenessChanged(parent->isOnline());
        parent->notify("online");
    }

    if (props.contains(QLatin1String("RequestedPresence")) &&
        requestedPresence.barePresence() != qdbus_cast<SimplePresence>(
                props[QLatin1String("RequestedPresence")])) {
        requestedPresence = Presence(qdbus_cast<SimplePresence>(
                props[QLatin1String("RequestedPresence")]));
        debug() << " Requested Presence:" << requestedPresence.type() <<
            "-" << requestedPresence.status();
        emit parent->requestedPresenceChanged(requestedPresence);
        parent->notify("requestedPresence");
    }

    if (props.contains(QLatin1String("ChangingPresence")) &&
        changingPresence != qdbus_cast<bool>(
                props[QLatin1String("ChangingPresence")])) {
        changingPresence = qdbus_cast<bool>(
                props[QLatin1String("ChangingPresence")]);
        debug() << " Changing Presence:" << changingPresence;
        emit parent->changingPresence(changingPresence);
        parent->notify("changingPresence");
    }

    if (props.contains(QLatin1String("Connection"))) {
        QString path = qdbus_cast<QDBusObjectPath>(props[QLatin1String("Connection")]).path();
        if (path.isEmpty()) {
            debug() << " The map contains \"Connection\" but it's empty as a QDBusObjectPath!";
            debug() << " Trying QString (known bug in some MC/dbus-glib versions)";
            path = qdbus_cast<QString>(props[QLatin1String("Connection")]);
        }

        debug() << " Connection Object Path:" << path;
        if (path == QLatin1String("/")) {
            path = QString();
        }

        connObjPathQueue.enqueue(path);

        if (connObjPathQueue.size() == 1) {
            processConnQueue();
        }

        // onConnectionBuilt for a previous path will make sure the path we enqueued is processed if
        // the queue wasn't empty (so is now size() > 1)
    }

    bool connectionStatusChanged = false;
    if (props.contains(QLatin1String("ConnectionStatus")) ||
        props.contains(QLatin1String("ConnectionStatusReason")) ||
        props.contains(QLatin1String("ConnectionError")) ||
        props.contains(QLatin1String("ConnectionErrorDetails"))) {
        ConnectionStatus oldConnectionStatus = connectionStatus;

        if (props.contains(QLatin1String("ConnectionStatus")) &&
            connectionStatus != ConnectionStatus(
                    qdbus_cast<uint>(props[QLatin1String("ConnectionStatus")]))) {
            connectionStatus = ConnectionStatus(
                    qdbus_cast<uint>(props[QLatin1String("ConnectionStatus")]));
            debug() << " Connection Status:" << connectionStatus;
            connectionStatusChanged = true;
        }

        if (props.contains(QLatin1String("ConnectionStatusReason")) &&
            connectionStatusReason != ConnectionStatusReason(
                    qdbus_cast<uint>(props[QLatin1String("ConnectionStatusReason")]))) {
            connectionStatusReason = ConnectionStatusReason(
                    qdbus_cast<uint>(props[QLatin1String("ConnectionStatusReason")]));
            debug() << " Connection StatusReason:" << connectionStatusReason;
            connectionStatusChanged = true;
        }

        if (connectionStatusChanged) {
            parent->notify("connectionStatus");
            parent->notify("connectionStatusReason");
        }

        if (props.contains(QLatin1String("ConnectionError")) &&
            connectionError != qdbus_cast<QString>(
                props[QLatin1String("ConnectionError")])) {
            connectionError = qdbus_cast<QString>(
                    props[QLatin1String("ConnectionError")]);
            debug() << " Connection Error:" << connectionError;
            connectionStatusChanged = true;
        }

        if (props.contains(QLatin1String("ConnectionErrorDetails")) &&
            connectionErrorDetails.allDetails() != qdbus_cast<QVariantMap>(
                props[QLatin1String("ConnectionErrorDetails")])) {
            connectionErrorDetails = Connection::ErrorDetails(qdbus_cast<QVariantMap>(
                    props[QLatin1String("ConnectionErrorDetails")]));
            debug() << " Connection Error Details:" << connectionErrorDetails.allDetails();
            connectionStatusChanged = true;
        }

        if (connectionStatusChanged) {
            /* Something other than status changed, let's not emit connectionStatusChanged
             * and keep the error/errorDetails, for the next interaction.
             * It may happen if ConnectionError changes and in another property
             * change the status changes to Disconnected, so we use the error
             * previously signalled. If the status changes to something other
             * than Disconnected later, the error is cleared. */
            if (oldConnectionStatus != connectionStatus) {
                /* We don't signal error for status other than Disconnected */
                if (connectionStatus != ConnectionStatusDisconnected) {
                    connectionError = QString();
                    connectionErrorDetails = Connection::ErrorDetails();
                } else if (connectionError.isEmpty()) {
                    connectionError = ConnectionHelper::statusReasonToErrorName(
                            connectionStatusReason, oldConnectionStatus);
                }

                checkCapabilitiesChanged(profileChanged);

                emit parent->connectionStatusChanged(connectionStatus);
                parent->notify("connectionError");
                parent->notify("connectionErrorDetails");
            } else {
                connectionStatusChanged = false;
            }
        }
    }

    if (!connectionStatusChanged && profileChanged) {
        checkCapabilitiesChanged(profileChanged);
    }
}

void Account::Private::retrieveAvatar()
{
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
            parent->mPriv->properties->Get(
                TP_QT_IFACE_ACCOUNT_INTERFACE_AVATAR,
                QLatin1String("Avatar")), parent);
    parent->connect(watcher,
            SIGNAL(finished(QDBusPendingCallWatcher*)),
            SLOT(gotAvatar(QDBusPendingCallWatcher*)));
}

bool Account::Private::processConnQueue()
{
    while (!connObjPathQueue.isEmpty()) {
        QString path = connObjPathQueue.head();
        if (path.isEmpty()) {
            if (!connection.isNull()) {
                debug() << "Dropping connection for account" << parent->objectPath();

                connection.reset();
                emit parent->connectionChanged(connection);
                parent->notify("connection");
                parent->notify("connectionObjectPath");
            }

            connObjPathQueue.dequeue();
        } else {
            debug() << "Building connection" << path << "for account" << parent->objectPath();

            if (connection && connection->objectPath() == path) {
                debug() << "  Connection already built";
                connObjPathQueue.dequeue();
                continue;
            }

            QString busName = path.mid(1).replace(QLatin1String("/"), QLatin1String("."));
            parent->connect(connFactory->proxy(busName, path, chanFactory, contactFactory),
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(onConnectionBuilt(Tp::PendingOperation*)));

            // No dequeue here, but only in onConnectionBuilt, so we will queue future changes
            return false; // Only move on to the next paths when that build finishes
        }
    }

    return true;
}

void Account::onDispatcherIntrospected(Tp::PendingOperation *op)
{
    if (!mPriv->dispatcherContext->introspected) {
        Tp::PendingVariant *pv = static_cast<Tp::PendingVariant *>(op);
        Q_ASSERT(pv != NULL);

        // Only the first Account for a given dispatcher will enter this branch, and will
        // immediately make further created accounts skip the whole waiting for CD to get
        // introspected part entirely
        mPriv->dispatcherContext->introspected = true;

        if (pv->isValid()) {
            mPriv->dispatcherContext->supportsHints = qdbus_cast<bool>(pv->result());
            debug() << "Discovered channel dispatcher support for request hints: "
                << mPriv->dispatcherContext->supportsHints;
        } else {
            if (pv->errorName() == TP_QT_ERROR_NOT_IMPLEMENTED) {
                debug() << "Channel Dispatcher does not implement support for request hints";
            } else {
                warning() << "(Too old?) Channel Dispatcher failed to tell us whether"
                    << "it supports request hints, assuming it doesn't:"
                    << pv->errorName() << ':' << pv->errorMessage();
            }
            mPriv->dispatcherContext->supportsHints = false;
        }
    }

    debug() << "Calling Properties::GetAll(Account) on " << objectPath();
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
            mPriv->properties->GetAll(
                TP_QT_IFACE_ACCOUNT), this);
    connect(watcher,
            SIGNAL(finished(QDBusPendingCallWatcher*)),
            SLOT(gotMainProperties(QDBusPendingCallWatcher*)));
}

void Account::gotMainProperties(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QVariantMap> reply = *watcher;

    if (!reply.isError()) {
        debug() << "Got reply to Properties.GetAll(Account) for" << objectPath();
        mPriv->updateProperties(reply.value());

        mPriv->readinessHelper->setInterfaces(interfaces());
        mPriv->mayFinishCore = true;

        if (mPriv->connObjPathQueue.isEmpty()) {
            debug() << "Account basic functionality is ready";
            mPriv->coreFinished = true;
            mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, true);
        } else {
            debug() << "Deferring finishing Account::FeatureCore until the connection is built";
        }
    } else {
        mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, false, reply.error());

        warning().nospace() <<
            "GetAll(Account) failed: " <<
            reply.error().name() << ": " << reply.error().message();
    }

    watcher->deleteLater();
}

void Account::gotAvatar(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QVariant> reply = *watcher;

    if (!reply.isError()) {
        debug() << "Got reply to GetAvatar(Account)";
        mPriv->avatar = qdbus_cast<Avatar>(reply);

        // It could be in either of actual or missing from the first time in corner cases like the
        // object going away, so let's be prepared for both (only checking for actualFeatures here
        // actually used to trigger a rare bug)
        //
        // Anyway, the idea is to not do setIntrospectCompleted twice
        if (!mPriv->readinessHelper->actualFeatures().contains(FeatureAvatar) &&
                !mPriv->readinessHelper->missingFeatures().contains(FeatureAvatar)) {
            mPriv->readinessHelper->setIntrospectCompleted(FeatureAvatar, true);
        }

        emit avatarChanged(mPriv->avatar);
        notify("avatar");
    } else {
        // check if the feature is already there, and for some reason retrieveAvatar
        // failed when called the second time
        if (!mPriv->readinessHelper->actualFeatures().contains(FeatureAvatar) &&
                !mPriv->readinessHelper->missingFeatures().contains(FeatureAvatar)) {
            mPriv->readinessHelper->setIntrospectCompleted(FeatureAvatar, false, reply.error());
        }

        warning().nospace() <<
            "GetAvatar(Account) failed: " <<
            reply.error().name() << ": " << reply.error().message();
    }

    watcher->deleteLater();
}

void Account::onAvatarChanged()
{
    debug() << "Avatar changed, retrieving it";
    mPriv->retrieveAvatar();
}

void Account::onConnectionManagerReady(PendingOperation *operation)
{
    bool error = operation->isError();
    if (!error) {
        error = !mPriv->cm->hasProtocol(mPriv->protocolName);
    }

    if (!error) {
        mPriv->readinessHelper->setIntrospectCompleted(FeatureProtocolInfo, true);
    }
    else {
        warning() << "Failed to find the protocol in the CM protocols for account" << objectPath();
        mPriv->readinessHelper->setIntrospectCompleted(FeatureProtocolInfo, false,
                operation->errorName(), operation->errorMessage());
    }
}

void Account::onConnectionReady(PendingOperation *op)
{
    mPriv->checkCapabilitiesChanged(false);

    /* let's not fail if connection can't become ready, the caps will still
     * work, but return the CM caps instead. Also no need to call
     * setIntrospectCompleted if the feature was already set to complete once,
     * since this method will be called whenever the account connection
     * changes */
    if (!isReady(FeatureCapabilities)) {
        mPriv->readinessHelper->setIntrospectCompleted(FeatureCapabilities, true);
    }
}

void Account::onPropertyChanged(const QVariantMap &delta)
{
    mPriv->updateProperties(delta);
}

void Account::onRemoved()
{
    mPriv->valid = false;
    mPriv->enabled = false;
    invalidate(TP_QT_ERROR_OBJECT_REMOVED,
            QLatin1String("Account removed from AccountManager"));
    emit removed();
}

void Account::onConnectionBuilt(PendingOperation *op)
{
    PendingReady *readyOp = qobject_cast<PendingReady *>(op);
    Q_ASSERT(readyOp != NULL);

    if (op->isError()) {
        warning() << "Building connection" << mPriv->connObjPathQueue.head() << "failed with" <<
            op->errorName() << "-" << op->errorMessage();

        if (!mPriv->connection.isNull()) {
            mPriv->connection.reset();
            emit connectionChanged(mPriv->connection);
            notify("connection");
            notify("connectionObjectPath");
        }
    } else {
        ConnectionPtr prevConn = mPriv->connection;
        QString prevConnPath = mPriv->connectionObjectPath();

        mPriv->connection = ConnectionPtr::qObjectCast(readyOp->proxy());
        Q_ASSERT(mPriv->connection);

        debug() << "Connection" << mPriv->connectionObjectPath() << "built for" << objectPath();

        if (prevConn != mPriv->connection) {
            notify("connection");
            emit connectionChanged(mPriv->connection);
        }

        if (prevConnPath != mPriv->connectionObjectPath()) {
            notify("connectionObjectPath");
        }
    }

    mPriv->connObjPathQueue.dequeue();

    if (mPriv->processConnQueue() && !mPriv->coreFinished && mPriv->mayFinishCore) {
        debug() << "Account" << objectPath() << "basic functionality is ready (connections built)";
        mPriv->coreFinished = true;
        mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, true);
    }
}

/**
 * \fn void Account::removed()
 *
 * Emitted when this account is removed from the account manager it belonged.
 *
 * \sa remove().
 */

/**
 * \fn void Account::validityChanged(bool validity)
 *
 * Emitted when the value of isValidAccount() changes.
 *
 * \param validity The new validity of this account.
 * \sa isValidAccount()
 */

/**
 * \fn void Account::stateChanged(bool state)
 *
 * Emitted when the value of isEnabled() changes.
 *
 * \param state The new state of this account.
 * \sa isEnabled()
 */

/**
 * \fn void Account::serviceNameChanged(const QString &serviceName)
 *
 * Emitted when the value of serviceName() changes.
 *
 * \param serviceName The new service name of this account.
 * \sa serviceName(), setServiceName()
 */

/**
 * \fn void Account::profileChanged(const Tp::ProfilePtr &profile)
 *
 * Emitted when the value of profile() changes.
 *
 * \param profile The new profile of this account.
 * \sa profile()
 */

/**
 * \fn void Account::displayNameChanged(const QString &displayName)
 *
 * Emitted when the value of displayName() changes.
 *
 * \param displayName The new display name of this account.
 * \sa displayName(), setDisplayName()
 */

/**
 * \fn void Account::iconNameChanged(const QString &iconName)
 *
 * Emitted when the value of iconName() changes.
 *
 * \param iconName The new icon name of this account.
 * \sa iconName(), setIconName()
 */

/**
 * \fn void Account::nicknameChanged(const QString &nickname)
 *
 * Emitted when the value of nickname() changes.
 *
 * \param nickname The new nickname of this account.
 * \sa nickname(), setNickname()
 */

/**
 * \fn void Account::normalizedNameChanged(const QString &normalizedName)
 *
 * Emitted when the value of normalizedName() changes.
 *
 * \param normalizedName The new normalized name of this account.
 * \sa normalizedName()
 */

/**
 * \fn void Account::capabilitiesChanged(const Tp::ConnectionCapabilities &capabilities)
 *
 * Emitted when the value of capabilities() changes.
 *
 * \param capabilities The new capabilities of this account.
 * \sa capabilities()
 */

/**
 * \fn void Account::connectsAutomaticallyPropertyChanged(bool connectsAutomatically)
 *
 * Emitted when the value of connectsAutomatically() changes.
 *
 * \param connectsAutomatically The new value of connects automatically property
 *                              of this account.
 * \sa isEnabled()
 */

/**
 * \fn void Account::firstOnline()
 *
 * Emitted when this account is first put online.
 *
 * \sa hasBeenOnline()
 */

/**
 * \fn void Account::parametersChanged(const QVariantMap &parameters)
 *
 * Emitted when the value of parameters() changes.
 *
 * \param parameters The new parameters of this account.
 * \sa parameters()
 */

/**
 * \fn void Account::changingPresence(bool value)
 *
 * Emitted when the value of isChangingPresence() changes.
 *
 * \param value Whether this account's connection is changing presence.
 * \sa isChangingPresence()
 */

/**
 * \fn void Account::automaticPresenceChanged(const Tp::Presence &automaticPresence)
 *
 * Emitted when the value of automaticPresence() changes.
 *
 * \param automaticPresence The new value of automatic presence property of this
 *                          account.
 * \sa automaticPresence(), currentPresenceChanged()
 */

/**
 * \fn void Account::currentPresenceChanged(const Tp::Presence &currentPresence)
 *
 * Emitted when the value of currentPresence() changes.
 *
 * \param currentPresence The new value of the current presence property of this
 *                        account.
 * \sa currentPresence()
 */

/**
 * \fn void Account::requestedPresenceChanged(const Tp::Presence &requestedPresence)
 *
 * Emitted when the value of requestedPresence() changes.
 *
 * \param requestedPresence The new value of the requested presence property of this
 *                          account.
 * \sa requestedPresence(), currentPresenceChanged()
 */

/**
 * \fn void Account::onlinenessChanged(bool online)
 *
 * Emitted when the value of isOnline() changes.
 *
 * \param online Whether this account is online.
 * \sa isOnline(), currentPresence()
 */

/**
 * \fn void Account::avatarChanged(const Tp::Avatar &avatar)
 *
 * Emitted when the value of avatar() changes.
 *
 * \param avatar The new avatar of this account.
 * \sa avatar()
 */

/**
 * \fn void Account::connectionStatusChanged(Tp::ConnectionStatus status)
 *
 * Emitted when the connection status changes.
 *
 * \param status The new status of this account connection.
 * \sa connectionStatus(), connectionStatusReason(), connectionError(), connectionErrorDetails(),
 *     Connection::ErrorDetails
 */

/**
 * \fn void Account::connectionChanged(const Tp::ConnectionPtr &connection)
 *
 * Emitted when the value of connection() changes.
 *
 * The \a connection will have the features set in the ConnectionFactory used by this account ready
 * and the same channel and contact factories used by this account.
 *
 * \param connection A ConnectionPtr pointing to the new Connection object or a null ConnectionPtr
 *                   if there is no connection.
 * \sa connection()
 */

} // Tp