summaryrefslogtreecommitdiff
path: root/telepathy-glib/connection.c
blob: 93c1a1171d8038a658635276dc93bef4a6c9a7c7 (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
/*
 * connection.c - proxy for a Telepathy connection
 *
 * Copyright (C) 2007-2011 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2007-2011 Nokia Corporation
 *
 * 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 "config.h"

#include "telepathy-glib/connection.h"

#include <string.h>

#include <dbus/dbus-glib.h>
#include <dbus/dbus-protocol.h>

#include <telepathy-glib/asv.h>
#include <telepathy-glib/cli-connection.h>
#include <telepathy-glib/cli-misc.h>
#include <telepathy-glib/connection-manager.h>
#include <telepathy-glib/dbus.h>
#include <telepathy-glib/defs.h>
#include <telepathy-glib/enums.h>
#include <telepathy-glib/errors.h>
#include <telepathy-glib/gtypes.h>
#include <telepathy-glib/handle.h>
#include <telepathy-glib/interfaces.h>
#include <telepathy-glib/proxy-subclass.h>
#include <telepathy-glib/util.h>
#include <telepathy-glib/value-array.h>

#define DEBUG_FLAG TP_DEBUG_CONNECTION
#include "telepathy-glib/capabilities-internal.h"
#include "telepathy-glib/connection-internal.h"
#include "telepathy-glib/connection-contact-list.h"
#include "telepathy-glib/dbus-internal.h"
#include "telepathy-glib/debug-internal.h"
#include "telepathy-glib/proxy-internal.h"
#include "telepathy-glib/client-factory-internal.h"
#include "telepathy-glib/contact-internal.h"
#include "telepathy-glib/util-internal.h"
#include "telepathy-glib/variant-util.h"

/**
 * SECTION:connection
 * @title: TpConnection
 * @short_description: proxy object for a Telepathy connection
 * @see_also: #TpConnectionManager, #TpChannel
 *
 * #TpConnection objects represent Telepathy instant messaging connections
 * accessed via D-Bus.
 *
 * #TpConnection objects should be obtained from a #TpAccount, unless you
 * are implementing a lower-level Telepathy component (such as the account
 * manager service itself).
 *
 * Since 0.16, #TpConnection always has a non-%NULL #TpProxy:factory, and its
 * #TpProxy:factory will be propagated to its #TpChannel objects
 * (if any). Similarly, the #TpProxy:factory<!-- -->'s features
 * will be used for #TpContact objects.
 * If a #TpConnection is created without going via the
 * #TpAccount or specifying a #TpProxy:factory, the default
 * is to use a new #TpAutomaticClientFactory.
 *
 * Since: 0.7.1
 */

/**
 * TP_CONNECTION_FEATURE_CORE:
 *
 * Expands to a call to a function that returns a quark for the "core" feature
 * on a #TpConnection.
 *
 * When this feature is prepared, the basic properties of the Connection have
 * been retrieved and are available for use, and change-notification has been
 * set up for those that can change.
 *
 * Specifically, this implies that:
 *
 * <itemizedlist>
 *  <listitem>#TpConnection:status has a value other than
 *    %TP_UNKNOWN_CONNECTION_STATUS, and #TpConnection:status-reason is
 *    the reason for changing to that status</listitem>
 *  <listitem>interfaces that are always available have been added to the
 *    #TpProxy:interfaces (although the set of interfaces is not guaranteed
 *    to be complete until #TpConnection:status becomes
 *    %TP_CONNECTION_STATUS_CONNECTED))</listitem>
 * </itemizedlist>
 *
 * <note>
 *  <title>prepared does not imply connected</title>
 *  <para>This
 *    feature does not imply that the connection has successfully connected.
 *    It only implies that an initial status (disconnected, connecting or
 *    connected) has been discovered.</para>
 * </note>
 *
 * One can ask for a feature to be prepared using the
 * tp_proxy_prepare_async() function, and waiting for it to callback.
 *
 * Since: 0.11.3
 */

GQuark
tp_connection_get_feature_quark_core (void)
{
  return g_quark_from_static_string ("tp-connection-feature-core");
}

/**
 * TP_CONNECTION_FEATURE_CONNECTED:
 *
 * Expands to a call to a function that returns a #GQuark representing the
 * "connected" feature.
 *
 * When this feature is prepared, it means that the connection has become
 * connected to the appropriate real-time communications service, and all
 * information requested via other features has been updated accordingly.
 * In particular, the following aspects of %TP_CONNECTION_FEATURE_CORE
 * will be up to date:
 *
 * <itemizedlist>
 *  <listitem>#TpConnection:status is
 *    %TP_CONNECTION_STATUS_CONNECTED</listitem>
 *  <listitem>#TpConnection:self-contact is non-%NULL</listitem>
 *  <listitem>all interfaces have been added to the set of
 *    #TpProxy:interfaces, and that set will not change again</listitem>
 * </itemizedlist>
 *
 * <note>
 *   <title>Someone still has to call Connect()</title>
 *   <para>Requesting this feature via tp_proxy_prepare_async() means that
 *     you want to wait for the connection to connect, but it doesn't actually
 *     start the process of connecting. For connections associated with
 *     a #TpAccount, the account manager service is responsible for
 *     doing that, but if you are constructing connections directly
 *     (e.g. if you are implementing an account manager), you must
 *     tp_cli_connection_call_connect() separately.
 *     </para>
 * </note>
 *
 * One can ask for a feature to be prepared using the
 * tp_proxy_prepare_async() function, and waiting for it to callback.
 *
 * Since: 0.11.3
 */

GQuark
tp_connection_get_feature_quark_connected (void)
{
  return g_quark_from_static_string ("tp-connection-feature-connected");
}

/**
 * TP_CONNECTION_FEATURE_CAPABILITIES:
 *
 * Expands to a call to a function that returns a #GQuark representing the
 * "capabilities" feature.
 *
 * When this feature is prepared, the Requests.RequestableChannelClasses
 * property of the Connection has been retrieved.
 * In particular, the %TpConnection:capabilities property has been set.
 *
 * One can ask for a feature to be prepared using the
 * tp_proxy_prepare_async() function, and waiting for it to callback.
 *
 * Since: 0.11.3
 */

GQuark
tp_connection_get_feature_quark_capabilities (void)
{
  return g_quark_from_static_string ("tp-connection-feature-capabilities");
}

/**
 * TP_CONNECTION_FEATURE_BALANCE:
 *
 * Expands to a call to a function that returns a #GQuark representing the
 * "balance" feature.
 *
 * When this feature is prepared, the Balance.AccountBalance and
 * Balance.ManageCreditURI properties of the Connection have been retrieved.
 * In particular, the %TpConnection:balance, %TpConnection:balance-scale,
 * %TpConnection:balance-currency and %TpConnection:balance-uri properties
 * have been set and the TpConnection::balance-changed: will be emitted
 * when they are changed.
 *
 * One can ask for a feature to be prepared using the
 * tp_proxy_prepare_async() function, and waiting for it to callback.
 *
 * Since: 0.15.1
 */

GQuark
tp_connection_get_feature_quark_balance (void)
{
  return g_quark_from_static_string ("tp-connection-feature-balance");
}

/**
 * TP_ERRORS_DISCONNECTED:
 *
 * #GError domain representing a Telepathy connection becoming disconnected.
 * The @code in a #GError with this domain must be a member of
 * #TpConnectionStatusReason.
 *
 * This macro expands to a function call returning a #GQuark.
 *
 * Since 0.7.24, this error domain is only used if a connection manager emits
 * a #TpConnectionStatusReason not known to telepathy-glib.
 *
 * Since: 0.7.1
 */
GQuark
tp_errors_disconnected_quark (void)
{
  static GQuark q = 0;

  if (q == 0)
    q = g_quark_from_static_string ("tp_errors_disconnected_quark");

  return q;
}

/**
 * TP_UNKNOWN_CONNECTION_STATUS:
 *
 * An invalid connection status used in #TpConnection to indicate that the
 * status has not yet been discovered.
 *
 * Since: 0.7.1
 */

/**
 * TpConnectionClass:
 * @parent_class: the parent class
 *
 * The class of a #TpConnection. In addition to @parent_class there are four
 * pointers reserved for possible future use.
 *
 * (Changed in 0.7.12: the layout of the structure is visible, allowing
 * subclassing.)
 *
 * Since: 0.7.1
 */

/**
 * TpConnection:
 *
 * A proxy object for a Telepathy connection. There are no interesting
 * public struct fields.
 *
 * (Changed in 0.7.12: the layout of the structure is visible, allowing
 * subclassing.)
 *
 * Since: 0.7.1
 */

/* properties */
enum
{
  PROP_STATUS = 1,
  PROP_STATUS_REASON,
  PROP_CM_NAME,
  PROP_PROTOCOL_NAME,
  PROP_SELF_CONTACT,
  PROP_CAPABILITIES,
  PROP_BALANCE,
  PROP_BALANCE_SCALE,
  PROP_BALANCE_CURRENCY,
  PROP_BALANCE_URI,
  PROP_CONTACT_LIST_STATE,
  PROP_CONTACT_LIST_PERSISTS,
  PROP_CAN_CHANGE_CONTACT_LIST,
  PROP_REQUEST_USES_MESSAGE,
  PROP_DISJOINT_GROUPS,
  PROP_GROUP_STORAGE,
  PROP_CONTACT_GROUPS,
  PROP_CAN_REPORT_ABUSIVE,
  PROP_BLOCKED_CONTACTS,
  N_PROPS
};

enum {
  SIGNAL_BALANCE_CHANGED,
  SIGNAL_GROUPS_CREATED,
  SIGNAL_GROUPS_REMOVED,
  SIGNAL_GROUP_RENAMED,
  SIGNAL_CONTACT_LIST_CHANGED,
  SIGNAL_BLOCKED_CONTACTS_CHANGED,
  N_SIGNALS
};

static guint signals[N_SIGNALS] = { 0 };

G_DEFINE_TYPE (TpConnection,
    tp_connection,
    TP_TYPE_PROXY)

static void
tp_connection_get_property (GObject *object,
                            guint property_id,
                            GValue *value,
                            GParamSpec *pspec)
{
  TpConnection *self = TP_CONNECTION (object);

  switch (property_id)
    {
    case PROP_CM_NAME:
      g_value_set_string (value, self->priv->cm_name);
      break;
    case PROP_PROTOCOL_NAME:
      g_value_set_string (value, self->priv->proto_name);
      break;
    case PROP_STATUS:
      g_value_set_uint (value, self->priv->status);
      break;
    case PROP_STATUS_REASON:
      g_value_set_uint (value, self->priv->status_reason);
      break;
    case PROP_SELF_CONTACT:
      g_value_set_object (value, tp_connection_get_self_contact (self));
      break;
    case PROP_CAPABILITIES:
      g_value_set_object (value, self->priv->capabilities);
      break;
    case PROP_BALANCE:
      g_value_set_int (value, self->priv->balance);
      break;
    case PROP_BALANCE_SCALE:
      g_value_set_uint (value, self->priv->balance_scale);
      break;
    case PROP_BALANCE_CURRENCY:
      g_value_set_string (value, self->priv->balance_currency);
      break;
    case PROP_BALANCE_URI:
      g_value_set_string (value, self->priv->balance_uri);
      break;
    case PROP_CONTACT_LIST_STATE:
      g_value_set_uint (value, self->priv->contact_list_state);
      break;
    case PROP_CONTACT_LIST_PERSISTS:
      g_value_set_boolean (value, self->priv->contact_list_persists);
      break;
    case PROP_CAN_CHANGE_CONTACT_LIST:
      g_value_set_boolean (value, self->priv->can_change_contact_list);
      break;
    case PROP_REQUEST_USES_MESSAGE:
      g_value_set_boolean (value, self->priv->request_uses_message);
      break;
    case PROP_DISJOINT_GROUPS:
      g_value_set_boolean (value, self->priv->disjoint_groups);
      break;
    case PROP_GROUP_STORAGE:
      g_value_set_uint (value, self->priv->group_storage);
      break;
    case PROP_CONTACT_GROUPS:
      g_value_set_boxed (value, self->priv->contact_groups);
      break;
    case PROP_CAN_REPORT_ABUSIVE:
      g_value_set_boolean (value, tp_connection_can_report_abusive (self));
      break;
    case PROP_BLOCKED_CONTACTS:
      g_value_set_boxed (value, tp_connection_get_blocked_contacts (self));
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
      break;
    }
}

static void
tp_connection_unpack_balance (TpConnection *self,
    GValueArray *balance_s)
{
  gint balance = 0;
  guint scale = G_MAXUINT32;
  const char *currency = "";
  gboolean changed = FALSE;

  if (balance_s == NULL)
    goto finally;

  tp_value_array_unpack (balance_s, 3,
      &balance, &scale, &currency);

finally:

  g_object_freeze_notify ((GObject *) self);

  if (self->priv->balance != balance)
    {
      self->priv->balance = balance;
      g_object_notify ((GObject *) self, "balance");
      changed = TRUE;
    }

  if (self->priv->balance_scale != scale)
    {
      self->priv->balance_scale = scale;
      g_object_notify ((GObject *) self, "balance-scale");
      changed = TRUE;
    }

  if (tp_strdiff (self->priv->balance_currency, currency))
    {
      g_free (self->priv->balance_currency);
      self->priv->balance_currency = g_strdup (currency);
      g_object_notify ((GObject *) self, "balance-currency");
      changed = TRUE;
    }

  g_object_thaw_notify ((GObject *) self);

  if (changed)
    {
      g_signal_emit (self, signals[SIGNAL_BALANCE_CHANGED], 0,
          balance, scale, currency);
    }
}

static void
tp_connection_get_balance_cb (TpProxy *proxy,
    GHashTable *props,
    const GError *in_error,
    gpointer user_data,
    GObject *weak_obj)
{
  TpConnection *self = (TpConnection *) proxy;
  GSimpleAsyncResult *result = user_data;
  GValueArray *balance = NULL;

  if (in_error != NULL)
    {
      DEBUG ("Failed to get Balance properties: %s", in_error->message);
      g_simple_async_result_set_from_error (result, in_error);
      goto finally;
    }

  balance =
    tp_asv_get_boxed (props, "AccountBalance", TP_STRUCT_TYPE_CURRENCY_AMOUNT);
  self->priv->balance_uri =
    g_strdup (tp_asv_get_string (props, "ManageCreditURI"));

  g_object_freeze_notify ((GObject *) self);

  tp_connection_unpack_balance (self, balance);

  _tp_proxy_set_feature_prepared (proxy, TP_CONNECTION_FEATURE_BALANCE,
      TRUE);

  g_object_notify ((GObject *) self, "balance-uri");

  g_object_thaw_notify ((GObject *) self);

finally:
  g_simple_async_result_complete (result);
}

static void
tp_connection_balance_changed_cb (TpConnection *self,
    const GValueArray *balance,
    gpointer user_data,
    GObject *weak_obj)
{
  tp_connection_unpack_balance (self, (GValueArray *) balance);
}

static void
tp_connection_prepare_balance_async (TpProxy *proxy,
    const TpProxyFeature *feature,
    GAsyncReadyCallback callback,
    gpointer user_data)
{
  TpConnection *self = (TpConnection *) proxy;
  GSimpleAsyncResult *result;

  result = g_simple_async_result_new ((GObject *) proxy, callback, user_data,
      tp_connection_prepare_balance_async);

  g_assert (self->priv->balance_currency == NULL);

  tp_cli_dbus_properties_call_get_all (self, -1,
      TP_IFACE_CONNECTION_INTERFACE_BALANCE1,
      tp_connection_get_balance_cb, result, g_object_unref, NULL);

  tp_cli_connection_interface_balance1_connect_to_balance_changed (self,
      tp_connection_balance_changed_cb,
      NULL, NULL, NULL, NULL);
}

static void
tp_connection_get_rcc_cb (TpProxy *proxy,
    const GValue *value,
    const GError *error,
    gpointer user_data,
    GObject *weak_object)
{
  TpConnection *self = (TpConnection *) proxy;
  GSimpleAsyncResult *result;

  if (error != NULL)
    {
      DEBUG ("Failed to get RequestableChannelClasses property, using an "
          "empty set: %s", error->message);

      /* it's NULL-safe */
      self->priv->capabilities = _tp_capabilities_new (NULL, FALSE);
      goto finally;
    }

  g_assert (self->priv->capabilities == NULL);

  if (!G_VALUE_HOLDS (value, TP_ARRAY_TYPE_REQUESTABLE_CHANNEL_CLASS_LIST))
    {
      DEBUG ("RequestableChannelClasses is not of type a(a{sv}as), using an "
          "empty set: %s", G_VALUE_TYPE_NAME (value));

      /* it's NULL-safe */
      self->priv->capabilities = _tp_capabilities_new (NULL, FALSE);
      goto finally;
    }

  DEBUG ("CAPABILITIES ready");

  self->priv->capabilities = _tp_capabilities_new (
      dbus_g_value_build_g_variant (value), FALSE);

finally:
  while ((result = g_queue_pop_head (&self->priv->capabilities_queue)) != NULL)
    {
      g_simple_async_result_complete (result);
      g_object_unref (result);
    }

  g_object_notify ((GObject *) self, "capabilities");
}

static void
_tp_connection_do_get_capabilities_async (TpConnection *self,
    GSimpleAsyncResult *result)
{
  if (self->priv->capabilities != NULL)
    {
      /* been there, done that, bored now */
      g_simple_async_result_complete_in_idle (result);
      g_object_unref (result);
    }
  else
    {
      g_queue_push_tail (&self->priv->capabilities_queue, result);
      if (g_queue_get_length (&self->priv->capabilities_queue) == 1)
        {
          DEBUG ("%s: Retrieving capabilities",
            tp_proxy_get_object_path (self));

          /* We don't check whether we actually have this interface here.
           * The Requests interface is mandatory, and we assume we have it. */
          tp_cli_dbus_properties_call_get (self, -1,
            TP_IFACE_CONNECTION, "RequestableChannelClasses",
            tp_connection_get_rcc_cb, NULL, NULL, NULL);
        }
    }
}

static void
tp_connection_prepare_capabilities_async (TpProxy *proxy,
    const TpProxyFeature *feature,
    GAsyncReadyCallback callback,
    gpointer user_data)
{
  TpConnection *self = (TpConnection *) proxy;
  GSimpleAsyncResult *result;

  DEBUG ("%s: Preparing capabilities", tp_proxy_get_object_path (self));

  result = g_simple_async_result_new ((GObject *) self, callback, user_data,
      tp_connection_prepare_capabilities_async);

  _tp_connection_do_get_capabilities_async (self, result);
}

static void
signal_connected (TpConnection *self)
{
  /* we shouldn't have gone to status CONNECTED for any reason
   * that isn't REQUESTED :-) */
  DEBUG ("%s (%p): CORE and CONNECTED ready",
    tp_proxy_get_object_path (self), self);
  self->priv->status = TP_CONNECTION_STATUS_CONNECTED;
  self->priv->status_reason = TP_CONNECTION_STATUS_REASON_REQUESTED;

  _tp_proxy_set_feature_prepared ((TpProxy *) self,
      TP_CONNECTION_FEATURE_CONNECTED, TRUE);
  _tp_proxy_set_feature_prepared ((TpProxy *) self,
      TP_CONNECTION_FEATURE_CORE, TRUE);

  g_object_notify ((GObject *) self, "status");
  g_object_notify ((GObject *) self, "status-reason");
}

static void
will_announced_connected_cb (GObject *source,
    GAsyncResult *result,
    gpointer user_data)
{
  TpConnection *self = (TpConnection *) source;
  GError *error = NULL;

  if (!_tp_proxy_will_announce_connected_finish ((TpProxy *) self, result,
        &error))
    {
      DEBUG ("_tp_connection_prepare_contact_info_async failed: %s",
          error->message);

      g_error_free (error);
    }

  if (tp_proxy_get_invalidated (self) != NULL)
    {
      DEBUG ("Connection has been invalidated; we're done");
      return;
    }

  signal_connected (self);
}

static void
tp_connection_continue_introspection (TpConnection *self)
{
  if (tp_proxy_get_invalidated (self) != NULL)
    {
      DEBUG ("Already invalidated: not becoming ready");
      return;
    }

  if (self->priv->introspect_needed == NULL)
    {
      if (!self->priv->introspecting_after_connected)
        {
          /* Introspection will restart when we become CONNECTED */
          DEBUG ("CORE ready, but not CONNECTED");
          _tp_proxy_set_feature_prepared ((TpProxy *) self,
            TP_CONNECTION_FEATURE_CORE, TRUE);
          return;
        }

      /* We'll announce CONNECTED state soon, but first give a chance to
       * prepared feature to be updated, if needed */
      _tp_proxy_will_announce_connected_async ((TpProxy *) self,
          will_announced_connected_cb, NULL);
    }
  else
    {
      TpConnectionProc next = self->priv->introspect_needed->data;

      self->priv->introspect_needed = g_list_delete_link (
          self->priv->introspect_needed,
          self->priv->introspect_needed);
      next (self);
    }
}

static void
tp_connection_set_self_contact (TpConnection *self,
    TpContact *contact)
{
  if (contact != self->priv->self_contact)
    {
      TpContact *tmp = self->priv->self_contact;

      self->priv->self_contact = g_object_ref (contact);
      tp_clear_object (&tmp);
      g_object_notify ((GObject *) self, "self-contact");
    }

  if (self->priv->introspecting_self_contact)
    {
      self->priv->introspecting_self_contact = FALSE;
      tp_connection_continue_introspection (self);
    }
}

static void
upgrade_self_contact_cb (GObject *object,
    GAsyncResult *result,
    gpointer user_data)
{
  TpClientFactory *factory = (TpClientFactory *) object;
  TpConnection *self = user_data;
  GPtrArray *contacts;
  TpContact *contact;
  GError *error = NULL;

  if (!tp_client_factory_upgrade_contacts_finish (factory, result, &contacts,
          &error))
    {
      DEBUG ("Error upgrading self contact: %s", error->message);
      g_clear_error (&error);
      goto out;
    }

  g_assert (contacts->len == 1);
  contact = g_ptr_array_index (contacts, 0);

  /* Self contact could have changed while we were upgrading */
  if (tp_contact_get_handle (contact) == self->priv->last_known_self_handle)
    {
      tp_connection_set_self_contact (self, contact);
    }

  g_ptr_array_unref (contacts);

out:
  g_object_unref (self);
}

static void
get_self_contact (TpConnection *self)
{
  TpClientFactory *factory;
  TpContact *contact;

  factory = tp_proxy_get_factory (self);

  contact = tp_client_factory_ensure_contact (factory, self,
      self->priv->last_known_self_handle,
      self->priv->last_known_self_id);

  tp_client_factory_upgrade_contacts_async (factory, self,
      1, &contact, upgrade_self_contact_cb, g_object_ref (self));

  g_object_unref (contact);
}

static void
introspect_self_contact (TpConnection *self)
{
  self->priv->introspecting_self_contact = TRUE;
  get_self_contact (self);
}

static void
on_self_contact_changed (TpConnection *self,
                        guint self_handle,
                        const gchar *self_id,
                        gpointer user_data G_GNUC_UNUSED,
                        GObject *user_object G_GNUC_UNUSED)
{
  if (self_handle == 0)
    {
      DEBUG ("Ignoring alleged change of self-handle to %u", self_handle);
      return;
    }

  if (self->priv->last_known_self_handle == 0)
    {
      /* We're going to call GetAll(Connection) anyway, or if the CM
       * is sufficiently deficient, GetSelfHandle(). */
      DEBUG ("Ignoring early self-handle change to %u, we'll pick it up later",
          self_handle);
      return;
    }

  if (self->priv->last_known_self_handle == self_handle &&
      !tp_strdiff (self_id, self->priv->last_known_self_id))
    {
      DEBUG ("Ignoring no-op self-handle change to %u '%s'",
          self_handle, self_id);
      return;
    }

  DEBUG ("SelfHandleChanged to %u '%s'", self_handle, self_id);
  self->priv->last_known_self_handle = self_handle;
  g_free (self->priv->last_known_self_id);
  self->priv->last_known_self_id = g_strdup (self_id);

  if (self->priv->introspecting_after_connected ||
      tp_connection_get_status (self, NULL) == TP_CONNECTION_STATUS_CONNECTED)
    get_self_contact (self);
}

/* Appending callbacks to self->priv->introspect_needed relies on this */
G_STATIC_ASSERT (sizeof (TpConnectionProc) <= sizeof (gpointer));

static void
_tp_connection_got_properties (TpProxy *proxy,
    GHashTable *asv,
    const GError *error,
    gpointer unused G_GNUC_UNUSED,
    GObject *unused_object G_GNUC_UNUSED);

static void
tp_connection_status_changed (TpConnection *self,
                              guint status,
                              guint reason)
{
  DEBUG ("%p: %d -> %d because %d", self, self->priv->status, status, reason);

  if (status == TP_CONNECTION_STATUS_CONNECTED)
    {
      if (self->priv->introspection_call != NULL &&
          !self->priv->introspecting_after_connected)
        {
          /* We thought we knew what was going on, but now the connection has
           * gone to CONNECTED and all bets are off. Start again! */
          DEBUG ("Cancelling pre-CONNECTED introspection and starting again");
          tp_proxy_pending_call_cancel (self->priv->introspection_call);
          self->priv->introspection_call = NULL;
          g_list_free (self->priv->introspect_needed);
          self->priv->introspect_needed = NULL;
        }

      self->priv->introspecting_after_connected = TRUE;

      /* we defer the perceived change to CONNECTED until ready */
      if (self->priv->introspection_call == NULL)
        {
          self->priv->introspection_call =
            tp_cli_dbus_properties_call_get_all (self, -1,
              TP_IFACE_CONNECTION, _tp_connection_got_properties, NULL, NULL, NULL);
        }
    }
  else
    {
      self->priv->status = status;
      self->priv->status_reason = reason;
      g_object_notify ((GObject *) self, "status");
      g_object_notify ((GObject *) self, "status-reason");
    }
}

static void
tp_connection_connection_error_cb (TpConnection *self,
                                   const gchar *error_name,
                                   GHashTable *details,
                                   gpointer user_data,
                                   GObject *weak_object)
{
  g_free (self->priv->connection_error);
  self->priv->connection_error = g_strdup (error_name);

  if (self->priv->connection_error_details != NULL)
    g_hash_table_unref (self->priv->connection_error_details);

  self->priv->connection_error_details = g_boxed_copy (
      TP_HASH_TYPE_STRING_VARIANT_MAP, details);
}

void
_tp_connection_status_reason_to_gerror (TpConnectionStatusReason reason,
    TpConnectionStatus prev_status,
    const gchar **ret_str,
    GError **error)
{
  TpError code;
  const gchar *message;

  switch (reason)
    {
    case TP_CONNECTION_STATUS_REASON_NONE_SPECIFIED:
      code = TP_ERROR_DISCONNECTED;
      message = "Disconnected for unspecified reason";
      break;

    case TP_CONNECTION_STATUS_REASON_REQUESTED:
      code = TP_ERROR_CANCELLED;
      message = "User requested disconnection";
      break;

    case TP_CONNECTION_STATUS_REASON_NETWORK_ERROR:
      code = TP_ERROR_NETWORK_ERROR;
      message = "Network error";
      break;

    case TP_CONNECTION_STATUS_REASON_ENCRYPTION_ERROR:
      code = TP_ERROR_ENCRYPTION_ERROR;
      message = "Encryption error";
      break;

    case TP_CONNECTION_STATUS_REASON_NAME_IN_USE:
      if (prev_status == TP_CONNECTION_STATUS_CONNECTED)
        {
          code = TP_ERROR_CONNECTION_REPLACED;
          message = "Connection replaced";
        }
      else
        {
          /* If the connection was with register=TRUE, we should ideally use
           * REGISTRATION_EXISTS; but we can't actually tell that from here,
           * so we'll have to rely on CMs supporting in-band registration
           * (Gabble) to emit ConnectionError */
          code = TP_ERROR_ALREADY_CONNECTED;
          message = "Already connected (or if registering, registration "
            "already exists)";
        }
      break;

    case TP_CONNECTION_STATUS_REASON_CERT_NOT_PROVIDED:
      code = TP_ERROR_CERT_NOT_PROVIDED;
      message = "Server certificate not provided";
      break;

    case TP_CONNECTION_STATUS_REASON_CERT_UNTRUSTED:
      code = TP_ERROR_CERT_UNTRUSTED;
      message = "Server certificate CA not trusted";
      break;

    case TP_CONNECTION_STATUS_REASON_CERT_EXPIRED:
      code = TP_ERROR_CERT_EXPIRED;
      message = "Server certificate expired";
      break;

    case TP_CONNECTION_STATUS_REASON_CERT_NOT_ACTIVATED:
      code = TP_ERROR_CERT_NOT_ACTIVATED;
      message = "Server certificate not valid yet";
      break;

    case TP_CONNECTION_STATUS_REASON_CERT_HOSTNAME_MISMATCH:
      code = TP_ERROR_CERT_HOSTNAME_MISMATCH;
      message = "Server certificate has wrong hostname";
      break;

    case TP_CONNECTION_STATUS_REASON_CERT_FINGERPRINT_MISMATCH:
      code = TP_ERROR_CERT_FINGERPRINT_MISMATCH;
      message = "Server certificate fingerprint mismatch";
      break;

    case TP_CONNECTION_STATUS_REASON_CERT_SELF_SIGNED:
      code = TP_ERROR_CERT_SELF_SIGNED;
      message = "Server certificate is self-signed";
      break;

    case TP_CONNECTION_STATUS_REASON_CERT_OTHER_ERROR:
      code = TP_ERROR_CERT_INVALID;
      message = "Unspecified server certificate error";
      break;

    default:
      g_set_error (error, TP_ERRORS_DISCONNECTED, reason,
          "Unknown disconnection reason");

      if (ret_str != NULL)
        *ret_str = TP_ERROR_STR_DISCONNECTED;

      return;
    }

  g_set_error (error, TP_ERROR, code, "%s", message);

  if (ret_str != NULL)
    *ret_str = tp_error_get_dbus_name (code);
}

static void
tp_connection_status_changed_cb (TpConnection *self,
                                 guint status,
                                 guint reason,
                                 gpointer user_data,
                                 GObject *weak_object)
{
  TpConnectionStatus prev_status = self->priv->status;

  /* The status is initially attempted to be discovered starting in the
   * constructor. If we don't have the reply for that call yet, ignore this
   * signal StatusChanged in order to run the interface introspection only one
   * time. We will get the initial introspection reply later anyway. */
  if (self->priv->status != TP_UNKNOWN_CONNECTION_STATUS)
    {
      tp_connection_status_changed (self, status, reason);
    }

  /* we only want to run this in response to a StatusChanged signal,
   * not if the initial status is DISCONNECTED */

  if (status == TP_CONNECTION_STATUS_DISCONNECTED)
    {
      GError *error = NULL;

      if (self->priv->connection_error == NULL)
        {
          _tp_connection_status_reason_to_gerror (reason, prev_status,
              NULL, &error);
        }
      else
        {
          g_assert (self->priv->connection_error_details != NULL);
          tp_proxy_dbus_error_to_gerror (self, self->priv->connection_error,
              tp_asv_get_string (self->priv->connection_error_details,
                "debug-message"), &error);

          /* ... but if we don't know anything about that D-Bus error
           * name, we can still be more helpful by deriving an error code from
           * TpConnectionStatusReason */
          if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_DBUS_ERROR))
            {
              GError *from_csr = NULL;

              _tp_connection_status_reason_to_gerror (reason, prev_status,
                  NULL, &from_csr);
              error->domain = from_csr->domain;
              error->code = from_csr->code;
              g_error_free (from_csr);
            }
        }

      tp_proxy_invalidate ((TpProxy *) self, error);
      g_error_free (error);
    }
}

static void
tp_connection_invalidated (TpConnection *self)
{
  if (self->priv->introspection_call != NULL)
    {
      DEBUG ("Cancelling introspection");
      tp_proxy_pending_call_cancel (self->priv->introspection_call);
      self->priv->introspection_call = NULL;
    }
}

static void
_tp_connection_got_properties (TpProxy *proxy,
    GHashTable *asv,
    const GError *error,
    gpointer unused G_GNUC_UNUSED,
    GObject *unused_object G_GNUC_UNUSED)
{
  TpConnection *self = TP_CONNECTION (proxy);
  TpConnectionStatus status;
  const gchar * const *interfaces;
  gboolean valid;
  GError *e = NULL;

  if (tp_proxy_get_invalidated (self) != NULL)
    {
      DEBUG ("%p: already invalidated, not trying to become ready: %s",
          self, tp_proxy_get_invalidated (self)->message);
      return;
    }

  if (error != NULL)
    {
      /* Properties are now mandatory */
      tp_proxy_invalidate (proxy, error);
      return;
    }

  if (self->priv->introspection_call)
    self->priv->introspection_call = NULL;

  interfaces = tp_asv_get_strv (asv, "Interfaces");
  if (interfaces == NULL)
    goto error;

  tp_proxy_add_interfaces (proxy, interfaces);
  self->priv->ready_enough_for_contacts = TRUE;

  status = tp_asv_get_uint32 (asv, "Status", &valid);
  if (!valid || status > TP_CONNECTION_STATUS_DISCONNECTED)
    goto error;

  if (status == TP_CONNECTION_STATUS_CONNECTED)
    {
      TpHandle self_handle;
      const gchar *self_id;

      self_handle = tp_asv_get_uint32 (asv, "SelfHandle", &valid);
      if (!valid || self_handle == 0)
        goto error;

      self_id = tp_asv_get_string (asv, "SelfID");
      if (tp_str_empty (self_id))
        goto error;

      self->priv->introspecting_after_connected = TRUE;
      self->priv->last_known_self_handle = self_handle;
      g_free (self->priv->last_known_self_id);
      self->priv->last_known_self_id = g_strdup (self_id);

      self->priv->introspect_needed = g_list_append (
          self->priv->introspect_needed, introspect_self_contact);
    }
  else
    {
      tp_connection_status_changed (self, status,
          TP_CONNECTION_STATUS_REASON_NONE_SPECIFIED);
    }

  tp_connection_continue_introspection (self);
  return;

error:
  e = g_error_new_literal (TP_ERROR, TP_ERROR_INVALID_ARGUMENT,
      "Connection does not implement all properties.");
  WARNING ("%s", e->message);
  tp_proxy_invalidate (proxy, e);
  g_clear_error (&e);
}

static gboolean _tp_connection_parse (const gchar *path_or_bus_name,
    char delimiter,
    gchar **protocol,
    gchar **cm_name);

static void
tp_connection_constructed (GObject *object)
{
  GObjectClass *object_class = (GObjectClass *) tp_connection_parent_class;
  TpConnection *self = TP_CONNECTION (object);
  const gchar *object_path;

  if (object_class->constructed != NULL)
    object_class->constructed (object);

  DEBUG ("%s (%p) constructed", tp_proxy_get_object_path (object), object);

  g_assert (tp_proxy_get_factory (self) != NULL);

  /* Connect to my own StatusChanged signal.
   * The connection hasn't had a chance to become invalid yet, so we can
   * assume that this signal connection will work */
  tp_cli_connection_connect_to_status_changed (self,
      tp_connection_status_changed_cb, NULL, NULL, NULL, NULL);
  tp_cli_connection_connect_to_connection_error (self,
      tp_connection_connection_error_cb, NULL, NULL, NULL, NULL);
  tp_cli_connection_connect_to_self_contact_changed (self,
      on_self_contact_changed, NULL, NULL, NULL, NULL);

  object_path = tp_proxy_get_object_path (TP_PROXY (self));
  g_assert (_tp_connection_parse (object_path, '/',
      &(self->priv->proto_name), &(self->priv->cm_name)));

  tp_cli_dbus_properties_call_get_all (self, -1,
      TP_IFACE_CONNECTION, _tp_connection_got_properties, NULL, NULL, NULL);

  g_signal_connect (self, "invalidated",
      G_CALLBACK (tp_connection_invalidated), NULL);
}

static void
tp_connection_init (TpConnection *self)
{
  self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, TP_TYPE_CONNECTION,
      TpConnectionPrivate);

  /* This is conceptually part of Connection core now. The only reason
   * it's kept separate is to reduce D-Bus traffic, since the
   * ChannelDispatcher implementation is normally the only thing
   * that needs to see its properties or signals. */
  tp_proxy_add_interface_by_id ((TpProxy *) self,
      TP_IFACE_QUARK_CONNECTION_INTERFACE_REQUESTS);

  self->priv->status = TP_UNKNOWN_CONNECTION_STATUS;
  self->priv->status_reason = TP_CONNECTION_STATUS_REASON_NONE_SPECIFIED;
  self->priv->contacts = g_hash_table_new (g_direct_hash, g_direct_equal);
  self->priv->introspection_call = NULL;
  self->priv->interests = tp_intset_new ();
  self->priv->contact_groups = g_ptr_array_new_with_free_func (g_free);
  g_ptr_array_add (self->priv->contact_groups, NULL);
  self->priv->roster = g_hash_table_new_full (g_direct_hash, g_direct_equal,
      NULL, g_object_unref);
  self->priv->contacts_changed_queue = g_queue_new ();

  g_queue_init (&self->priv->capabilities_queue);

  self->priv->blocked_contacts = g_ptr_array_new_with_free_func (
      g_object_unref);

  self->priv->blocked_changed_queue = g_queue_new ();
}

static void
tp_connection_finalize (GObject *object)
{
  TpConnection *self = TP_CONNECTION (object);

  DEBUG ("%p", self);

  tp_clear_pointer (&self->priv->cm_name, g_free);
  tp_clear_pointer (&self->priv->proto_name, g_free);

  /* not true unless we were finalized before we were ready */
  if (self->priv->introspect_needed != NULL)
    {
      g_list_free (self->priv->introspect_needed);
      self->priv->introspect_needed = NULL;
    }

  g_free (self->priv->connection_error);
  self->priv->connection_error = NULL;

  if (self->priv->connection_error_details != NULL)
    {
      g_hash_table_unref (self->priv->connection_error_details);
      self->priv->connection_error_details = NULL;
    }

  if (self->priv->avatar_request_queue != NULL)
    {
      g_array_unref (self->priv->avatar_request_queue);
      self->priv->avatar_request_queue = NULL;
    }

  if (self->priv->avatar_request_idle_id != 0)
    {
      g_source_remove (self->priv->avatar_request_idle_id);
      self->priv->avatar_request_idle_id = 0;
    }

  tp_contact_info_spec_list_free (self->priv->contact_info_supported_fields);
  self->priv->contact_info_supported_fields = NULL;

  tp_clear_pointer (&self->priv->balance_currency, g_free);
  tp_clear_pointer (&self->priv->balance_uri, g_free);
  tp_clear_pointer (&self->priv->cm_name, g_free);
  tp_clear_pointer (&self->priv->proto_name, g_free);
  tp_clear_pointer (&self->priv->last_known_self_id, g_free);


  ((GObjectClass *) tp_connection_parent_class)->finalize (object);
}

static void
contact_notify_disposed (gpointer k G_GNUC_UNUSED,
    gpointer v,
    gpointer d G_GNUC_UNUSED)
{
  _tp_contact_connection_disposed (v);
}


static void
tp_connection_dispose (GObject *object)
{
  TpConnection *self = TP_CONNECTION (object);

  DEBUG ("%p", object);

  if (self->priv->account != NULL)
    {
      g_object_remove_weak_pointer ((GObject *) self->priv->account,
          (gpointer) &self->priv->account);
      self->priv->account = NULL;
    }

  tp_clear_pointer (&self->priv->contact_groups, g_ptr_array_unref);
  tp_clear_pointer (&self->priv->roster, g_hash_table_unref);
  tp_clear_pointer (&self->priv->contacts_changed_queue,
      _tp_connection_contacts_changed_queue_free);
  tp_clear_pointer (&self->priv->blocked_changed_queue,
      _tp_connection_blocked_changed_queue_free);

  if (self->priv->contacts != NULL)
    {
      g_hash_table_foreach (self->priv->contacts, contact_notify_disposed,
          NULL);
      tp_clear_pointer (&self->priv->contacts, g_hash_table_unref);
    }

  tp_clear_object (&self->priv->capabilities);
  tp_clear_pointer (&self->priv->avatar_requirements,
      tp_avatar_requirements_destroy);

  if (self->priv->interests != NULL)
    {
      guint size = tp_intset_size (self->priv->interests);

      /* Before freeing the set of tokens in which we declared an
       * interest, cancel those interests. We'll still get the signals
       * if there's another interested TpConnection in this process,
       * because the CM uses distributed refcounting. */
      if (size > 0)
        {
          TpIntsetFastIter iter;
          GPtrArray *strings;
          guint element;

          strings = g_ptr_array_sized_new (size + 1);

          tp_intset_fast_iter_init (&iter, self->priv->interests);

          while (tp_intset_fast_iter_next (&iter, &element))
            g_ptr_array_add (strings,
                (gchar *) g_quark_to_string (element));

          g_ptr_array_add (strings, NULL);

          /* no callback - if the CM replies, we'll ignore it anyway */
          tp_cli_connection_call_remove_client_interest (self, -1,
              (const gchar **) strings->pdata, NULL, NULL, NULL, NULL);
          g_ptr_array_unref (strings);
        }

      tp_intset_destroy (self->priv->interests);
      self->priv->interests = NULL;
    }

  tp_clear_pointer (&self->priv->blocked_contacts, g_ptr_array_unref);
  g_clear_object (&self->priv->self_contact);

  ((GObjectClass *) tp_connection_parent_class)->dispose (object);
}

enum {
    FEAT_CORE,
    FEAT_CONNECTED,
    FEAT_CAPABILITIES,
    FEAT_AVATAR_REQUIREMENTS,
    FEAT_CONTACT_INFO,
    FEAT_BALANCE,
    FEAT_CONTACT_LIST,
    FEAT_CONTACT_LIST_PROPS,
    FEAT_CONTACT_GROUPS,
    FEAT_CONTACT_BLOCKING,
    FEAT_ALIASING,
    N_FEAT
};

static const TpProxyFeature *
tp_connection_list_features (TpProxyClass *cls G_GNUC_UNUSED)
{
  static TpProxyFeature features[N_FEAT + 1] = { { 0 } };
  static GQuark need_avatars[2] = {0, 0};
  static GQuark need_contact_info[2] = {0, 0};
  static GQuark need_balance[2] = {0, 0};
  static GQuark need_contact_list[2] = {0, 0};
  static GQuark need_contact_groups[2] = {0, 0};
  static GQuark need_contact_blocking[2] = {0, 0};
  static GQuark depends_contact_list[2] = {0, 0};
  static GQuark need_aliasing[2] = {0, 0};

  if (G_LIKELY (features[0].name != 0))
    return features;

  features[FEAT_CORE].name = TP_CONNECTION_FEATURE_CORE;
  features[FEAT_CORE].core = TRUE;

  features[FEAT_CONNECTED].name = TP_CONNECTION_FEATURE_CONNECTED;

  features[FEAT_CAPABILITIES].name = TP_CONNECTION_FEATURE_CAPABILITIES;
  features[FEAT_CAPABILITIES].prepare_async =
      tp_connection_prepare_capabilities_async;

  features[FEAT_AVATAR_REQUIREMENTS].name = TP_CONNECTION_FEATURE_AVATAR_REQUIREMENTS;
  features[FEAT_AVATAR_REQUIREMENTS].prepare_async =
    _tp_connection_prepare_avatar_requirements_async;
  need_avatars[0] = TP_IFACE_QUARK_CONNECTION_INTERFACE_AVATARS1;
  features[FEAT_AVATAR_REQUIREMENTS].interfaces_needed = need_avatars;

  features[FEAT_CONTACT_INFO].name = TP_CONNECTION_FEATURE_CONTACT_INFO;
  features[FEAT_CONTACT_INFO].prepare_async =
    _tp_connection_prepare_contact_info_async;
  need_contact_info[0] = TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACT_INFO1;
  features[FEAT_CONTACT_INFO].interfaces_needed = need_contact_info;

  features[FEAT_BALANCE].name = TP_CONNECTION_FEATURE_BALANCE;
  features[FEAT_BALANCE].prepare_async = tp_connection_prepare_balance_async;
  need_balance[0] = TP_IFACE_QUARK_CONNECTION_INTERFACE_BALANCE1;
  features[FEAT_BALANCE].interfaces_needed = need_balance;

  features[FEAT_CONTACT_LIST].name = TP_CONNECTION_FEATURE_CONTACT_LIST;
  features[FEAT_CONTACT_LIST].prepare_async = _tp_connection_prepare_contact_list_async;
  need_contact_list[0] = TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACT_LIST1;
  features[FEAT_CONTACT_LIST].interfaces_needed = need_contact_list;
  depends_contact_list[0] = TP_CONNECTION_FEATURE_CONTACT_LIST_PROPERTIES;
  features[FEAT_CONTACT_LIST].depends_on = depends_contact_list;

  features[FEAT_CONTACT_LIST_PROPS].name = TP_CONNECTION_FEATURE_CONTACT_LIST_PROPERTIES;
  features[FEAT_CONTACT_LIST_PROPS].prepare_async = _tp_connection_prepare_contact_list_props_async;
  features[FEAT_CONTACT_LIST_PROPS].interfaces_needed = need_contact_list;

  features[FEAT_CONTACT_GROUPS].name = TP_CONNECTION_FEATURE_CONTACT_GROUPS;
  features[FEAT_CONTACT_GROUPS].prepare_async = _tp_connection_prepare_contact_groups_async;
  need_contact_groups[0] = TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACT_GROUPS1;
  features[FEAT_CONTACT_GROUPS].interfaces_needed = need_contact_groups;

  features[FEAT_CONTACT_BLOCKING].name = TP_CONNECTION_FEATURE_CONTACT_BLOCKING;
  features[FEAT_CONTACT_BLOCKING].prepare_async = _tp_connection_prepare_contact_blocking_async;
  need_contact_blocking[0] = TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACT_BLOCKING1;
  features[FEAT_CONTACT_BLOCKING].interfaces_needed = need_contact_blocking;

  features[FEAT_ALIASING].name = TP_CONNECTION_FEATURE_ALIASING;
  features[FEAT_ALIASING].prepare_async = _tp_connection_prepare_aliasing_async;
  need_aliasing[0] = TP_IFACE_QUARK_CONNECTION_INTERFACE_ALIASING1;
  features[FEAT_ALIASING].interfaces_needed = need_aliasing;

  /* assert that the terminator at the end is there */
  g_assert (features[N_FEAT].name == 0);

  return features;
}

static void
tp_connection_class_init (TpConnectionClass *klass)
{
  GParamSpec *param_spec;
  TpProxyClass *proxy_class = (TpProxyClass *) klass;
  GObjectClass *object_class = (GObjectClass *) klass;

  g_type_class_add_private (klass, sizeof (TpConnectionPrivate));

  object_class->constructed = tp_connection_constructed;
  object_class->get_property = tp_connection_get_property;
  object_class->dispose = tp_connection_dispose;
  object_class->finalize = tp_connection_finalize;

  proxy_class->interface = TP_IFACE_QUARK_CONNECTION;
  /* If you change this, you must also change TpChannel to stop asserting
   * that its connection has a unique name */
  proxy_class->must_have_unique_name = TRUE;
  proxy_class->list_features = tp_connection_list_features;

  /**
   * TpConnection:status:
   *
   * This connection's status, or %TP_UNKNOWN_CONNECTION_STATUS if we don't
   * know yet.
   *
   * To wait for a valid status (and other properties), call
   * tp_proxy_prepare_async() with the feature %TP_CONNECTION_FEATURE_CORE.
   *
   * Since version 0.11.3, the change to status
   * %TP_CONNECTION_STATUS_CONNECTED is delayed slightly, until introspection
   * of the connection has finished.
   */
  param_spec = g_param_spec_uint ("status", "Status",
      "The status of this connection", 0, G_MAXUINT32,
      TP_UNKNOWN_CONNECTION_STATUS,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_STATUS,
      param_spec);

  /**
   * TpConnection:cm-name:
   *
   * This connection's connection manager name.
   *
   * Since: 0.19.3
   */
  g_object_class_install_property (object_class, PROP_CM_NAME,
      g_param_spec_string ("cm-name",
          "Connection manager name",
          "The connection's connection manager name",
          NULL,
          G_PARAM_STATIC_STRINGS | G_PARAM_READABLE));

  /**
   * TpConnection:protocol-name:
   *
   * The connection's machine-readable protocol name, such as "jabber",
   * "msn" or "local-xmpp". Recommended names for most protocols can be
   * found in the Telepathy D-Bus Interface Specification.
   *
   * Since: 0.13.16
   *
   */
  g_object_class_install_property (object_class, PROP_PROTOCOL_NAME,
      g_param_spec_string ("protocol-name",
          "Protocol name",
          "The connection's protocol name",
          NULL,
          G_PARAM_STATIC_STRINGS | G_PARAM_READABLE));

  /**
   * TpConnection:self-contact:
   *
   * A #TpContact representing the local user on this connection,
   * or %NULL if not yet available.
   *
   * If the local user's unique identifier changes (for instance by using
   * /nick on IRC), this property will change to a different #TpContact object
   * representing the new identifier, and #GObject::notify will be emitted.
   *
   * The #TpContact object is guaranteed to have all of the features previously
   * passed to tp_client_factory_add_contact_features() prepared.
   *
   * To wait for a non-%NULL self-contact (and other properties), call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONNECTED.
   *
   * Since: 0.13.9
   */
  param_spec = g_param_spec_object ("self-contact", "Self contact",
      "The local user's Contact object on this connection", TP_TYPE_CONTACT,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_SELF_CONTACT,
      param_spec);

  /**
   * TpConnection:status-reason:
   *
   * To wait for a valid status (and other properties), call
   * tp_proxy_prepare_async() with the feature %TP_CONNECTION_FEATURE_CORE.
   *
   * The reason why #TpConnection:status changed to its current value,
   * or TP_CONNECTION_STATUS_REASON_NONE_SPECIFIED if unknown.
   * know yet.
   */
  param_spec = g_param_spec_uint ("status-reason", "Last status change reason",
      "The reason why #TpConnection:status changed to its current value",
      0, G_MAXUINT32, TP_CONNECTION_STATUS_REASON_NONE_SPECIFIED,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_STATUS_REASON,
      param_spec);

 /**
   * TpConnection:capabilities:
   *
   * The %TpCapabilities object representing the capabilities of this
   * connection, or NULL if we don't know yet.
   *
   * To wait for valid capability information, call tp_proxy_prepare_async()
   * with the feature %TP_CONNECTION_FEATURE_CAPABILITIES.
   */
  param_spec = g_param_spec_object ("capabilities", "Capabilities",
      "A TpCapabilities object representing the capabilities of the connection",
      TP_TYPE_CAPABILITIES,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_CAPABILITIES,
      param_spec);

  /**
   * TpConnection:balance:
   *
   * The Amount field of the Balance.AccountBalance property.
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature %TP_CONNECTION_FEATURE_BALANCE.
   *
   * See Also: tp_connection_get_balance()
   */
  param_spec = g_param_spec_int ("balance", "Balance Amount",
      "The Amount field of the Account Balance",
      G_MININT32, G_MAXINT32, 0,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_BALANCE,
      param_spec);

  /**
   * TpConnection:balance-scale:
   *
   * The Scale field of the Balance.AccountBalance property.
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature %TP_CONNECTION_FEATURE_BALANCE.
   *
   * See Also: tp_connection_get_balance()
   */
  param_spec = g_param_spec_uint ("balance-scale", "Balance Scale",
      "The Scale field of the Account Balance",
      0, G_MAXUINT32, G_MAXUINT32,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_BALANCE_SCALE,
      param_spec);

  /**
   * TpConnection:balance-currency:
   *
   * The Currency field of the Balance.AccountBalance property.
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature %TP_CONNECTION_FEATURE_BALANCE.
   *
   * See Also: tp_connection_get_balance()
   */
  param_spec = g_param_spec_string ("balance-currency", "Balance Currency",
      "The Currency field of the Account Balance",
      NULL,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_BALANCE_CURRENCY,
      param_spec);

  /**
   * TpConnection:balance-uri:
   *
   * The Balance.ManageCreditURI property.
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature %TP_CONNECTION_FEATURE_BALANCE.
   */
  param_spec = g_param_spec_string ("balance-uri", "Balance URI",
      "The URI for managing the account balance",
      NULL,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_BALANCE_URI,
      param_spec);

  /**
   * TpConnection::balance-changed:
   * @self: a channel
   * @balance: the value of the #TpConnection:balance property
   * @balance_scale: the value of the #TpConnection:balance-scale property
   * @balance_currency: the value of the #TpConnection:balance-currency property
   *
   * Emitted when at least one of the #TpConnection:balance,
   * #TpConnection:balance-scale or #TpConnection:balance-currency
   * property is changed.
   *
   * For this signal to be emitted, you must first call
   * tp_proxy_prepare_async() with the feature %TP_CONNECTION_FEATURE_BALANCE.
   *
   * Since: 0.15.1
   */
  signals[SIGNAL_BALANCE_CHANGED] = g_signal_new ("balance-changed",
      G_OBJECT_CLASS_TYPE (klass),
      G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
      0,
      NULL, NULL, NULL,
      G_TYPE_NONE, 3, G_TYPE_INT, G_TYPE_UINT, G_TYPE_STRING);

  /**
   * TpConnection:contact-list-state:
   *
   * The progress made in retrieving the contact list.
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_LIST_PROPERTIES or
   * %TP_CONNECTION_FEATURE_CONTACT_LIST.
   *
   * Since: 0.15.5
   */
  param_spec = g_param_spec_uint ("contact-list-state", "ContactList state",
      "The state of the contact list",
      0, G_MAXUINT, TP_CONTACT_LIST_STATE_NONE,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_CONTACT_LIST_STATE,
      param_spec);

  /**
   * TpConnection:contact-list-persists:
   *
   * If true, presence subscriptions (in both directions) on this connection are
   * stored by the server or other infrastructure.
   *
   * If false, presence subscriptions on this connection are not stored.
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_LIST_PROPERTIES or
   * %TP_CONNECTION_FEATURE_CONTACT_LIST.
   *
   * Since: 0.15.5
   */
  param_spec = g_param_spec_boolean ("contact-list-persists",
      "ContactList persists", "Whether the contact list persists",
      FALSE,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_CONTACT_LIST_PERSISTS,
      param_spec);

  /**
   * TpConnection:can-change-contact-list:
   *
   * If true, presence subscription and publication can be changed using the
   * RequestSubscription, AuthorizePublication and RemoveContacts methods.
   *
   * Rational: link-local XMPP, presence is implicitly published to everyone in
   * the local subnet, so the user cannot control their presence publication.
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_LIST_PROPERTIES or
   * %TP_CONNECTION_FEATURE_CONTACT_LIST.
   *
   * Since: 0.15.5
   */
  param_spec = g_param_spec_boolean ("can-change-contact-list",
      "ContactList can change", "Whether the contact list can change",
      FALSE,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_CAN_CHANGE_CONTACT_LIST,
      param_spec);

  /**
   * TpConnection:request-uses-message:
   *
   * If true, the Message parameter to RequestSubscription is likely to be
   * significant, and user interfaces SHOULD prompt the user for a message to
   * send with the request; a message such as "I would like to add you to my
   * contact list", translated into the local user's language, might make a
   * suitable default.
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_LIST_PROPERTIES or
   * %TP_CONNECTION_FEATURE_CONTACT_LIST.
   *
   * Since: 0.15.5
   */
  param_spec = g_param_spec_boolean ("request-uses-message",
      "Request Uses Message", "Whether request uses message",
      FALSE,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_REQUEST_USES_MESSAGE,
      param_spec);

  /**
   * TpConnection:disjoint-groups:
   *
   * True if each contact can be in at most one group; false if each contact
   * can be in many groups.
   *
   * This property cannot change after the connection has moved to the
   * %TP_CONNECTION_STATUS_CONNECTED state. Until then, its value is undefined,
   * and it may change at any time, without notification.
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_GROUPS.
   *
   * Since: 0.15.5
   */
  param_spec = g_param_spec_boolean ("disjoint-groups",
      "Disjoint Groups", "Whether groups are disjoint",
      FALSE,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_DISJOINT_GROUPS,
      param_spec);

  /**
   * TpConnection:group-storage:
   *
   * Indicates the extent to which contacts' groups can be set and stored.
   *
   * This property cannot change after the connection has moved to the
   * %TP_CONNECTION_STATUS_CONNECTED state. Until then, its value is undefined,
   * and it may change at any time, without notification.
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_GROUPS.
   *
   * Since: 0.15.5
   */
  param_spec = g_param_spec_uint ("group-storage",
      "Group Storage", "Group storage capabilities",
      0, G_MAXUINT, TP_CONTACT_METADATA_STORAGE_TYPE_NONE,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_GROUP_STORAGE,
      param_spec);

  /**
   * TpConnection:contact-groups:
   *
   * The names of all groups that currently exist. This may be a larger set than
   * the union of all #TpContact:contact-groups properties, if the connection
   * allows groups to be empty.
   *
   * This property's value is not meaningful until the
   * #TpConnection:contact-list-state property has become
   * %TP_CONTACT_LIST_STATE_SUCCESS.
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_GROUPS.
   *
   * Since: 0.15.5
   */
  param_spec = g_param_spec_boxed ("contact-groups",
      "Contact Groups",
      "All existing contact groups",
      G_TYPE_STRV,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_CONTACT_GROUPS,
      param_spec);

  /**
   * TpConnection:can-report-abusive:
   *
   * If this property is %TRUE, contacts may be reported as abusive to the
   * server administrators by setting report_abusive to %TRUE when calling
   * tp_connection_block_contacts_async().
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_BLOCKING.
   *
   * Since: 0.17.0
   */
  param_spec = g_param_spec_boolean ("can-report-abusive",
      "Can report abusive",
      "Can report abusive",
      FALSE,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_CAN_REPORT_ABUSIVE,
      param_spec);

  /**
   * TpConnection:blocked-contacts:
   *
   * A #GPtrArray of blocked #TpContact. Changes are notified using the
   * #TpConnection::blocked-contacts-changed signal.
   *
   * These TpContact objects have been prepared with the desired features.
   * See tp_client_factory_add_contact_features() to define which
   * features needs to be prepared on them.
   *
   * For this property to be valid, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_BLOCKING.
   *
   * Since: 0.17.0
   */
  param_spec = g_param_spec_boxed ("blocked-contacts",
      "blocked contacts",
      "Blocked contacts",
      G_TYPE_PTR_ARRAY,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_BLOCKED_CONTACTS,
      param_spec);

  /**
   * TpConnection::groups-created:
   * @self: a #TpConnection
   * @added: a #GStrv with the names of the new groups.
   *
   * Emitted when new, empty groups are created. This will often be followed by
   * #TpContact::contact-groups-changed signals that add some members. When this
   * signal is emitted, #TpConnection:contact-groups property is already
   * updated.
   *
   * For this signal to be emited, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_GROUPS.
   *
   * Since: 0.15.5
   */
  signals[SIGNAL_GROUPS_CREATED] = g_signal_new (
      "groups-created",
      G_TYPE_FROM_CLASS (object_class),
      G_SIGNAL_RUN_LAST,
      0,
      NULL, NULL, NULL,
      G_TYPE_NONE, 1, G_TYPE_STRV);

  /**
   * TpConnection::groups-removed:
   * @self: A #TpConnection
   * @added: A #GStrv with the names of the groups.
   *
   * Emitted when one or more groups are removed. If they had members at the
   * time that they were removed, then immediately after this signal is emitted,
   * #TpContact::contact-groups-changed signals that their members were removed.
   * When this signal is emitted, #TpConnection:contact-groups property is
   * already updated.
   *
   * For this signal to be emited, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_GROUPS.
   *
   * Since: 0.15.5
   */
  signals[SIGNAL_GROUPS_REMOVED] = g_signal_new (
      "groups-removed",
      G_TYPE_FROM_CLASS (object_class),
      G_SIGNAL_RUN_LAST,
      0,
      NULL, NULL, NULL,
      G_TYPE_NONE, 1, G_TYPE_STRV);

  /**
   * TpConnection::group-renamed:
   * @self: a #TpConnection
   * @old_name: the old name of the group.
   * @new_name: the new name of the group.
   *
   * Emitted when a group is renamed, in protocols where this can be
   * distinguished from group creation, removal and membership changes.
   *
   * Immediately after this signal is emitted, #TpConnection::groups-created
   * signal the creation of a group with the new name, and
   * #TpConnection::groups-removed signal the removal of a group with the old
   * name.
   * If the group was not empty, immediately after those signals are emitted,
   * #TpContact::contact-groups-changed signal that the members of that group
   * were removed from the old name and added to the new name.
   *
   * When this signal is emitted, #TpConnection:contact-groups property is
   * already updated.
   *
   * For this signal to be emited, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_GROUPS.
   *
   * Since: 0.15.5
   */
  signals[SIGNAL_GROUP_RENAMED] = g_signal_new (
      "group-renamed",
      G_TYPE_FROM_CLASS (object_class),
      G_SIGNAL_RUN_LAST,
      0,
      NULL, NULL, NULL,
      G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_STRING);
  /**
   * TpConnection::contact-list-changed:
   * @self: a #TpConnection
   * @added: (type GLib.PtrArray) (element-type TelepathyGLib.Contact):
   *  a #GPtrArray of #TpContact added to contacts list
   * @removed: (type GLib.PtrArray) (element-type TelepathyGLib.Contact):
   *  a #GPtrArray of #TpContact removed from contacts list
   *
   * Notify of changes in the list of contacts as returned by
   * tp_connection_dup_contact_list(). It is guaranteed that all contacts have
   * desired features prepared. See
   * tp_client_factory_add_contact_features() to define which features
   * needs to be prepared.
   *
   * This signal is also emitted for the initial set of contacts once retrieved.
   *
   * For this signal to be emitted, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_LIST.
   *
   * Since: 0.15.5
   */
  signals[SIGNAL_CONTACT_LIST_CHANGED] = g_signal_new (
      "contact-list-changed",
      G_OBJECT_CLASS_TYPE (klass),
      G_SIGNAL_RUN_LAST,
      0,
      NULL, NULL, NULL,
      G_TYPE_NONE, 2, G_TYPE_PTR_ARRAY, G_TYPE_PTR_ARRAY);

  /**
   * TpConnection::blocked-contacts-changed:
   * @self: a #TpConnection
   * @added: (type GLib.PtrArray) (element-type TelepathyGLib.Contact):
   *  a #GPtrArray of #TpContact which have been blocked
   * @removed: (type GLib.PtrArray) (element-type TelepathyGLib.Contact):
   *  a #GPtrArray of #TpContact which are no longer blocked
   *
   * Notify of changes in #TpConnection:blocked-contacts.
   *  It is guaranteed that all contacts have desired features prepared. See
   * tp_client_factory_add_contact_features() to define which features
   * needs to be prepared.
   *
   * This signal is also emitted for the initial set of blocked contacts once
   * retrieved.
   *
   * For this signal to be emitted, you must first call
   * tp_proxy_prepare_async() with the feature
   * %TP_CONNECTION_FEATURE_CONTACT_BLOCKING.
   *
   * Since: 0.17.0
   */
  signals[SIGNAL_BLOCKED_CONTACTS_CHANGED] = g_signal_new (
      "blocked-contacts-changed",
      G_OBJECT_CLASS_TYPE (klass),
      G_SIGNAL_RUN_LAST,
      0,
      NULL, NULL, NULL,
      G_TYPE_NONE, 2, G_TYPE_PTR_ARRAY, G_TYPE_PTR_ARRAY);

}

TpConnection *
_tp_connection_new (TpClientFactory *factory,
    const gchar *bus_name,
    const gchar *object_path,
    GError **error)
{
  gchar *dup_path = NULL;
  gchar *dup_name = NULL;
  gchar *dup_unique_name = NULL;
  TpConnection *ret = NULL;

  g_return_val_if_fail (TP_IS_CLIENT_FACTORY (factory), NULL);
  g_return_val_if_fail (object_path != NULL ||
                        (bus_name != NULL && bus_name[0] != ':'), NULL);

  if (object_path == NULL)
    {
      dup_path = g_strdelimit (g_strdup_printf ("/%s", bus_name), ".", '/');
      object_path = dup_path;
    }
  else if (bus_name == NULL)
    {
      dup_name = g_strdelimit (g_strdup (object_path + 1), "/", '.');
      bus_name = dup_name;
    }

  if (!_tp_connection_parse (object_path, '/', NULL, NULL))
    {
      g_set_error (error, TP_DBUS_ERRORS, TP_DBUS_ERROR_INVALID_OBJECT_PATH,
          "Connection object path is not in the right format");
      goto finally;
    }

  if (!tp_dbus_check_valid_bus_name (bus_name,
        TP_DBUS_NAME_TYPE_NOT_BUS_DAEMON, error))
    goto finally;

  /* Resolve unique name if necessary */
  if (bus_name[0] != ':')
    {
      if (!_tp_dbus_connection_get_name_owner (
          tp_client_factory_get_dbus_connection (factory), 2000, bus_name,
          &dup_unique_name, error))
        goto finally;

      bus_name = dup_unique_name;

      if (!tp_dbus_check_valid_bus_name (bus_name,
          TP_DBUS_NAME_TYPE_UNIQUE, error))
        goto finally;
    }

  if (!tp_dbus_check_valid_object_path (object_path, error))
    goto finally;

  ret = TP_CONNECTION (g_object_new (TP_TYPE_CONNECTION,
        "bus-name", bus_name,
        "object-path", object_path,
        "factory", factory,
        NULL));

finally:
  g_free (dup_path);
  g_free (dup_name);
  g_free (dup_unique_name);

  return ret;
}

/**
 * tp_connection_get_account:
 * @self: a connection
 *
 * Return the the #TpAccount associated with this connection. Will return %NULL
 * if @self was not acquired from a #TpAccount via tp_account_get_connection(),
 * or if the account object got finalized in the meantime (#TpConnection does
 * not keep a strong ref on its #TpAccount).
 *
 * Returns: (transfer none): the account associated with this connection, or
 * %NULL.
 *
 * Since: 0.15.5
 */
TpAccount *
tp_connection_get_account (TpConnection *self)
{
  g_return_val_if_fail (TP_IS_CONNECTION (self), NULL);

  return self->priv->account;
}

void
_tp_connection_set_account (TpConnection *self,
    TpAccount *account)
{
  if (self->priv->account == account)
    return;

  g_assert (self->priv->account == NULL);
  g_assert (account != NULL);
  g_assert (tp_proxy_get_factory (self) == tp_proxy_get_factory (account));

  self->priv->account = account;
  g_object_add_weak_pointer ((GObject *) account,
      (gpointer) &self->priv->account);
}

/**
 * tp_connection_get_status:
 * @self: a connection
 * @reason: (out): a TpConnectionStatusReason, or %NULL
 *
 * If @reason is not %NULL it is set to the reason why "status" changed to its
 * current value, or %TP_CONNECTION_STATUS_REASON_NONE_SPECIFIED if unknown.
 *
 * Returns: This connection's status, or %TP_UNKNOWN_CONNECTION_STATUS if we
 * don't know yet.
 *
 * Since: 0.7.14
 */
TpConnectionStatus
tp_connection_get_status (TpConnection *self,
                          TpConnectionStatusReason *reason)
{
  g_return_val_if_fail (TP_IS_CONNECTION (self), TP_UNKNOWN_CONNECTION_STATUS);

  if (reason != NULL)
    *reason = self->priv->status_reason;

  return self->priv->status;
}

/**
 * tp_connection_get_cm_name:
 * @self: a #TpConnection
 *
 * <!-- -->
 *
 * Returns: the same as the #TpConnection:cm-name property
 *
 * Since: 0.19.3
 *
 */
const gchar *
tp_connection_get_cm_name (TpConnection *self)
{
    g_return_val_if_fail (TP_IS_CONNECTION (self), NULL);

    return self->priv->cm_name;
}

/**
 * tp_connection_get_protocol_name:
 * @self: a #TpConnection
 *
 * <!-- -->
 *
 * Returns: the same as the #TpConnection:protocol-name property
 *
 * Since: 0.13.16
 *
 */
const gchar *
tp_connection_get_protocol_name (TpConnection *self)
{
    g_return_val_if_fail (TP_IS_CONNECTION (self), NULL);

    return self->priv->proto_name;
}

static gboolean
_tp_connection_parse (const gchar *path_or_bus_name,
                      char delimiter,
                      gchar **protocol,
                      gchar **cm_name)
{
  const gchar *prefix;
  const gchar *cm_name_start;
  const gchar *protocol_start;
  const gchar *account_start;
  gchar *dup_cm_name = NULL;
  gchar *dup_protocol = NULL;

  g_return_val_if_fail (delimiter == '.' || delimiter == '/', FALSE);

  /* If CM respects the spec, object path and bus name should be in the form:
   * /im/telepathy/v1/Connection/cmname/proto/account
   * im.telepathy.v1.Connection.cmname.proto.account
   */
  if (delimiter == '.')
    prefix = TP_CONN_BUS_NAME_BASE;
  else
    prefix = TP_CONN_OBJECT_PATH_BASE;

  if (!g_str_has_prefix (path_or_bus_name, prefix))
    goto OUT;

  cm_name_start = path_or_bus_name + strlen (prefix);
  protocol_start = strchr (cm_name_start, delimiter);
  if (protocol_start == NULL)
    goto OUT;
  protocol_start++;

  account_start = strchr (protocol_start, delimiter);
  if (account_start == NULL)
    goto OUT;
  account_start++;

  dup_cm_name = g_strndup (cm_name_start, protocol_start - cm_name_start - 1);
  if (!tp_connection_manager_check_valid_name (dup_cm_name, NULL))
    {
      g_free (dup_cm_name);
      dup_cm_name = NULL;
      goto OUT;
    }

  dup_protocol = g_strndup (protocol_start, account_start - protocol_start - 1);
  if (!tp_connection_manager_check_valid_protocol_name (dup_protocol, NULL))
    {
      g_free (dup_protocol);
      dup_protocol = NULL;
      goto OUT;
    }

OUT:

  if (dup_protocol == NULL || dup_cm_name == NULL)
    {
      g_free (dup_protocol);
      g_free (dup_cm_name);
      return FALSE;
    }

  if (cm_name != NULL)
    *cm_name = dup_cm_name;
  else
    g_free (dup_cm_name);

  if (protocol != NULL)
    *protocol = dup_protocol;
  else
    g_free (dup_protocol);

  return TRUE;
}

static guint
get_presence_type_availability (TpConnectionPresenceType type)
{
  switch (type)
    {
      case TP_CONNECTION_PRESENCE_TYPE_UNSET:
        return 0;
      case TP_CONNECTION_PRESENCE_TYPE_UNKNOWN:
        return 1;
      case TP_CONNECTION_PRESENCE_TYPE_ERROR:
        return 2;
      case TP_CONNECTION_PRESENCE_TYPE_OFFLINE:
        return 3;
      case TP_CONNECTION_PRESENCE_TYPE_HIDDEN:
        return 4;
      case TP_CONNECTION_PRESENCE_TYPE_EXTENDED_AWAY:
        return 5;
      case TP_CONNECTION_PRESENCE_TYPE_AWAY:
        return 6;
      case TP_CONNECTION_PRESENCE_TYPE_BUSY:
        return 7;
      case TP_CONNECTION_PRESENCE_TYPE_AVAILABLE:
        return 8;
    }

  /* This is an unexpected presence type, treat it like UNKNOWN */
  return 1;
}

/**
 * tp_connection_presence_type_cmp_availability:
 * @p1: a #TpConnectionPresenceType
 * @p2: a #TpConnectionPresenceType
 *
 * Compares @p1 and @p2 like strcmp(). @p1 > @p2 means @p1 is more available
 * than @p2.
 *
 * The order used is: available > busy > away > xa > hidden > offline > error >
 * unknown > unset
 *
 * Returns: -1, 0 or 1, if @p1 is <, == or > than @p2.
 *
 * Since: 0.7.16
 */
gint
tp_connection_presence_type_cmp_availability (TpConnectionPresenceType p1,
                                              TpConnectionPresenceType p2)
{
  guint availability1;
  guint availability2;

  availability1 = get_presence_type_availability (p1);
  availability2 = get_presence_type_availability (p2);

  if (availability1 < availability2)
    return -1;

  if (availability1 > availability2)
    return +1;

  return 0;
}

/* Can return a contact that's not meant to be visible to library users
 * because it lacks an identifier */
TpContact *
_tp_connection_lookup_contact (TpConnection *self,
                               TpHandle handle)
{
  g_return_val_if_fail (TP_IS_CONNECTION (self), NULL);

  return g_hash_table_lookup (self->priv->contacts, GUINT_TO_POINTER (handle));
}


/* this could be done with proper weak references, but we know that every
 * connection will weakly reference all its contacts, so we can just do this
 * explicitly in tp_contact_dispose */
void
_tp_connection_remove_contact (TpConnection *self,
                               TpHandle handle,
                               TpContact *contact)
{
  TpContact *mine;

  g_return_if_fail (TP_IS_CONNECTION (self));
  g_return_if_fail (TP_IS_CONTACT (contact));

  mine = g_hash_table_lookup (self->priv->contacts, GUINT_TO_POINTER (handle));
  g_return_if_fail (mine == contact);
  g_hash_table_remove (self->priv->contacts, GUINT_TO_POINTER (handle));
}


void
_tp_connection_add_contact (TpConnection *self,
                            TpHandle handle,
                            TpContact *contact)
{
  g_return_if_fail (TP_IS_CONNECTION (self));
  g_return_if_fail (TP_IS_CONTACT (contact));
  g_return_if_fail (g_hash_table_lookup (self->priv->contacts,
        GUINT_TO_POINTER (handle)) == NULL);

  g_hash_table_insert (self->priv->contacts, GUINT_TO_POINTER (handle),
      contact);

  /* Set TP_CONTACT_FEATURE_CONTACT_BLOCKING if possible */
  if (tp_proxy_is_prepared (self, TP_CONNECTION_FEATURE_CONTACT_BLOCKING))
    {
      _tp_connection_set_contact_blocked (self, contact);
    }
}

/**
 * tp_connection_get_capabilities:
 * @self: a connection
 *
 * <!-- -->
 *
 * Returns: (transfer none): the same #TpCapabilities as the
 * #TpConnection:capabilities property
 * Since: 0.11.3
 */
TpCapabilities *
tp_connection_get_capabilities (TpConnection *self)
{
  g_return_val_if_fail (TP_IS_CONNECTION (self), FALSE);

  return self->priv->capabilities;
}

/*
 * tp_connection_get_detailed_error:
 * @self: a connection
 * @details: (out) (allow-none) (element-type utf8 GObject.Value) (transfer none):
 *  optionally used to return a map from string to #GValue, which must not be
 *  modified or destroyed by the caller
 *
 * If the connection has disconnected, return the D-Bus error name with which
 * it disconnected (in particular, this is %TP_ERROR_STR_CANCELLED if it was
 * disconnected by a user request).
 *
 * Otherwise, return %NULL, without altering @details.
 *
 * Returns: (transfer none) (allow-none): a D-Bus error name, or %NULL.
 *
 * Since: 0.11.4
 */
static const gchar *
tp_connection_get_detailed_error (TpConnection *self,
    const GHashTable **details)
{
  TpProxy *proxy = (TpProxy *) self;

  if (tp_proxy_get_invalidated (proxy) == NULL)
    return NULL;

  if (self->priv->connection_error != NULL)
    {
      g_assert (self->priv->connection_error_details != NULL);

      if (details != NULL)
        *details = self->priv->connection_error_details;

      return self->priv->connection_error;
    }
  else
    {
      /* no detailed error, but we *have* been invalidated - guess one based
       * on the invalidation reason */

      if (details != NULL)
        {
          if (self->priv->connection_error_details == NULL)
            {
              self->priv->connection_error_details = tp_asv_new (
                  "debug-message", G_TYPE_STRING, tp_proxy_get_invalidated (proxy)->message,
                  NULL);
            }

          *details = self->priv->connection_error_details;
        }

      if (tp_proxy_get_invalidated (proxy)->domain == TP_ERROR)
        {
          return tp_error_get_dbus_name (tp_proxy_get_invalidated (proxy)->code);
        }
      else if (tp_proxy_get_invalidated (proxy)->domain == TP_DBUS_ERRORS)
        {
          switch (tp_proxy_get_invalidated (proxy)->code)
            {
            case TP_DBUS_ERROR_NAME_OWNER_LOST:
              /* the CM probably crashed */
              return DBUS_ERROR_NO_REPLY;
              break;

            case TP_DBUS_ERROR_OBJECT_REMOVED:
            case TP_DBUS_ERROR_INCONSISTENT:
            /* ... and all other cases up to and including
             * TP_DBUS_ERROR_CANCELLED don't make sense in this context, so
             * just use the generic one for them too */
            default:
              return TP_ERROR_STR_DISCONNECTED;
            }
        }
      else
        {
          /* no idea what that means */
          return TP_ERROR_STR_DISCONNECTED;
        }
    }
}

/**
 * tp_connection_dup_detailed_error:
 * @self: a connection
 * @details: (out) (allow-none) (transfer full):
 *  optionally used to return a %G_VARIANT_TYPE_VARDICT with details
 *  of the error
 *
 * If the connection has disconnected, return the D-Bus error name with which
 * it disconnected (in particular, this is %TP_ERROR_STR_CANCELLED if it was
 * disconnected by a user request).
 *
 * Otherwise, return %NULL, without altering @details.
 *
 * Returns: (transfer full) (allow-none): a D-Bus error name, or %NULL.
 *
 * Since: 0.19.0
 */
gchar *
tp_connection_dup_detailed_error (TpConnection *self,
    GVariant **details)
{
  const GHashTable *asv;
  const gchar *error = tp_connection_get_detailed_error (self, &asv);

  if (error == NULL)
    return NULL;

  if (details != NULL)
    *details = g_variant_ref_sink (tp_asv_to_vardict (asv));

  return g_strdup (error);
}

/**
 * tp_connection_add_client_interest:
 * @self: a connection
 * @interested_in: a string identifying an interface or part of an interface
 *  to which this connection will subscribe
 *
 * Subscribe to any opt-in change notifications for @interested_in.
 *
 * For contact information, use #TpContact instead, which will call this
 * automatically.
 *
 * Since: 0.11.3
 */
void
tp_connection_add_client_interest (TpConnection *self,
    const gchar *interested_in)
{
  tp_connection_add_client_interest_by_id (self,
      g_quark_from_string (interested_in));
}

/**
 * tp_connection_add_client_interest_by_id: (skip)
 * @self: a connection
 * @interested_in: a quark identifying an interface or part of an interface
 *  to which this connection will subscribe
 *
 * Subscribe to any opt-in change notifications for @interested_in.
 *
 * Equivalent to, but a little more efficient than, calling
 * tp_connection_add_client_interest() for the string value of @interested_in.
 *
 * Since: 0.11.3
 */
void
tp_connection_add_client_interest_by_id (TpConnection *self,
    GQuark interested_in)
{
  TpProxy *proxy = (TpProxy *) self;
  const gchar *interest = g_quark_to_string (interested_in);
  const gchar *strv[2] = { interest, NULL };

  g_return_if_fail (TP_IS_CONNECTION (self));
  g_return_if_fail (interest != NULL);

  if (tp_proxy_get_invalidated (proxy) != NULL ||
      tp_intset_is_member (self->priv->interests, interested_in))
    return;

  tp_intset_add (self->priv->interests, interested_in);

  /* no-reply flag set, and we ignore any reply */
  tp_cli_connection_call_add_client_interest (self, -1,
      strv, NULL, NULL, NULL, NULL);
}

/**
 * tp_connection_get_self_contact:
 * @self: a connection
 *
 * Return a #TpContact representing the local user on this connection.
 *
 * The returned object is not necessarily valid after the main loop is
 * re-entered; ref it with g_object_ref() if you want to keep it.
 *
 * Returns: (transfer none): the value of the TpConnection:self-contact
 *  property, which may be %NULL
 *
 * Since: 0.13.9
 */
TpContact *
tp_connection_get_self_contact (TpConnection *self)
{
  g_return_val_if_fail (TP_IS_CONNECTION (self), NULL);
  return self->priv->self_contact;
}

/**
 * tp_connection_bind_connection_status_to_property:
 * @self: a #TpConnection
 * @target: the target #GObject
 * @target_property: the property on @target to bind (must be %G_TYPE_BOOLEAN)
 * @invert: %TRUE if you wish to invert the value of @target_property
 *   (i.e. %FALSE if connected)
 *
 * Binds the :status of @self to the boolean property of another
 * object using a #GBinding such that the @target_property will be set to
 * %TRUE when @self is connected (and @invert is %FALSE).
 *
 * @target_property will be synchronised immediately (%G_BINDING_SYNC_CREATE).
 * @invert can be interpreted as analogous to %G_BINDING_INVERT_BOOLEAN.
 *
 * For instance, this function can be used to bind the GtkWidget:sensitive
 * property to only make a widget sensitive when the account is connected.
 *
 * See g_object_bind_property() for more information.
 *
 * Returns: (transfer none): the #GBinding instance representing the binding
 *   between the @self and the @target. The binding is released whenever the
 *   #GBinding reference count reaches zero.
 * Since: 0.13.16
 */
GBinding *
tp_connection_bind_connection_status_to_property (TpConnection *self,
    gpointer target,
    const char *target_property,
    gboolean invert)
{
  g_return_val_if_fail (TP_IS_CONNECTION (self), NULL);

  return g_object_bind_property_full (self, "status",
      target, target_property,
      G_BINDING_SYNC_CREATE,
      _tp_bind_connection_status_to_boolean,
      NULL, GUINT_TO_POINTER (invert), NULL);
}

/**
 * tp_connection_get_balance:
 * @self: a #TpConnection
 * @balance: (out): a pointer to store the account balance (or %NULL)
 * @scale: (out): a pointer to store the balance scale (or %NULL)
 * @currency: (out) (transfer none): a pointer to store the balance
 *   currency (or %NULL)
 *
 * If @self has a valid account balance, returns %TRUE and sets the variables
 * pointed to by @balance, @scale and @currency to the appropriate fields
 * of the Balance.AccountBalance property.
 *
 * The monetary value of the balance is expressed as a fixed-point number,
 * @balance, with a decimal scale defined by @scale; for instance a @balance
 * of 1234 with @scale of 2 represents a value of "12.34" in the currency
 * represented by @currency.
 *
 * Requires %TP_CONNECTION_FEATURE_BALANCE to be prepared.
 *
 * Returns: %TRUE if the balance is valid (and the values set), %FALSE if the
 *   balance is invalid.
 * Since: 0.15.1
 */
gboolean
tp_connection_get_balance (TpConnection *self,
    gint *balance,
    guint *scale,
    const gchar **currency)
{
  g_return_val_if_fail (TP_IS_CONNECTION (self), FALSE);

  if (self->priv->balance_currency == NULL)
    return FALSE;

  if (self->priv->balance == 0 &&
      self->priv->balance_scale == G_MAXUINT32 &&
      tp_str_empty (self->priv->balance_currency))
    return FALSE;

  if (balance != NULL)
    *balance = self->priv->balance;

  if (scale != NULL)
    *scale = self->priv->balance_scale;

  if (currency != NULL)
    *currency = self->priv->balance_currency;

  return TRUE;
}

/**
 * tp_connection_get_balance_uri:
 * @self: a #TpConnection
 *
 * The value of Balance.ManageCreditURI.
 *
 * Requires %TP_CONNECTION_FEATURE_BALANCE to be prepared.
 *
 * Returns: (transfer none): the #TpConnection:balance-uri property.
 * Since: 0.15.1
 */
const gchar *
tp_connection_get_balance_uri (TpConnection *self)
{
  g_return_val_if_fail (TP_IS_CONNECTION (self), FALSE);

  return self->priv->balance_uri;
}

static void
_tp_connection_void_cb (TpConnection *proxy,
    const GError *error,
    gpointer user_data,
    GObject *weak_object)
{
  GSimpleAsyncResult *result = G_SIMPLE_ASYNC_RESULT (user_data);

  if (error != NULL)
    g_simple_async_result_set_from_error (result, error);

  g_simple_async_result_complete_in_idle (result);
  g_object_unref (G_OBJECT (result));
}

/**
 * tp_connection_disconnect_async:
 * @self: a #TpConnection
 * @callback: a callback to call when the request is satisfied
 * @user_data: data to pass to @callback
 *
 * Disconnect the connection.
 *
 * This method is intended for use by AccountManager implementations,
 * such as Mission Control. To disconnect a connection managed by an
 * AccountManager, either use tp_account_request_presence_async()
 * or tp_account_set_enabled_async(), depending whether the intention is
 * to put the account offline temporarily, or disable it longer-term.
 *
 * Since: 0.17.5
 */
void
tp_connection_disconnect_async (TpConnection *self,
    GAsyncReadyCallback callback,
    gpointer user_data)
{
  GSimpleAsyncResult *result;

  g_return_if_fail (TP_IS_CONNECTION (self));

  result = g_simple_async_result_new (G_OBJECT (self), callback,
      user_data, tp_connection_disconnect_async);

  tp_cli_connection_call_disconnect (self, -1, _tp_connection_void_cb, result,
      NULL, NULL);
}

/**
 * tp_connection_disconnect_finish:
 * @self: a #TpConnection
 * @result: a #GAsyncResult
 * @error: a #GError to fill
 *
 * Interpret the result of tp_connection_disconnect_async().
 *
 * Returns: %TRUE if the call was successful, otherwise %FALSE
 *
 * Since: 0.17.5
 */
gboolean
tp_connection_disconnect_finish (TpConnection *self,
    GAsyncResult *result,
    GError **error)
{
  _tp_implement_finish_void (self, tp_connection_disconnect_async);
}