summaryrefslogtreecommitdiff
path: root/telepathy-glib/contact.c
blob: 31904132d723b4104e8231cdeac512b4e6302c43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
/* Object representing a Telepathy contact
 *
 * Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008 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 <telepathy-glib/contact.h>

#include <errno.h>

#include <telepathy-glib/capabilities-internal.h>
#include <telepathy-glib/dbus.h>
#include <telepathy-glib/gtypes.h>
#include <telepathy-glib/interfaces.h>
#include <telepathy-glib/util.h>

#define DEBUG_FLAG TP_DEBUG_CONTACTS
#include "telepathy-glib/connection-internal.h"
#include "telepathy-glib/debug-internal.h"

#include "telepathy-glib/_gen/signals-marshal.h"

/**
 * SECTION:contact
 * @title: TpContact
 * @short_description: object representing a contact
 * @see_also: #TpConnection
 *
 * #TpContact objects represent the contacts on a particular #TpConnection.
 *
 * Since: 0.7.18
 */

/**
 * TpContact:
 *
 * An object representing a contact on a #TpConnection.
 *
 * Contact objects support tracking a number of attributes of contacts, as
 * described by the #TpContactFeature flags. Features can be specified when
 * instantiating contact objects (with tp_connection_get_contacts_by_id() or
 * tp_connection_get_contacts_by_handle()), or added to an existing contact
 * object with tp_connection_upgrade_contacts(). For example, a client wishing
 * to keep track of a contact's alias would set #TP_CONTACT_FEATURE_ALIAS, and
 * then listen for the "notify::alias" signal, emitted whenever the
 * #TpContact:alias property changes.
 *
 * Note that releasing a #TpContact object might release handle references
 * held by calling tp_cli_connection_call_request_handles(),
 * tp_cli_connection_run_request_handles(),
 * tp_cli_connection_call_hold_handles(),
 * tp_cli_connection_run_hold_handles(),
 * tp_cli_connection_interface_contacts_call_get_contact_attributes() or
 * tp_cli_connection_interface_contacts_run_get_contact_attributes() directly.
 * Those functions should be avoided in favour of using #TpContact,
 * tp_connection_hold_handles(), tp_connection_request_handles() and
 * tp_connection_get_contact_attributes().
 *
 * Since: 0.7.18
 */

struct _TpContactClass {
    /*<private>*/
    GObjectClass parent_class;
};

struct _TpContact {
    /*<private>*/
    GObject parent;
    TpContactPrivate *priv;
};

/**
 * TpContactFeature:
 * @TP_CONTACT_FEATURE_ALIAS: #TpContact:alias
 * @TP_CONTACT_FEATURE_AVATAR_TOKEN: #TpContact:avatar-token
 * @TP_CONTACT_FEATURE_PRESENCE: #TpContact:presence-type,
 *  #TpContact:presence-status and #TpContact:presence-message
 * @TP_CONTACT_FEATURE_LOCATION: #TpContact:location (available since 0.11.1)
 * @TP_CONTACT_FEATURE_CAPABILITIES: #TpContact:capabilities
 *  (available since 0.11.3)
 * @TP_CONTACT_FEATURE_AVATAR_DATA: #TpContact:avatar-file and
 *  #TpContact:avatar-mime-type. Implies %TP_CONTACT_FEATURE_AVATAR_TOKEN
 *  (available since 0.11.6)
 * @TP_CONTACT_FEATURE_CONTACT_INFO: #TpContact:contact-info
 *  (available since 0.11.7)
 * @TP_CONTACT_FEATURE_CLIENT_TYPES: #TpContact:client-types
 *  (available since 0.13.1)
 *
 * Enumeration representing the features a #TpContact can optionally support.
 * When requesting a #TpContact, library users specify the desired features;
 * the #TpContact code will only initialize state for those features, to
 * avoid unwanted D-Bus round-trips and signal connections.
 *
 * Since 0.11.5, there is a corresponding #GEnumClass type,
 * %TP_TYPE_CONTACT_FEATURE.
 *
 * Since: 0.7.18
 */

/**
 * NUM_TP_CONTACT_FEATURES:
 *
 * 1 higher than the highest #TpContactFeature supported by this version of
 * telepathy-glib.
 *
 * Since: 0.7.18
 */

/**
 * TP_TYPE_CONTACT_FEATURE:
 *
 * The #GEnumClass type of a #TpContactFeature.
 *
 * Since: 0.11.5
 */

G_DEFINE_TYPE (TpContact, tp_contact, G_TYPE_OBJECT)


enum {
    PROP_CONNECTION = 1,
    PROP_HANDLE,
    PROP_IDENTIFIER,
    PROP_ALIAS,
    PROP_AVATAR_TOKEN,
    PROP_AVATAR_FILE,
    PROP_AVATAR_MIME_TYPE,
    PROP_PRESENCE_TYPE,
    PROP_PRESENCE_STATUS,
    PROP_PRESENCE_MESSAGE,
    PROP_LOCATION,
    PROP_CAPABILITIES,
    PROP_CONTACT_INFO,
    PROP_CLIENT_TYPES,
    N_PROPS
};

enum {
    SIGNAL_PRESENCE_CHANGED,
    N_SIGNALS
};

static guint signals[N_SIGNALS] = {0};

/* The API allows for more than 32 features, but this implementation does
 * not. We can easily expand this later. */
typedef enum {
    CONTACT_FEATURE_FLAG_ALIAS = 1 << TP_CONTACT_FEATURE_ALIAS,
    CONTACT_FEATURE_FLAG_AVATAR_TOKEN = 1 << TP_CONTACT_FEATURE_AVATAR_TOKEN,
    CONTACT_FEATURE_FLAG_PRESENCE = 1 << TP_CONTACT_FEATURE_PRESENCE,
    CONTACT_FEATURE_FLAG_LOCATION = 1 << TP_CONTACT_FEATURE_LOCATION,
    CONTACT_FEATURE_FLAG_CAPABILITIES = 1 << TP_CONTACT_FEATURE_CAPABILITIES,
    CONTACT_FEATURE_FLAG_AVATAR_DATA = 1 << TP_CONTACT_FEATURE_AVATAR_DATA,
    CONTACT_FEATURE_FLAG_CONTACT_INFO = 1 << TP_CONTACT_FEATURE_CONTACT_INFO,
    CONTACT_FEATURE_FLAG_CLIENT_TYPES = 1 << TP_CONTACT_FEATURE_CLIENT_TYPES,
} ContactFeatureFlags;

struct _TpContactPrivate {
    /* basics */
    TpConnection *connection;
    TpHandle handle;
    gchar *identifier;
    ContactFeatureFlags has_features;

    /* aliasing */
    gchar *alias;

    /* avatars */
    gchar *avatar_token;
    GFile *avatar_file;
    gchar *avatar_mime_type;

    /* presence */
    TpConnectionPresenceType presence_type;
    gchar *presence_status;
    gchar *presence_message;

    /* location */
    GHashTable *location;

    /* client types */
    gchar **client_types;

    /* capabilities */
    TpCapabilities *capabilities;

    /* a list of TpContactInfoField */
    GList *contact_info;
};


/**
 * tp_contact_get_connection:
 * @self: a contact
 *
 * <!-- nothing more to say -->
 *
 * Returns: (transfer none): a borrowed reference to the #TpContact:connection
 *  (it must be referenced with g_object_ref if it must remain valid
 *  longer than the contact)
 *
 * Since: 0.7.18
 */
TpConnection *
tp_contact_get_connection (TpContact *self)
{
  g_return_val_if_fail (self != NULL, 0);

  return self->priv->connection;
}


/**
 * tp_contact_get_handle:
 * @self: a contact
 *
 * Return the contact's handle, which is of type %TP_HANDLE_TYPE_CONTACT,
 * or 0 if the #TpContact:connection has become invalid.
 *
 * This handle is referenced using the Telepathy D-Bus API and remains
 * referenced for as long as @self exists and the
 * #TpContact:connection remains valid.
 *
 * However, the caller of this function does not gain an additional reference
 * to the handle.
 *
 * Returns: the same handle as the #TpContact:handle property
 *
 * Since: 0.7.18
 */
TpHandle
tp_contact_get_handle (TpContact *self)
{
  g_return_val_if_fail (self != NULL, 0);

  return self->priv->handle;
}

/**
 * tp_contact_get_identifier:
 * @self: a contact
 *
 * Return the contact's identifier. This remains valid for as long as @self
 * exists; if the caller requires a string that will persist for longer than
 * that, it must be copied with g_strdup().
 *
 * Returns: the same non-%NULL identifier as the #TpContact:identifier property
 *
 * Since: 0.7.18
 */
const gchar *
tp_contact_get_identifier (TpContact *self)
{
  g_return_val_if_fail (self != NULL, NULL);
  /* identifier must be non-NULL by the time we're visible to library-user
   * code */
  g_return_val_if_fail (self->priv->identifier != NULL, NULL);

  return self->priv->identifier;
}

/**
 * tp_contact_has_feature:
 * @self: a contact
 * @feature: a desired feature
 *
 * <!-- -->
 *
 * Returns: %TRUE if @self has been set up to track the feature @feature
 *
 * Since: 0.7.18
 */
gboolean
tp_contact_has_feature (TpContact *self,
                        TpContactFeature feature)
{
  g_return_val_if_fail (self != NULL, FALSE);
  g_return_val_if_fail (feature < NUM_TP_CONTACT_FEATURES, FALSE);

  return ((self->priv->has_features & (1 << feature)) != 0);
}


/**
 * tp_contact_get_alias:
 * @self: a contact
 *
 * Return the contact's alias. This remains valid until the main loop
 * is re-entered; if the caller requires a string that will persist for
 * longer than that, it must be copied with g_strdup().
 *
 * Returns: the same non-%NULL alias as the #TpContact:alias
 *
 * Since: 0.7.18
 */
const gchar *
tp_contact_get_alias (TpContact *self)
{
  g_return_val_if_fail (self != NULL, NULL);
  /* identifier must be non-NULL by the time we're visible to library-user
   * code */
  g_return_val_if_fail (self->priv->identifier != NULL, NULL);

  if (self->priv->alias != NULL)
    return self->priv->alias;

  return self->priv->identifier;
}


/**
 * tp_contact_get_avatar_token:
 * @self: a contact
 *
 * Return the contact's avatar token. This remains valid until the main loop
 * is re-entered; if the caller requires a string that will persist for
 * longer than that, it must be copied with g_strdup().
 *
 * Returns: the same token as the #TpContact:avatar-token property
 *  (possibly %NULL)
 *
 * Since: 0.7.18
 */
const gchar *
tp_contact_get_avatar_token (TpContact *self)
{
  g_return_val_if_fail (self != NULL, NULL);

  return self->priv->avatar_token;
}

/**
 * tp_contact_get_avatar_file:
 * @self: a contact
 *
 * Return the contact's avatar file. This remains valid until the main loop
 * is re-entered; if the caller requires a #GFile that will persist for
 * longer than that, it must be reffed with g_object_ref().
 *
 * Returns: (transfer none): the same #GFile as the #TpContact:avatar-file property
 *  (possibly %NULL)
 *
 * Since: 0.11.6
 */
GFile *
tp_contact_get_avatar_file (TpContact *self)
{
  g_return_val_if_fail (self != NULL, NULL);

  return self->priv->avatar_file;
}

/**
 * tp_contact_get_avatar_mime_type:
 * @self: a contact
 *
 * Return the contact's avatar MIME type. This remains valid until the main loop
 * is re-entered; if the caller requires a string that will persist for
 * longer than that, it must be copied with g_strdup().
 *
 * Returns: the same MIME type as the #TpContact:avatar-mime-type property
 *  (possibly %NULL)
 *
 * Since: 0.11.6
 */
const gchar *
tp_contact_get_avatar_mime_type (TpContact *self)
{
  g_return_val_if_fail (self != NULL, NULL);

  return self->priv->avatar_mime_type;
}

/**
 * tp_contact_get_presence_type:
 * @self: a contact
 *
 * If this object has been set up to track %TP_CONTACT_FEATURE_PRESENCE
 * and the underlying connection supports either the Presence or
 * SimplePresence interfaces, return the type of the contact's presence.
 *
 * Otherwise, return %TP_CONNECTION_PRESENCE_TYPE_UNSET.
 *
 * Returns: the same presence type as the #TpContact:presence-type property
 *
 * Since: 0.7.18
 */
TpConnectionPresenceType
tp_contact_get_presence_type (TpContact *self)
{
  g_return_val_if_fail (self != NULL, TP_CONNECTION_PRESENCE_TYPE_UNSET);

  return self->priv->presence_type;
}


/**
 * tp_contact_get_presence_status:
 * @self: a contact
 *
 * Return the name of the contact's presence status, or an empty string.
 * This remains valid until the main loop is re-entered; if the caller
 * requires a string that will persist for longer than that, it must be
 * copied with g_strdup().
 *
 * Returns: the same non-%NULL status name as the #TpContact:presence-status
 *  property
 *
 * Since: 0.7.18
 */
const gchar *
tp_contact_get_presence_status (TpContact *self)
{
  g_return_val_if_fail (self != NULL, NULL);

  return (self->priv->presence_status == NULL ? "" :
      self->priv->presence_status);
}


/**
 * tp_contact_get_presence_message:
 * @self: a contact
 *
 * Return the contact's user-defined status message, or an empty string.
 * This remains valid until the main loop is re-entered; if the caller
 * requires a string that will persist for longer than that, it must be
 * copied with g_strdup().
 *
 * Returns: the same non-%NULL message as the #TpContact:presence-message
 *  property
 *
 * Since: 0.7.18
 */
const gchar *
tp_contact_get_presence_message (TpContact *self)
{
  g_return_val_if_fail (self != NULL, NULL);

  return (self->priv->presence_message == NULL ? "" :
      self->priv->presence_message);
}

/**
 * tp_contact_get_location:
 * @self: a contact
 *
 * Return the contact's user-defined location or %NULL if the location is
 * unspecified.
 * This remains valid until the main loop is re-entered; if the caller
 * requires a hash table that will persist for longer than that, it must be
 * reffed with g_hash_table_ref().
 *
 * Returns: (element-type utf8 GObject.Value) (transfer none): the same
 *  #GHashTable (or %NULL) as the #TpContact:location property
 *
 * Since: 0.11.1
 */
GHashTable *
tp_contact_get_location (TpContact *self)
{
  g_return_val_if_fail (self != NULL, NULL);

  return self->priv->location;
}

/**
 * tp_contact_get_client_types:
 * @self: a contact
 *
 * Return the contact's client types or %NULL if the client types are
 * unspecified.
 *
 * Returns: (array zero-terminated=1) (transfer none): the same
 *  #GStrv as the #TpContact:client-types property
 *
 * Since: 0.13.1
 */
const gchar * const *
tp_contact_get_client_types (TpContact *self)
{
  g_return_val_if_fail (self != NULL, NULL);

  return (const gchar * const *) self->priv->client_types;
}

/**
 * tp_contact_get_capabilities:
 * @self: a contact
 *
 * <!-- -->
 *
 * Returns: (transfer none): the same #TpCapabilities (or %NULL) as the
 * #TpContact:capabilities property
 *
 * Since: 0.11.3
 */
TpCapabilities *
tp_contact_get_capabilities (TpContact *self)
{
  g_return_val_if_fail (self != NULL, NULL);

  return self->priv->capabilities;
}

/**
 * tp_contact_get_contact_info:
 * @self: a #TpContact
 *
 * Returns a newly allocated #GList of contact's vCard fields. The list must be
 * freed with g_list_free() after used.
 *
 * Note that the #TpContactInfoField<!-- -->s in the returned #GList are not
 * dupped before returning from this function. One could copy every item in the
 * list using tp_contact_info_field_copy().
 *
 * Same as the #TpContact:contact-info property.
 *
 * Returns: (element-type TelepathyGLib.ContactInfoField) (transfer container):
 *  a #GList of #TpContactInfoField, or %NULL if the feature is not yet
 *  prepared.
 * Since: 0.11.7
 */
GList *
tp_contact_get_contact_info (TpContact *self)
{
  g_return_val_if_fail (TP_IS_CONTACT (self), NULL);

  return g_list_copy (self->priv->contact_info);
}

void
_tp_contact_connection_invalidated (TpContact *contact)
{
  /* The connection has gone away, so we no longer have a meaningful handle,
   * and will never have one again. */
  g_assert (contact->priv->handle != 0);
  contact->priv->handle = 0;
  g_object_notify ((GObject *) contact, "handle");
}


static void
tp_contact_dispose (GObject *object)
{
  TpContact *self = TP_CONTACT (object);

  if (self->priv->handle != 0)
    {
      g_assert (self->priv->connection != NULL);

      _tp_connection_remove_contact (self->priv->connection,
          self->priv->handle, self);

      self->priv->handle = 0;
    }

  tp_clear_object (&self->priv->connection);
  tp_clear_pointer (&self->priv->location, g_hash_table_unref);
  tp_clear_object (&self->priv->capabilities);
  tp_clear_object (&self->priv->avatar_file);

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


static void
tp_contact_finalize (GObject *object)
{
  TpContact *self = TP_CONTACT (object);

  g_free (self->priv->identifier);
  g_free (self->priv->alias);
  g_free (self->priv->avatar_token);
  g_free (self->priv->avatar_mime_type);
  g_free (self->priv->presence_status);
  g_free (self->priv->presence_message);
  g_strfreev (self->priv->client_types);
  tp_contact_info_list_free (self->priv->contact_info);

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


static void
tp_contact_get_property (GObject *object,
                         guint property_id,
                         GValue *value,
                         GParamSpec *pspec)
{
  TpContact *self = TP_CONTACT (object);

  switch (property_id)
    {
    case PROP_CONNECTION:
      g_value_set_object (value, self->priv->connection);
      break;

    case PROP_HANDLE:
      g_value_set_uint (value, self->priv->handle);
      break;

    case PROP_IDENTIFIER:
      g_assert (self->priv->identifier != NULL);
      g_value_set_string (value, self->priv->identifier);
      break;

    case PROP_ALIAS:
      /* tp_contact_get_alias actually has some logic, so avoid
       * duplicating it */
      g_value_set_string (value, tp_contact_get_alias (self));
      break;

    case PROP_AVATAR_TOKEN:
      g_value_set_string (value, self->priv->avatar_token);
      break;

    case PROP_AVATAR_FILE:
      g_value_set_object (value, self->priv->avatar_file);
      break;

    case PROP_AVATAR_MIME_TYPE:
      g_value_set_string (value, self->priv->avatar_mime_type);
      break;

    case PROP_PRESENCE_TYPE:
      g_value_set_uint (value, self->priv->presence_type);
      break;

    case PROP_PRESENCE_STATUS:
      g_value_set_string (value, tp_contact_get_presence_status (self));
      break;

    case PROP_PRESENCE_MESSAGE:
      g_value_set_string (value, tp_contact_get_presence_message (self));
      break;

    case PROP_LOCATION:
      g_value_set_boxed (value, tp_contact_get_location (self));
      break;

    case PROP_CAPABILITIES:
      g_value_set_object (value, tp_contact_get_capabilities (self));
      break;

    case PROP_CONTACT_INFO:
      g_value_set_boxed (value, self->priv->contact_info);
      break;

    case PROP_CLIENT_TYPES:
      g_value_set_boxed (value, tp_contact_get_client_types (self));
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
      break;
  }
}


static void
tp_contact_class_init (TpContactClass *klass)
{
  GObjectClass *object_class = (GObjectClass *) klass;
  GParamSpec *param_spec;

  g_type_class_add_private (klass, sizeof (TpContactPrivate));
  object_class->get_property = tp_contact_get_property;
  object_class->dispose = tp_contact_dispose;
  object_class->finalize = tp_contact_finalize;

  /**
   * TpContact:connection:
   *
   * The #TpConnection to which this contact belongs.
   */
  param_spec = g_param_spec_object ("connection", "TpConnection object",
      "Connection object that owns this channel",
      TP_TYPE_CONNECTION,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_CONNECTION, param_spec);

  /**
   * TpContact:handle:
   *
   * The contact's handle in the Telepathy D-Bus API, a handle of type
   * %TP_HANDLE_TYPE_CONTACT representing the string
   * given by #TpContact:identifier.
   *
   * This handle is referenced using the Telepathy D-Bus API and remains
   * referenced for as long as the #TpContact exists and the
   * #TpContact:connection remains valid.
   *
   * However, getting this property does not cause an additional reference
   * to the handle to be held.
   *
   * If the #TpContact:connection becomes invalid, this property is no longer
   * meaningful and will be set to 0.
   */
  param_spec = g_param_spec_uint ("handle",
      "Handle",
      "The TP_HANDLE_TYPE_CONTACT handle for this contact",
      0, G_MAXUINT32, 0,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_HANDLE, param_spec);

  /**
   * TpContact:identifier:
   *
   * The contact's identifier in the instant messaging protocol (e.g.
   * XMPP JID, SIP URI, AOL screenname or IRC nick - whatever the underlying
   * protocol uses to identify a user).
   *
   * This is never %NULL for contact objects that are visible to library-user
   * code.
   */
  param_spec = g_param_spec_string ("identifier",
      "IM protocol identifier",
      "The contact's identifier in the instant messaging protocol (e.g. "
        "XMPP JID, SIP URI, AOL screenname or IRC nick)",
      NULL,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_IDENTIFIER, param_spec);

  /**
   * TpContact:alias:
   *
   * The contact's alias if available, falling back to their
   * #TpContact:identifier if no alias is available or if the #TpContact has
   * not been set up to track %TP_CONTACT_FEATURE_ALIAS.
   *
   * This alias may have been supplied by the contact themselves, or by the
   * local user, so it does not necessarily unambiguously identify the contact.
   * However, it is suitable for use as a main "display name" for the contact.
   *
   * This is never %NULL for contact objects that are visible to library-user
   * code.
   */
  param_spec = g_param_spec_string ("alias",
      "Alias",
      "The contact's alias (display name)",
      NULL,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_ALIAS, param_spec);

  /**
   * TpContact:avatar-token:
   *
   * An opaque string representing state of the contact's avatar (depending on
   * the protocol, this might be a hash, a timestamp or something else), or
   * an empty string if there is no avatar.
   *
   * This may be %NULL if it is not known whether this contact has an avatar
   * or not (either for network protocol reasons, or because this #TpContact
   * has not been set up to track %TP_CONTACT_FEATURE_AVATAR_TOKEN).
   */
  param_spec = g_param_spec_string ("avatar-token",
      "Avatar token",
      "Opaque string representing the contact's avatar, or \"\", or NULL",
      NULL,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_AVATAR_TOKEN,
      param_spec);

  /**
   * TpContact:avatar-file:
   *
   * #GFile to the latest cached avatar image, or %NULL if this contact has
   * no avatar, or if the avatar data is not yet retrieved.
   *
   * When #TpContact:avatar-token changes, this property is not updated
   * immediately, but will be updated when the new avatar data is retrieved and
   * stored in cache. Until then, the file will keep its old value of the latest
   * cached avatar image.
   *
   * This is set to %NULL if %TP_CONTACT_FEATURE_AVATAR_DATA is not set on this
   * contact. Note that setting %TP_CONTACT_FEATURE_AVATAR_DATA will also
   * implicitly set %TP_CONTACT_FEATURE_AVATAR_TOKEN.
   *
   * Since: 0.11.6
   */
  param_spec = g_param_spec_object ("avatar-file",
      "Avatar file",
      "File to the latest cached avatar image, or %NULL",
      G_TYPE_FILE,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_AVATAR_FILE,
      param_spec);

  /**
   * TpContact:avatar-mime-type:
   *
   * MIME type of the latest cached avatar image, or %NULL if this contact has
   * no avatar, or if the avatar data is not yet retrieved.
   *
   * This is always the MIME type of the image given by #TpContact:avatar-file.
   *
   * Since: 0.11.6
   */
  param_spec = g_param_spec_string ("avatar-mime-type",
      "Avatar MIME type",
      "MIME type of the latest cached avatar image, or %NULL",
      NULL,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_AVATAR_MIME_TYPE,
      param_spec);

  /**
   * TpContact:presence-type:
   *
   * The #TpConnectionPresenceType representing the type of presence status
   * for this contact.
   *
   * This is provided so even unknown values for #TpContact:presence-status
   * can be classified into their fundamental types.
   *
   * This may be %TP_CONNECTION_PRESENCE_TYPE_UNSET if this #TpContact
   * has not been set up to track %TP_CONTACT_FEATURE_PRESENCE.
   */
  param_spec = g_param_spec_uint ("presence-type",
      "Presence type",
      "The TpConnectionPresenceType for this contact",
      0, G_MAXUINT32, TP_CONNECTION_PRESENCE_TYPE_UNSET,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_PRESENCE_TYPE,
      param_spec);

  /**
   * TpContact:presence-status:
   *
   * A string representing the presence status of this contact. This may be
   * a well-known string from the Telepathy specification, like "available",
   * or a connection-manager-specific string, like "out-to-lunch".
   *
   * This may be an empty string if this #TpContact object has not been set up
   * to track %TP_CONTACT_FEATURE_PRESENCE. It is never %NULL.
   */
  param_spec = g_param_spec_string ("presence-status",
      "Presence status",
      "Possibly connection-manager-specific string representing the "
        "contact's presence status",
      "",
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_PRESENCE_STATUS,
      param_spec);

  /**
   * TpContact:presence-message:
   *
   * If this contact has set a user-defined status message, that message;
   * if not, an empty string (which user interfaces may replace with a
   * localized form of the #TpContact:presence-status or
   * #TpContact:presence-type).
   *
   * This may be an empty string even if the contact has set a message,
   * if this #TpContact object has not been set up to track
   * %TP_CONTACT_FEATURE_PRESENCE. It is never %NULL.
   */
  param_spec = g_param_spec_string ("presence-message",
      "Presence message",
      "User-defined status message, or an empty string",
      "",
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_PRESENCE_MESSAGE,
      param_spec);

  /**
   * TpContact:location:
   *
   * If this contact has set a user-defined location, a string to
   * #GValue * hash table containing his location. If not, %NULL.
   * tp_asv_get_string() and similar functions can be used to access
   * the contents.
   *
   * This may be %NULL even if the contact has set a location,
   * if this #TpContact object has not been set up to track
   * %TP_CONTACT_FEATURE_LOCATION.
   *
   * Since: 0.11.1
   */
  param_spec = g_param_spec_boxed ("location",
      "Location",
      "User-defined location, or NULL",
      TP_HASH_TYPE_STRING_VARIANT_MAP,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_LOCATION,
      param_spec);

  /**
   * TpContact:capabilities:
   *
   * The capabilities supported by this contact. If the underlying Connection
   * doesn't support the ContactCapabilities interface, this property will
   * contain the capabilities supported by the connection.
   * Use tp_capabilities_is_specific_to_contact() to check if the capabilities
   * are specific to this #TpContact or not.
   *
   * This may be %NULL if this #TpContact object has not been set up to track
   * %TP_CONTACT_FEATURE_CAPABILITIES.
   *
   * Since: 0.11.3
   */
  param_spec = g_param_spec_object ("capabilities",
      "Capabilities",
      "Capabilities of the contact, or NULL",
      TP_TYPE_CAPABILITIES,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_CAPABILITIES,
      param_spec);

  /**
   * TpContact:contact-info:
   *
   * A #GList of #TpContactInfoField representing the vCard of this contact.
   *
   * This is set to %NULL if %TP_CONTACT_FEATURE_CONTACT_INFO is not set on this
   * contact.
   *
   * Since: 0.11.7
   */
  param_spec = g_param_spec_boxed ("contact-info",
      "Contact Info",
      "Information of the contact, or NULL",
      TP_TYPE_CONTACT_INFO_LIST,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_CONTACT_INFO,
      param_spec);

  /**
   * TpContact:client-types:
   *
   * A #GStrv containing the client types of this contact.
   *
   * This is set to %NULL if %TP_CONTACT_FEATURE_CLIENT_TYPES is not
   * set on this contact.
   *
   * Since: 0.13.1
   */
  param_spec = g_param_spec_boxed ("client-types",
      "Client types",
      "Client types of the contact, or NULL",
      G_TYPE_STRV,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_CLIENT_TYPES,
      param_spec);

  /**
   * TpContact::presence-changed:
   * @contact: A #TpContact
   * @type: The new value of #TpContact:presence-type
   * @status: The new value of #TpContact:presence-status
   * @message: The new value of #TpContact:presence-message
   *
   * Emitted when this contact's presence changes.
   *
   * Since: 0.11.7
   */
  signals[SIGNAL_PRESENCE_CHANGED] = g_signal_new ("presence-changed",
      G_TYPE_FROM_CLASS (object_class),
      G_SIGNAL_RUN_LAST,
      0,
      NULL, NULL,
      _tp_marshal_VOID__UINT_STRING_STRING,
      G_TYPE_NONE, 3, G_TYPE_UINT, G_TYPE_STRING, G_TYPE_STRING);
}


static TpContact *
tp_contact_ensure (TpConnection *connection,
                   TpHandle handle)
{
  TpContact *self = _tp_connection_lookup_contact (connection, handle);

  if (self != NULL)
    {
      g_assert (self->priv->handle == handle);
      return g_object_ref (self);
    }

  self = TP_CONTACT (g_object_new (TP_TYPE_CONTACT, NULL));

  self->priv->handle = handle;
  _tp_connection_add_contact (connection, handle, self);
  self->priv->connection = g_object_ref (connection);

  return self;
}

/**
 * tp_connection_dup_contact_if_possible:
 * @connection: a connection
 * @handle: a handle of type %TP_HANDLE_TYPE_CONTACT
 * @identifier: (transfer none): the normalized identifier (XMPP JID, etc.)
 *  corresponding to @handle, or %NULL if not known
 *
 * Try to return an existing contact object or create a new contact object
 * immediately.
 *
 * If tp_connection_has_immortal_handles() would return %TRUE and
 * @identifier is non-%NULL, this function always succeeds.
 *
 * On connections without immortal handles, it is not possible to guarantee
 * that @handle remains valid without making asynchronous D-Bus calls, so
 * it might be necessary to delay processing of messages or other events
 * until a #TpContact can be constructed asynchronously, for instance by using
 * tp_connection_get_contacts_by_id().
 *
 * Similarly, if @identifier is %NULL, it might not be possible to find the
 * identifier for @handle without making asynchronous D-Bus calls, so
 * it might be necessary to delay processing of messages or other events
 * until a #TpContact can be constructed asynchronously, for instance by using
 * tp_connection_get_contacts_by_handle().
 *
 * Returns: (transfer full): a contact or %NULL
 *
 * Since: 0.13.UNRELEASED
 */
TpContact *
tp_connection_dup_contact_if_possible (TpConnection *connection,
    TpHandle handle,
    const gchar *identifier)
{
  TpContact *ret;

  g_return_val_if_fail (TP_IS_CONNECTION (connection), NULL);
  g_return_val_if_fail (handle != 0, NULL);

  ret = _tp_connection_lookup_contact (connection, handle);

  if (ret != NULL && ret->priv->identifier != NULL)
    {
      g_object_ref (ret);
    }
  else if (tp_connection_has_immortal_handles (connection) &&
      identifier != NULL)
    {
      ret = tp_contact_ensure (connection, handle);

      if (ret->priv->identifier == NULL)
        {
          /* new object, I suppose we'll have to believe the caller */
          ret->priv->identifier = g_strdup (identifier);
        }
    }
  else
    {
      /* we don't already have a contact, and we can't make one without
       * D-Bus calls (either because we can't rely on the handle staying
       * static, or we don't know the identifier) */
      return NULL;
    }

  g_assert (ret->priv->handle == handle);

  if (G_UNLIKELY (identifier != NULL &&
        tp_strdiff (ret->priv->identifier, identifier)))
    {
      WARNING ("Either this client, or connection manager %s, is broken: "
          "handle %u is thought to be '%s', but we already have "
          "a TpContact that thinks the identifier is '%s'",
          tp_proxy_get_bus_name (connection), handle, identifier,
          ret->priv->identifier);
      g_object_unref (ret);
      return NULL;
    }

  return ret;
}

static void
tp_contact_init (TpContact *self)
{
  self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, TP_TYPE_CONTACT,
      TpContactPrivate);

  self->priv->client_types = NULL;
}


typedef struct _ContactsContext ContactsContext;
typedef void (*ContactsProc) (ContactsContext *self);
typedef enum { CB_BY_HANDLE, CB_BY_ID, CB_UPGRADE } ContactsSignature;

struct _ContactsContext {
    gsize refcount;

    /* owned */
    TpConnection *connection;
    /* array of owned TpContact; preallocated but empty until handles have
     * been held or requested */
    GPtrArray *contacts;
    /* array of handles; empty until RequestHandles has returned, if we
     * started from IDs */
    GArray *handles;
    /* array of handles; empty until RequestHandles has returned, if we
     * started from IDs */
    GArray *invalid;

    /* strv of IDs; NULL unless we started from IDs */
    GPtrArray *request_ids;
    /* ID => GError, NULL unless we started from IDs */
    GHashTable *request_errors;

    /* features we need before this request can finish */
    ContactFeatureFlags wanted;

    /* callback for when we've finished, plus the usual misc */
    ContactsSignature signature;
    union {
        TpConnectionContactsByHandleCb by_handle;
        TpConnectionContactsByIdCb by_id;
        TpConnectionUpgradeContactsCb upgrade;
    } callback;
    gpointer user_data;
    GDestroyNotify destroy;
    GObject *weak_object;

    /* Whether or not our weak object died*/
    gboolean no_purpose_in_life;

    /* queue of ContactsProc */
    GQueue todo;

    /* index into handles or ids, only used when the first HoldHandles call
     * failed with InvalidHandle, or the RequestHandles call failed with
     * NotAvailable */
    guint next_index;

    /* TRUE if all contacts already have IDs */
    gboolean contacts_have_ids;
};

/* This code (and lots of telepathy-glib, really) won't work if this
 * assertion fails, because we put function pointers in a GQueue. If anyone
 * cares about platforms where this fails, fixing this would involve
 * slice-allocating sizeof (GCallback) bytes repeatedly, and putting *those*
 * in the queue. */
G_STATIC_ASSERT (sizeof (GCallback) == sizeof (gpointer));

static void
contacts_context_weak_notify (gpointer data,
  GObject *dead)
{
  ContactsContext *c = data;

  g_assert (c->weak_object == dead);
  c->no_purpose_in_life = TRUE;
  c->weak_object = NULL;
}

static ContactsContext *
contacts_context_new (TpConnection *connection,
                      guint n_contacts,
                      ContactFeatureFlags want_features,
                      ContactsSignature signature,
                      gpointer user_data,
                      GDestroyNotify destroy,
                      GObject *weak_object)
{
  ContactsContext *c = g_slice_new0 (ContactsContext);

  c->refcount = 1;
  c->connection = g_object_ref (connection);
  c->contacts = g_ptr_array_sized_new (n_contacts);
  c->handles = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle), n_contacts);
  c->invalid = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle), n_contacts);

  c->wanted = want_features;
  c->signature = signature;
  c->user_data = user_data;
  c->destroy = destroy;
  c->weak_object = weak_object;

  if (c->weak_object != NULL)
    g_object_weak_ref (c->weak_object, contacts_context_weak_notify, c);

  g_queue_init (&c->todo);

  return c;
}


static void
contacts_context_unref (gpointer p)
{
  ContactsContext *c = p;

  if ((--c->refcount) > 0)
    return;

  g_assert (c->connection != NULL);
  tp_clear_object (&c->connection);

  g_queue_clear (&c->todo);

  g_assert (c->contacts != NULL);
  g_ptr_array_foreach (c->contacts, (GFunc) g_object_unref, NULL);
  g_ptr_array_free (c->contacts, TRUE);
  c->contacts = NULL;

  g_assert (c->handles != NULL);
  g_array_free (c->handles, TRUE);
  c->handles = NULL;

  g_assert (c->invalid != NULL);
  g_array_free (c->invalid, TRUE);
  c->invalid = NULL;

  if (c->request_ids != NULL)
    g_strfreev ((gchar **) g_ptr_array_free (c->request_ids, FALSE));

  c->request_ids = NULL;

  tp_clear_pointer (&c->request_errors, g_hash_table_destroy);

  if (c->destroy != NULL)
    c->destroy (c->user_data);

  c->destroy = NULL;
  c->user_data = NULL;

  if (c->weak_object != NULL)
    g_object_weak_unref (c->weak_object, contacts_context_weak_notify, c);
  c->weak_object = NULL;

  g_slice_free (ContactsContext, c);
}


static void
contacts_context_fail (ContactsContext *c,
                       const GError *error)
{
  guint i;

  switch (c->signature)
    {
    case CB_BY_HANDLE:
      g_array_append_vals (c->invalid, c->handles->data, c->handles->len);

      c->callback.by_handle (c->connection, 0, NULL,
          c->invalid->len, (const TpHandle *) c->invalid->data,
          error, c->user_data, c->weak_object);
      return;
    case CB_BY_ID:
      /* -1 because NULL terminator is explicit */
      for (i = 0; i < c->request_ids->len - 1; i++)
        {
          const gchar *id = g_ptr_array_index (c->request_ids, i);

          if (!g_hash_table_lookup (c->request_errors, id))
            {
              g_hash_table_insert (c->request_errors,
                  g_strdup (id), g_error_copy (error));
            }
        }

      c->callback.by_id (c->connection, 0, NULL, NULL,
          c->request_errors, error, c->user_data, c->weak_object);
      return;
    case CB_UPGRADE:
      c->callback.upgrade (c->connection,
          c->contacts->len, (TpContact * const *) c->contacts->pdata,
          error, c->user_data, c->weak_object);
      return;
    default:
      g_assert_not_reached ();
    }
}


/**
 * TpConnectionContactsByHandleCb:
 * @connection: The connection
 * @n_contacts: The number of TpContact objects successfully created
 *  (one per valid handle), or 0 on unrecoverable errors
 * @contacts: (array length=n_contacts): An array of @n_contacts TpContact
 *  objects (this callback is not given a reference to any of these objects,
 *  and must call g_object_ref() on any that it will keep), or %NULL on
 *  unrecoverable errors
 * @n_failed: The number of invalid handles that were passed to
 *  tp_connection_get_contacts_by_handle() (or on unrecoverable errors,
 *  the total number of handles that were given)
 * @failed: (array length=n_failed): An array of @n_failed handles that were
 *  passed to tp_connection_get_contacts_by_handle() but turned out to be
 *  invalid (or on unrecoverable errors, all the handles that were given)
 * @error: %NULL on success, or an unrecoverable error that caused everything
 *  to fail
 * @user_data: the @user_data that was passed to
 *  tp_connection_get_contacts_by_handle()
 * @weak_object: the @weak_object that was passed to
 *  tp_connection_get_contacts_by_handle()
 *
 * Signature of a callback used to receive the result of
 * tp_connection_get_contacts_by_handle().
 *
 * If an unrecoverable error occurs (for instance, if @connection
 * becomes disconnected) the whole operation fails, and no contacts or
 * invalid handles are returned.
 *
 * If some or even all of the @handles passed to
 * tp_connection_get_contacts_by_handle() were not valid, this is not
 * considered to be a failure. @error will be %NULL in this situation,
 * @contacts will contain contact objects for those handles that were
 * valid (possibly none of them), and @invalid will contain the handles
 * that were not valid.
 *
 * Since: 0.7.18
 */

/**
 * TpConnectionContactsByIdCb:
 * @connection: The connection
 * @n_contacts: The number of TpContact objects successfully created
 *  (one per valid ID), or 0 on unrecoverable errors
 * @contacts: (array length=n_contacts): An array of @n_contacts TpContact
 *  objects (this callback is
 *  not given a reference to any of these objects, and must call
 *  g_object_ref() on any that it will keep), or %NULL on unrecoverable errors
 * @requested_ids: (array length=n_contacts): An array of @n_contacts valid IDs
 *  (JIDs, SIP URIs etc.)
 *  that were passed to tp_connection_get_contacts_by_id(), in an order
 *  corresponding to @contacts, or %NULL on unrecoverable errors
 * @failed_id_errors: (element-type utf8 GLib.Error): A hash table in which
 *  the keys are IDs and the values are errors (#GError)
 * @error: %NULL on success, or an unrecoverable error that caused everything
 *  to fail
 * @user_data: the @user_data that was passed to
 *  tp_connection_get_contacts_by_id()
 * @weak_object: the @weak_object that was passed to
 *  tp_connection_get_contacts_by_id()
 *
 * Signature of a callback used to receive the result of
 * tp_connection_get_contacts_by_id().
 *
 * @requested_ids contains the IDs that were converted to handles successfully.
 * The normalized form of requested_ids[i] is
 * tp_contact_get_identifier (contacts[i]).
 *
 * If some or even all of the @ids passed to
 * tp_connection_get_contacts_by_id() were not valid, this is not
 * considered to be a fatal error. @error will be %NULL in this situation,
 * @contacts will contain contact objects for those IDs that were
 * valid (it may be empty), and @failed_id_errors will map the IDs
 * that were not valid to a corresponding #GError (if the connection manager
 * complies with the Telepathy spec, it will have domain %TP_ERRORS and code
 * %TP_ERROR_INVALID_HANDLE).
 *
 * If an unrecoverable error occurs (for instance, if @connection
 * becomes disconnected) the whole operation fails, and no contacts
 * or requested IDs are returned. @failed_id_errors will contain all the IDs
 * that were requested, mapped to a corresponding #GError (either one
 * indicating that the ID was invalid, if that was determined before the
 * fatal error occurred, or a copy of @error).
 *
 * Since: 0.7.18
 */

/**
 * TpConnectionUpgradeContactsCb:
 * @connection: The connection
 * @n_contacts: The number of TpContact objects for which an upgrade was
 *  requested
 * @contacts: An array of @n_contacts TpContact objects (this callback is
 *  not given an extra reference to any of these objects, and must call
 *  g_object_ref() on any that it will keep)
 * @error: An unrecoverable error, or %NULL if the connection remains valid
 * @user_data: the @user_data that was passed to
 *  tp_connection_upgrade_contacts()
 * @weak_object: the @weak_object that was passed to
 *  tp_connection_upgrade_contacts()
 *
 * Signature of a callback used to receive the result of
 * tp_connection_upgrade_contacts().
 *
 * If an unrecoverable error occurs (for instance, if @connection becomes
 * disconnected) it is indicated by @error, but the contacts in @contacts
 * are still provided.
 *
 * Since: 0.7.18
 */


static void
contacts_context_continue (ContactsContext *c)
{
  if (c->no_purpose_in_life)
    return;

  if (g_queue_is_empty (&c->todo))
    {
      /* do some final sanity checking then hand over the contacts to the
       * library user */
      guint i;

      g_assert (c->contacts != NULL);
      g_assert (c->invalid != NULL);

      for (i = 0; i < c->contacts->len; i++)
        {
          TpContact *contact = TP_CONTACT (g_ptr_array_index (c->contacts, i));

          g_assert (contact->priv->identifier != NULL);
          g_assert (contact->priv->handle != 0);
        }

      switch (c->signature)
        {
        case CB_BY_HANDLE:
          c->callback.by_handle (c->connection,
              c->contacts->len, (TpContact * const *) c->contacts->pdata,
              c->invalid->len, (const TpHandle *) c->invalid->data,
              NULL, c->user_data, c->weak_object);
          break;
        case CB_BY_ID:
          c->callback.by_id (c->connection,
              c->contacts->len, (TpContact * const *) c->contacts->pdata,
              (const gchar * const *) c->request_ids->pdata,
              c->request_errors, NULL, c->user_data, c->weak_object);
          break;
        case CB_UPGRADE:
          c->callback.upgrade (c->connection,
              c->contacts->len, (TpContact * const *) c->contacts->pdata,
              NULL, c->user_data, c->weak_object);
          break;
        default:
          g_assert_not_reached ();
        }
    }
  else
    {
      /* bah! */
      ContactsProc next = g_queue_pop_head (&c->todo);

      next (c);
    }
}

static gboolean
contacts_context_idle_continue (gpointer data)
{
  contacts_context_continue (data);
  return FALSE;
}

static void
contacts_held_one (TpConnection *connection,
                   TpHandleType handle_type,
                   guint n_handles,
                   const TpHandle *handles,
                   const GError *error,
                   gpointer user_data,
                   GObject *weak_object)
{
  ContactsContext *c = user_data;

  g_assert (handle_type == TP_HANDLE_TYPE_CONTACT);
  g_assert (c->next_index < c->handles->len);

  if (error == NULL)
    {
      /* I have a handle of my very own. Just what I always wanted! */
      TpContact *contact;

      g_assert (n_handles == 1);
      g_assert (handles[0] != 0);
      g_debug ("%u vs %u", g_array_index (c->handles, TpHandle, c->next_index),
          handles[0]);
      g_assert (g_array_index (c->handles, TpHandle, c->next_index)
          == handles[0]);

      contact = tp_contact_ensure (connection, handles[0]);
      g_ptr_array_add (c->contacts, contact);
      c->next_index++;
    }
  else if (error->domain == TP_ERRORS &&
      error->code == TP_ERROR_INVALID_HANDLE)
    {
      g_array_append_val (c->invalid,
          g_array_index (c->handles, TpHandle, c->next_index));
      /* ignore the bad handle - we just won't return a TpContact for it */
      g_array_remove_index_fast (c->handles, c->next_index);
      /* do not increment next_index - another handle has been moved into that
       * position */
    }
  else
    {
      /* the connection fell down a well or something */
      contacts_context_fail (c, error);
      return;
    }

  /* Either continue to hold handles, or proceed along the slow path. */
  contacts_context_continue (c);
}


static void
contacts_hold_one (ContactsContext *c)
{
  c->refcount++;
  tp_connection_hold_handles (c->connection, -1,
      TP_HANDLE_TYPE_CONTACT, 1,
      &g_array_index (c->handles, TpHandle, c->next_index),
      contacts_held_one, c, contacts_context_unref, c->weak_object);
}


static void
contacts_held_handles (TpConnection *connection,
                       TpHandleType handle_type,
                       guint n_handles,
                       const TpHandle *handles,
                       const GError *error,
                       gpointer user_data,
                       GObject *weak_object)
{
  ContactsContext *c = user_data;

  g_assert (handle_type == TP_HANDLE_TYPE_CONTACT);
  g_assert (weak_object == c->weak_object);

  if (error == NULL)
    {
      /* I now own all n handles. It's like Christmas morning! */
      guint i;

      g_assert (n_handles == c->handles->len);
      g_assert (c->contacts->len == 0);

      for (i = 0; i < c->handles->len; i++)
        {
          g_ptr_array_add (c->contacts,
              tp_contact_ensure (connection,
                g_array_index (c->handles, TpHandle, i)));
        }
    }
  else if (error->domain == TP_ERRORS &&
      error->code == TP_ERROR_INVALID_HANDLE)
    {
      /* One of the handles is bad. We don't know which one :-( so split
       * the batch into a chain of calls. */
      guint i;

      for (i = 0; i < c->handles->len; i++)
        {
          g_queue_push_head (&c->todo, contacts_hold_one);
        }

      g_assert (c->next_index == 0);
    }
  else
    {
      /* the connection fell down a well or something */
      contacts_context_fail (c, error);
      return;
    }

  /* Either hold the handles individually, or proceed along the slow path. */
  contacts_context_continue (c);
}


static void
contacts_inspected (TpConnection *connection,
                    const gchar **ids,
                    const GError *error,
                    gpointer user_data,
                    GObject *weak_object)
{
  ContactsContext *c = user_data;

  g_assert (weak_object == c->weak_object);
  g_assert (c->handles->len == c->contacts->len);

  if (error != NULL)
    {
      /* the connection fell down a well or something */
      contacts_context_fail (c, error);
      return;
    }
  else if (G_UNLIKELY (g_strv_length ((GStrv) ids) != c->handles->len))
    {
      GError *e = g_error_new (TP_DBUS_ERRORS, TP_DBUS_ERROR_INCONSISTENT,
          "Connection manager %s is broken: we inspected %u "
          "handles but InspectHandles returned %u strings",
          tp_proxy_get_bus_name (connection), c->handles->len,
          g_strv_length ((GStrv) ids));

      WARNING ("%s", e->message);
      contacts_context_fail (c, e);
      g_error_free (e);
      return;
    }
  else
    {
      guint i;

      for (i = 0; i < c->contacts->len; i++)
        {
          TpContact *contact = g_ptr_array_index (c->contacts, i);

          g_assert (ids[i] != NULL);

          if (contact->priv->identifier == NULL)
            {
              contact->priv->identifier = g_strdup (ids[i]);
            }
          else if (tp_strdiff (contact->priv->identifier, ids[i]))
            {
              GError *e = g_error_new (TP_DBUS_ERRORS,
                  TP_DBUS_ERROR_INCONSISTENT,
                  "Connection manager %s is broken: contact handle %u "
                  "identifier changed from %s to %s",
                  tp_proxy_get_bus_name (connection), contact->priv->handle,
                  contact->priv->identifier, ids[i]);

              WARNING ("%s", e->message);
              contacts_context_fail (c, e);
              g_error_free (e);
              return;
            }
        }
    }

  contacts_context_continue (c);
}


static void
contacts_inspect (ContactsContext *c)
{
  guint i;

  g_assert (c->handles->len == c->contacts->len);

  for (i = 0; i < c->contacts->len; i++)
    {
      TpContact *contact = g_ptr_array_index (c->contacts, i);

      if (contact->priv->identifier == NULL)
        {
          c->refcount++;
          tp_cli_connection_call_inspect_handles (c->connection, -1,
              TP_HANDLE_TYPE_CONTACT, c->handles, contacts_inspected,
              c, contacts_context_unref, c->weak_object);
          return;
        }
    }

  /* else there's no need to inspect the contacts' handles, because we already
   * know all their identifiers */
  contacts_context_continue (c);
}


static void
contacts_requested_aliases (TpConnection *connection,
                            const gchar **aliases,
                            const GError *error,
                            gpointer user_data,
                            GObject *weak_object)
{
  ContactsContext *c = user_data;

  g_assert (c->handles->len == c->contacts->len);

  if (error == NULL)
    {
      guint i;

      if (G_UNLIKELY (g_strv_length ((GStrv) aliases) != c->contacts->len))
        {
          WARNING ("Connection manager %s is broken: we requested %u "
              "handles' aliases but got %u strings back",
              tp_proxy_get_bus_name (connection), c->contacts->len,
              g_strv_length ((GStrv) aliases));

          /* give up on the possibility of getting aliases, and just
           * move on */
          contacts_context_continue (c);
          return;
        }

      for (i = 0; i < c->contacts->len; i++)
        {
          TpContact *contact = g_ptr_array_index (c->contacts, i);
          const gchar *alias = aliases[i];

          contact->priv->has_features |= CONTACT_FEATURE_FLAG_ALIAS;
          g_free (contact->priv->alias);
          contact->priv->alias = g_strdup (alias);
          g_object_notify ((GObject *) contact, "alias");
        }
    }
  else
    {
      /* never mind, we can live without aliases */
      DEBUG ("GetAliases failed with %s %u: %s",
          g_quark_to_string (error->domain), error->code, error->message);
    }

  contacts_context_continue (c);
}


static void
contacts_got_aliases (TpConnection *connection,
                      GHashTable *handle_to_alias,
                      const GError *error,
                      gpointer user_data,
                      GObject *weak_object)
{
  ContactsContext *c = user_data;

  if (error == NULL)
    {
      guint i;

      for (i = 0; i < c->contacts->len; i++)
        {
          TpContact *contact = g_ptr_array_index (c->contacts, i);
          const gchar *alias = g_hash_table_lookup (handle_to_alias,
              GUINT_TO_POINTER (contact->priv->handle));

          contact->priv->has_features |= CONTACT_FEATURE_FLAG_ALIAS;
          g_free (contact->priv->alias);
          contact->priv->alias = NULL;

          if (alias != NULL)
            {
              contact->priv->alias = g_strdup (alias);
            }
          else
            {
              WARNING ("No alias returned for %u, will use ID instead",
                  contact->priv->handle);
            }

          g_object_notify ((GObject *) contact, "alias");
        }
    }
  else if ((error->domain == TP_ERRORS &&
      error->code == TP_ERROR_NOT_IMPLEMENTED) ||
      (error->domain == DBUS_GERROR &&
       error->code == DBUS_GERROR_UNKNOWN_METHOD))
    {
      /* GetAliases not implemented, fall back to (slow?) RequestAliases */
      c->refcount++;
      tp_cli_connection_interface_aliasing_call_request_aliases (connection,
          -1, c->handles, contacts_requested_aliases,
          c, contacts_context_unref, weak_object);
      return;
    }
  else
    {
      /* never mind, we can live without aliases */
      DEBUG ("GetAliases failed with %s %u: %s",
          g_quark_to_string (error->domain), error->code, error->message);
    }

  contacts_context_continue (c);
}


static void
contacts_aliases_changed (TpConnection *connection,
                          const GPtrArray *alias_structs,
                          gpointer user_data G_GNUC_UNUSED,
                          GObject *weak_object G_GNUC_UNUSED)
{
  guint i;

  for (i = 0; i < alias_structs->len; i++)
    {
      GValueArray *pair = g_ptr_array_index (alias_structs, i);
      TpHandle handle = g_value_get_uint (pair->values + 0);
      const gchar *alias = g_value_get_string (pair->values + 1);
      TpContact *contact = _tp_connection_lookup_contact (connection, handle);

      if (contact != NULL)
        {
          contact->priv->has_features |= CONTACT_FEATURE_FLAG_ALIAS;
          DEBUG ("Contact \"%s\" alias changed from \"%s\" to \"%s\"",
              contact->priv->identifier, contact->priv->alias, alias);
          g_free (contact->priv->alias);
          contact->priv->alias = g_strdup (alias);
          g_object_notify ((GObject *) contact, "alias");
        }
    }
}


static void
contacts_bind_to_aliases_changed (TpConnection *connection)
{
  if (!connection->priv->tracking_aliases_changed)
    {
      connection->priv->tracking_aliases_changed = TRUE;

      tp_cli_connection_interface_aliasing_connect_to_aliases_changed (
          connection, contacts_aliases_changed, NULL, NULL, NULL, NULL);
    }
}


static void
contacts_get_aliases (ContactsContext *c)
{
  guint i;

  g_assert (c->handles->len == c->contacts->len);

  contacts_bind_to_aliases_changed (c->connection);

  for (i = 0; i < c->contacts->len; i++)
    {
      TpContact *contact = g_ptr_array_index (c->contacts, i);

      if ((contact->priv->has_features & CONTACT_FEATURE_FLAG_ALIAS) == 0)
        {
          c->refcount++;
          tp_cli_connection_interface_aliasing_call_get_aliases (c->connection,
              -1, c->handles, contacts_got_aliases, c, contacts_context_unref,
              c->weak_object);
          return;
        }
    }

  /* else there's no need to get the contacts' aliases, because we already
   * know them all */
  contacts_context_continue (c);
}


static void
contact_maybe_set_simple_presence (TpContact *contact,
                                   GValueArray *presence)
{
  guint type;
  const gchar *status;
  const gchar *message;

  if (contact == NULL || presence == NULL)
    return;

  contact->priv->has_features |= CONTACT_FEATURE_FLAG_PRESENCE;

  tp_value_array_unpack (presence, 3, &type, &status, &message);

  contact->priv->presence_type = type;

  g_free (contact->priv->presence_status);
  contact->priv->presence_status = g_strdup (status);

  g_free (contact->priv->presence_message);
  contact->priv->presence_message = g_strdup (message);

  g_object_notify ((GObject *) contact, "presence-type");
  g_object_notify ((GObject *) contact, "presence-status");
  g_object_notify ((GObject *) contact, "presence-message");

  g_signal_emit (contact, signals[SIGNAL_PRESENCE_CHANGED], 0,
      contact->priv->presence_type,
      contact->priv->presence_status,
      contact->priv->presence_message);
}

static void
contact_maybe_set_location (TpContact *self,
    GHashTable *location)
{
  if (self == NULL || location == NULL)
    return;

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

  self->priv->has_features |= CONTACT_FEATURE_FLAG_LOCATION;
  self->priv->location = g_hash_table_ref (location);
  g_object_notify ((GObject *) self, "location");
}

static void
contact_set_capabilities (TpContact *self,
    TpCapabilities *capabilities)
{
  tp_clear_object (&self->priv->capabilities);

  self->priv->has_features |= CONTACT_FEATURE_FLAG_CAPABILITIES;
  self->priv->capabilities = g_object_ref (capabilities);
  g_object_notify ((GObject *) self, "capabilities");
}

static void
contact_maybe_set_capabilities (TpContact *self,
    GPtrArray *arr)
{
  TpCapabilities *capabilities;

  if (self == NULL || arr == NULL)
    return;

  capabilities = _tp_capabilities_new (arr, TRUE);
  contact_set_capabilities (self, capabilities);
  g_object_unref (capabilities);
}


static void
contacts_presences_changed (TpConnection *connection,
                            GHashTable *presences,
                            gpointer user_data G_GNUC_UNUSED,
                            GObject *weak_object G_GNUC_UNUSED)
{
  GHashTableIter iter;
  gpointer key, value;

  g_hash_table_iter_init (&iter, presences);

  while (g_hash_table_iter_next (&iter, &key, &value))
    {
      TpContact *contact = _tp_connection_lookup_contact (connection,
          GPOINTER_TO_UINT (key));

      contact_maybe_set_simple_presence (contact, value);
    }
}


static void
contacts_got_simple_presence (TpConnection *connection,
                              GHashTable *presences,
                              const GError *error,
                              gpointer user_data,
                              GObject *weak_object)
{
  ContactsContext *c = user_data;

  if (error == NULL)
    {
      contacts_presences_changed (connection, presences, NULL, NULL);
    }
  else
    {
      /* never mind, we can live without presences */
      DEBUG ("GetPresences failed with %s %u: %s",
          g_quark_to_string (error->domain), error->code, error->message);
    }

  contacts_context_continue (c);
}


static void
contacts_bind_to_presences_changed (TpConnection *connection)
{
  if (!connection->priv->tracking_presences_changed)
    {
      connection->priv->tracking_presences_changed = TRUE;

      tp_cli_connection_interface_simple_presence_connect_to_presences_changed
        (connection, contacts_presences_changed, NULL, NULL, NULL, NULL);
    }
}

static void
contacts_get_simple_presence (ContactsContext *c)
{
  guint i;

  g_assert (c->handles->len == c->contacts->len);

  contacts_bind_to_presences_changed (c->connection);

  for (i = 0; i < c->contacts->len; i++)
    {
      TpContact *contact = g_ptr_array_index (c->contacts, i);

      if ((contact->priv->has_features & CONTACT_FEATURE_FLAG_PRESENCE) == 0)
        {
          c->refcount++;
          tp_cli_connection_interface_simple_presence_call_get_presences (
              c->connection, -1,
              c->handles, contacts_got_simple_presence,
              c, contacts_context_unref, c->weak_object);
          return;
        }
    }

  contacts_context_continue (c);
}

static void
contacts_location_updated (TpConnection *connection,
    guint handle,
    GHashTable *location,
    gpointer user_data G_GNUC_UNUSED,
    GObject *weak_object G_GNUC_UNUSED)
{
  TpContact *contact = _tp_connection_lookup_contact (connection,
          GPOINTER_TO_UINT (handle));

  contact_maybe_set_location (contact, location);
}

static void
contacts_bind_to_location_updated (TpConnection *connection)
{
  if (!connection->priv->tracking_location_changed)
    {
      connection->priv->tracking_location_changed = TRUE;

      tp_cli_connection_interface_location_connect_to_location_updated
        (connection, contacts_location_updated, NULL, NULL, NULL, NULL);

      tp_connection_add_client_interest (connection,
          TP_IFACE_CONNECTION_INTERFACE_LOCATION);
    }
}

static void
contacts_got_locations (TpConnection *connection,
    GHashTable *locations,
    const GError *error,
    gpointer user_data,
    GObject *weak_object)
{
  ContactsContext *c = user_data;

  if (error != NULL)
    {
      DEBUG ("GetLocations failed with %s %u: %s",
          g_quark_to_string (error->domain), error->code, error->message);
    }
  else
    {
      GHashTableIter iter;
      gpointer key, value;

      g_hash_table_iter_init (&iter, locations);
      while (g_hash_table_iter_next (&iter, &key, &value))
        {
          contacts_location_updated (connection, GPOINTER_TO_UINT (key),
              value, NULL, NULL);
        }
    }

  contacts_context_continue (c);
}

static void
contacts_get_locations (ContactsContext *c)
{
  guint i;

  g_assert (c->handles->len == c->contacts->len);

  contacts_bind_to_location_updated (c->connection);

  for (i = 0; i < c->contacts->len; i++)
    {
      TpContact *contact = g_ptr_array_index (c->contacts, i);

      if ((contact->priv->has_features & CONTACT_FEATURE_FLAG_LOCATION) == 0)
        {
          c->refcount++;
          tp_cli_connection_interface_location_call_get_locations (
              c->connection, -1, c->handles, contacts_got_locations,
              c, contacts_context_unref, c->weak_object);
          return;
        }
    }

  contacts_context_continue (c);
}

static void
contact_maybe_set_client_types (TpContact *self,
    const gchar * const *types)
{
  if (self == NULL || types == NULL)
    return;

  if (self->priv->client_types != NULL)
    g_strfreev (self->priv->client_types);

  self->priv->has_features |= CONTACT_FEATURE_FLAG_CLIENT_TYPES;
  self->priv->client_types = g_strdupv ((gchar **) types);
  g_object_notify ((GObject *) self, "client-types");
}

static void
contacts_client_types_updated (TpConnection *connection,
    guint handle,
    const gchar **types,
    gpointer user_data G_GNUC_UNUSED,
    GObject *weak_object G_GNUC_UNUSED)
{
  TpContact *contact = _tp_connection_lookup_contact (connection,
          GPOINTER_TO_UINT (handle));

  contact_maybe_set_client_types (contact, types);
}

static void
contacts_bind_to_client_types_updated (TpConnection *connection)
{
  if (!connection->priv->tracking_client_types_updated)
    {
      connection->priv->tracking_client_types_updated = TRUE;

      tp_cli_connection_interface_client_types_connect_to_client_types_updated
        (connection, contacts_client_types_updated, NULL, NULL, NULL, NULL);
    }
}

static void
set_conn_capabilities_on_contacts (GPtrArray *contacts,
    TpConnection *connection)
{
  guint i;

  for (i = 0; i < contacts->len; i++)
    {
      TpContact *contact = g_ptr_array_index (contacts, i);

      contact_set_capabilities (contact, tp_connection_get_capabilities (
            connection));
    }
}

static void
connection_capabilities_prepare_cb (GObject *object,
    GAsyncResult *res,
    gpointer user_data)
{
  GError *error = NULL;
  ContactsContext *c = user_data;

  if (!tp_proxy_prepare_finish (object, res, &error))
    {
      DEBUG ("Failed to prepare Connection capabilities feature: %s %u: %s",
          g_quark_to_string (error->domain), error->code, error->message);
    }
  else if (!tp_proxy_is_prepared (object, TP_CONNECTION_FEATURE_CAPABILITIES))
    {
      DEBUG ("Connection capabilities feature has not been actually prepared");
    }
  else
    {
      set_conn_capabilities_on_contacts (c->contacts, c->connection);
    }

  contacts_context_continue (c);
  contacts_context_unref (c);
}

static void
contacts_get_conn_capabilities (ContactsContext *c)
{
  GQuark features[] = { TP_CONNECTION_FEATURE_CAPABILITIES, 0 };
  g_assert (c->handles->len == c->contacts->len);

  c->refcount++;
  tp_proxy_prepare_async (c->connection, features,
      connection_capabilities_prepare_cb, c);
}

static void
contacts_capabilities_updated (TpConnection *connection,
    GHashTable *capabilities,
    gpointer user_data G_GNUC_UNUSED,
    GObject *weak_object G_GNUC_UNUSED)
{
  GHashTableIter iter;
  gpointer handle, value;

  g_hash_table_iter_init (&iter, capabilities);
  while (g_hash_table_iter_next (&iter, &handle, &value))
    {
      TpContact *contact = _tp_connection_lookup_contact (connection,
              GPOINTER_TO_UINT (handle));

      contact_maybe_set_capabilities (contact, value);
    }
}

static void
contacts_bind_to_capabilities_updated (TpConnection *connection)
{
  if (!connection->priv->tracking_contact_caps_changed)
    {
      connection->priv->tracking_contact_caps_changed = TRUE;

      tp_cli_connection_interface_contact_capabilities_connect_to_contact_capabilities_changed
        (connection, contacts_capabilities_updated, NULL, NULL, NULL, NULL);
    }
}

static gboolean
build_avatar_filename (TpConnection *connection,
    const gchar *avatar_token,
    gboolean create_dir,
    gchar **ret_filename,
    gchar **ret_mime_filename)
{
  gchar *protocol;
  gchar *cm_name;
  gchar *dir;
  gchar *token_escaped;
  gboolean success = TRUE;

  if (!tp_connection_parse_object_path (connection, &protocol, &cm_name))
    return FALSE;

  token_escaped = tp_escape_as_identifier (avatar_token);
  dir = g_build_filename (g_get_user_cache_dir (),
      "telepathy", "avatars", cm_name, protocol, NULL);

  if (create_dir)
    {
      if (g_mkdir_with_parents (dir, 0700) == -1)
        {
          DEBUG ("Error creating avatar cache dir: %s", g_strerror (errno));
          success = FALSE;
          goto out;
        }
    }

  if (ret_filename != NULL)
    *ret_filename = g_strconcat (dir, G_DIR_SEPARATOR_S, token_escaped, NULL);

  if (ret_mime_filename != NULL)
    *ret_mime_filename = g_strconcat (dir, G_DIR_SEPARATOR_S, token_escaped,
        ".mime", NULL);

out:

  g_free (protocol);
  g_free (cm_name);
  g_free (dir);
  g_free (token_escaped);

  return success;
}

static void contact_set_avatar_token (TpContact *self, const gchar *new_token,
    gboolean request);

static void
contact_avatar_retrieved (TpConnection *connection,
    guint handle,
    const gchar *token,
    const GArray *avatar,
    const gchar *mime_type,
    gpointer user_data G_GNUC_UNUSED,
    GObject *weak_object G_GNUC_UNUSED)
{
  TpContact *self = _tp_connection_lookup_contact (connection, handle);
  gchar *filename;
  gchar *mime_filename;
  GError *error = NULL;

  if (!build_avatar_filename (connection, token, TRUE, &filename,
      &mime_filename))
    return;

  /* Save avatar in cache, even if the contact is unknown, to avoid as much as
   * possible future avatar requests */
  if (!g_file_set_contents (filename, avatar->data, avatar->len, &error))
    {
      DEBUG ("Failed to store avatar in cache (%s): %s", filename,
          error ? error->message : "No error message");
      g_clear_error (&error);
      goto out;
    }
  if (!g_file_set_contents (mime_filename, mime_type, -1, &error))
    {
      DEBUG ("Failed to store MIME type in cache (%s): %s", mime_filename,
          error ? error->message : "No error message");
      g_clear_error (&error);
      goto out;
    }

  DEBUG ("Contact#%u avatar stored in cache: %s, %s", handle, filename,
      mime_type);

  if (self == NULL)
    goto out;

  /* Update the avatar token if a newer one is given */
  contact_set_avatar_token (self, token, FALSE);

  tp_clear_object (&self->priv->avatar_file);
  self->priv->avatar_file = g_file_new_for_path (filename);

  g_free (self->priv->avatar_mime_type);
  self->priv->avatar_mime_type = g_strdup (mime_type);

  g_object_notify ((GObject *) self, "avatar-file");
  g_object_notify ((GObject *) self, "avatar-mime-type");

out:
  g_free (filename);
  g_free (mime_filename);
}

static gboolean
connection_avatar_request_idle_cb (gpointer user_data)
{
  TpConnection *connection = user_data;

  DEBUG ("Request %d avatars", connection->priv->avatar_request_queue->len);

  tp_cli_connection_interface_avatars_call_request_avatars (connection, -1,
      connection->priv->avatar_request_queue, NULL, NULL, NULL, NULL);

  g_array_free (connection->priv->avatar_request_queue, TRUE);
  connection->priv->avatar_request_queue = NULL;
  connection->priv->avatar_request_idle_id = 0;

  return FALSE;
}

static void
contact_update_avatar_data (TpContact *self)
{
  TpConnection *connection;
  gchar *filename = NULL;
  gchar *mime_filename = NULL;

  /* If token is NULL, it means that CM doesn't know the token. In that case we
   * have to request the avatar data to get the token. This happens with XMPP
   * for offline contacts. We don't want to bypass the avatar cache, so we won't
   * update avatar. */
  if (self->priv->avatar_token == NULL)
    return;

   /* If token is empty (""), it means the contact has no avatar. */
  if (tp_str_empty (self->priv->avatar_token))
    {
      tp_clear_object (&self->priv->avatar_file);

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

      DEBUG ("contact#%u has no avatar", self->priv->handle);

      g_object_notify ((GObject *) self, "avatar-file");
      g_object_notify ((GObject *) self, "avatar-mime-type");

      return;
    }

  /* We have a token, search in cache... */
  if (build_avatar_filename (self->priv->connection, self->priv->avatar_token,
          FALSE, &filename, &mime_filename))
    {
      if (g_file_test (filename, G_FILE_TEST_EXISTS))
        {
          GError *error = NULL;

          tp_clear_object (&self->priv->avatar_file);
          self->priv->avatar_file = g_file_new_for_path (filename);

          g_free (self->priv->avatar_mime_type);
          if (!g_file_get_contents (mime_filename, &self->priv->avatar_mime_type,
              NULL, &error))
            {
              DEBUG ("Error reading avatar MIME type (%s): %s", mime_filename,
                  error ? error->message : "No error message");
              self->priv->avatar_mime_type = NULL;
              g_clear_error (&error);
            }

          DEBUG ("contact#%u avatar found in cache: %s, %s",
              self->priv->handle, filename, self->priv->avatar_mime_type);

          g_object_notify ((GObject *) self, "avatar-file");
          g_object_notify ((GObject *) self, "avatar-mime_type");

          goto out;
        }
    }

  /* Not found in cache, queue this contact. We do this to group contacts
   * for the AvatarRequest call */
  connection = self->priv->connection;
  if (connection->priv->avatar_request_queue == NULL)
    connection->priv->avatar_request_queue = g_array_new (FALSE, FALSE,
        sizeof (TpHandle));

  g_array_append_val (connection->priv->avatar_request_queue,
      self->priv->handle);

  if (connection->priv->avatar_request_idle_id == 0)
    connection->priv->avatar_request_idle_id = g_idle_add (
        connection_avatar_request_idle_cb, connection);

out:

  g_free (filename);
  g_free (mime_filename);
}

static void
contacts_bind_to_avatar_retrieved (TpConnection *connection)
{
  if (!connection->priv->tracking_avatar_retrieved)
    {
      connection->priv->tracking_avatar_retrieved = TRUE;

      tp_cli_connection_interface_avatars_connect_to_avatar_retrieved
        (connection, contact_avatar_retrieved, NULL, NULL, NULL, NULL);
    }
}

static void
contacts_get_avatar_data (ContactsContext *c)
{
  guint i;

  g_assert (c->handles->len == c->contacts->len);

  contacts_bind_to_avatar_retrieved (c->connection);

  for (i = 0; i < c->contacts->len; i++)
    {
      TpContact *contact = g_ptr_array_index (c->contacts, i);

      if ((contact->priv->has_features & CONTACT_FEATURE_FLAG_AVATAR_DATA) == 0)
        {
          contact->priv->has_features |= CONTACT_FEATURE_FLAG_AVATAR_DATA;
          contact_update_avatar_data (contact);
        }
    }

  contacts_context_continue (c);
}

static void
contact_set_avatar_token (TpContact *self, const gchar *new_token,
    gboolean request)
{
  if (!tp_strdiff (self->priv->avatar_token, new_token))
    return;

  DEBUG ("contact#%u token is %s", self->priv->handle, new_token);

  self->priv->has_features |= CONTACT_FEATURE_FLAG_AVATAR_TOKEN;
  g_free (self->priv->avatar_token);
  self->priv->avatar_token = g_strdup (new_token);
  g_object_notify ((GObject *) self, "avatar-token");

  if (request && tp_contact_has_feature (self, TP_CONTACT_FEATURE_AVATAR_DATA))
    contact_update_avatar_data (self);
}

static void
contacts_avatar_updated (TpConnection *connection,
                         TpHandle handle,
                         const gchar *new_token,
                         gpointer user_data G_GNUC_UNUSED,
                         GObject *weak_object G_GNUC_UNUSED)
{
  TpContact *contact = _tp_connection_lookup_contact (connection, handle);

  if (contact != NULL)
    contact_set_avatar_token (contact, new_token, TRUE);
}


static void
contacts_got_known_avatar_tokens (TpConnection *connection,
                                  GHashTable *handle_to_token,
                                  const GError *error,
                                  gpointer user_data,
                                  GObject *weak_object)
{
  ContactsContext *c = user_data;
  GHashTableIter iter;
  gpointer key, value;

  if (error == NULL)
    {
      g_hash_table_iter_init (&iter, handle_to_token);

      while (g_hash_table_iter_next (&iter, &key, &value))
        {
          contacts_avatar_updated (connection, GPOINTER_TO_UINT (key), value,
              NULL, NULL);
        }

    }
  /* FIXME: perhaps we could fall back to GetAvatarTokens (which should have
   * been called RequestAvatarTokens, because it blocks on network traffic)
   * if GetKnownAvatarTokens doesn't work? */
  else
    {
      /* never mind, we can live without avatar tokens */
      DEBUG ("GetKnownAvatarTokens failed with %s %u: %s",
          g_quark_to_string (error->domain), error->code, error->message);
    }

  contacts_context_continue (c);
}


static void
contacts_bind_to_avatar_updated (TpConnection *connection)
{
  if (!connection->priv->tracking_avatar_updated)
    {
      connection->priv->tracking_avatar_updated = TRUE;

      tp_cli_connection_interface_avatars_connect_to_avatar_updated
        (connection, contacts_avatar_updated, NULL, NULL, NULL, NULL);
    }
}


static void
contacts_get_avatar_tokens (ContactsContext *c)
{
  guint i;

  g_assert (c->handles->len == c->contacts->len);

  contacts_bind_to_avatar_updated (c->connection);

  for (i = 0; i < c->contacts->len; i++)
    {
      TpContact *contact = g_ptr_array_index (c->contacts, i);

      if ((contact->priv->has_features & CONTACT_FEATURE_FLAG_AVATAR_TOKEN)
          == 0)
        {
          c->refcount++;
          tp_cli_connection_interface_avatars_call_get_known_avatar_tokens (
              c->connection, -1,
              c->handles, contacts_got_known_avatar_tokens,
              c, contacts_context_unref, c->weak_object);
          return;
        }
    }

  contacts_context_continue (c);
}

static void
contact_maybe_set_info (TpContact *self,
    const GPtrArray *contact_info)
{
  guint i;

  if (self == NULL || contact_info == NULL)
    return;

  tp_contact_info_list_free (self->priv->contact_info);
  self->priv->contact_info = NULL;

  self->priv->has_features |= CONTACT_FEATURE_FLAG_CONTACT_INFO;
  for (i = 0; i < contact_info->len; i++)
    {
      GValueArray *va = g_ptr_array_index (contact_info, i);
      const gchar *field_name;
      GStrv parameters;
      GStrv field_value;

      tp_value_array_unpack (va, 3, &field_name, &parameters, &field_value);
      self->priv->contact_info = g_list_prepend (self->priv->contact_info,
          tp_contact_info_field_new (field_name, parameters, field_value));
    }
  self->priv->contact_info = g_list_reverse (self->priv->contact_info);

  g_object_notify ((GObject *) self, "contact-info");
}

static void
contact_info_changed (TpConnection *connection,
    guint handle,
    const GPtrArray *contact_info,
    gpointer user_data G_GNUC_UNUSED,
    GObject *weak_object G_GNUC_UNUSED)
{
  TpContact *self = _tp_connection_lookup_contact (connection, handle);

  contact_maybe_set_info (self, contact_info);
}

static void
contacts_got_contact_info (TpConnection *connection,
    GHashTable *info,
    const GError *error,
    gpointer user_data,
    GObject *weak_object)
{
  ContactsContext *c = user_data;

  if (error != NULL)
    {
      DEBUG ("GetContactInfo failed with %s %u: %s",
          g_quark_to_string (error->domain), error->code, error->message);
    }
  else
    {
      GHashTableIter iter;
      gpointer key, value;

      g_hash_table_iter_init (&iter, info);
      while (g_hash_table_iter_next (&iter, &key, &value))
        {
          contact_info_changed (connection, GPOINTER_TO_UINT (key),
              value, NULL, NULL);
        }
    }

  contacts_context_continue (c);
}

static void
contacts_bind_to_contact_info_changed (TpConnection *connection)
{
  if (!connection->priv->tracking_contact_info_changed)
    {
      connection->priv->tracking_contact_info_changed = TRUE;

      tp_cli_connection_interface_contact_info_connect_to_contact_info_changed (
          connection, contact_info_changed, NULL, NULL, NULL, NULL);
    }
}

static void
contacts_get_contact_info (ContactsContext *c)
{
  guint i;

  g_assert (c->handles->len == c->contacts->len);

  contacts_bind_to_contact_info_changed (c->connection);

  for (i = 0; i < c->contacts->len; i++)
    {
      TpContact *contact = g_ptr_array_index (c->contacts, i);

      if ((contact->priv->has_features & CONTACT_FEATURE_FLAG_CONTACT_INFO) == 0)
        {
          c->refcount++;
          tp_cli_connection_interface_contact_info_call_get_contact_info (
              c->connection, -1, c->handles, contacts_got_contact_info,
              c, contacts_context_unref, c->weak_object);
          return;
        }
    }

  contacts_context_continue (c);
}

typedef struct
{
  TpContact *contact;
  GSimpleAsyncResult *result;
  TpProxyPendingCall *call;
  GCancellable *cancellable;
  gulong cancelled_id;
} ContactInfoRequestData;

static void
contact_info_request_data_free (ContactInfoRequestData *data)
{
  if (data != NULL)
    {
      g_object_unref (data->result);

      if (data->cancellable != NULL)
        g_object_unref (data->cancellable);

      g_slice_free (ContactInfoRequestData, data);
    }
}

static void
contact_info_request_cb (TpConnection *connection,
    const GPtrArray *contact_info,
    const GError *error,
    gpointer user_data,
    GObject *weak_object)
{
  ContactInfoRequestData *data = user_data;
  TpContact *self = data->contact;

  if (data->cancellable != NULL)
    {
      /* At this point it's too late to cancel the operation. This will block
       * until the signal handler has finished if it's already running, so
       * we're guaranteed to never be in a partially-cancelled state after
       * this call. */
      g_cancellable_disconnect (data->cancellable, data->cancelled_id);

      /* If this is true, the cancelled callback has already run and completed the
       * async result, so just bail. */
      if (data->cancelled_id == 0)
        return;

      data->cancelled_id = 0;
    }

  if (error != NULL)
    {
      DEBUG ("Failed to request ContactInfo: %s", error->message);
      g_simple_async_result_set_from_error (data->result, error);
    }
  else
    {
      contact_maybe_set_info (self, contact_info);
    }

  g_simple_async_result_complete_in_idle (data->result);
  data->call = NULL;
}

static void
contact_info_request_cancelled_cb (GCancellable *cancellable,
    ContactInfoRequestData *data)
{
  GError *error = NULL;
  gboolean was_cancelled;

  /* We disconnect from the signal manually; since we're in the cancelled
   * callback, we hold the cancellable's lock so calling this instead of
   * g_cancellable_disconnect() is fine. We do this here so that
   * g_cancellable_disconnect() isn't called by contact_info_request_data_free()
   * which is called by tp_proxy_pending_call_cancel().
   * cancelled_id might already be 0 if the cancellable was cancelled before
   * we connected to it. */
  if (data->cancelled_id != 0)
    g_signal_handler_disconnect (data->cancellable, data->cancelled_id);
  data->cancelled_id = 0;

  was_cancelled = g_cancellable_set_error_if_cancelled (data->cancellable,
      &error);
  g_assert (was_cancelled);

  DEBUG ("Request ContactInfo cancelled");

  g_simple_async_result_set_from_error (data->result, error);
  g_simple_async_result_complete_in_idle (data->result);
  g_clear_error (&error);

  if (data->call != NULL)
    tp_proxy_pending_call_cancel (data->call);
}

/**
 * tp_contact_request_contact_info_async:
 * @self: a #TpContact
 * @cancellable: optional #GCancellable object, %NULL to ignore.
 * @callback: a callback to call when the request is satisfied
 * @user_data: data to pass to @callback
 *
 * Requests an asynchronous request of the contact info of @self. When
 * the operation is finished, @callback will be called. You can then call
 * tp_contact_request_contact_info_finish() to get the result of the operation.
 *
 * If the operation is successful, the #TpContact:contact-info property will be
 * updated (emitting "notify::contact-info" signal) before @callback is called.
 * That means you can call tp_contact_get_contact_info() to get the new vCard
 * inside @callback.
 *
 * Note that requesting the vCard from the network can take significant time, so
 * a bigger timeout is set on the underlying D-Bus call. @cancellable can be
 * cancelled to free resources used in the D-Bus call if the caller is no longer
 * interested in the vCard.
 *
 * If %TP_CONTACT_FEATURE_CONTACT_INFO is not yet set on @self, it will be
 * set before its property gets updated and @callback is called.
 *
 * Since: 0.11.7
 */
void
tp_contact_request_contact_info_async (TpContact *self,
    GCancellable *cancellable,
    GAsyncReadyCallback callback,
    gpointer user_data)
{
  ContactInfoRequestData *data;

  g_return_if_fail (TP_IS_CONTACT (self));

  contacts_bind_to_contact_info_changed (self->priv->connection);

  data = g_slice_new0 (ContactInfoRequestData);

  data->contact = self;
  data->result = g_simple_async_result_new (G_OBJECT (self), callback,
      user_data, tp_contact_request_contact_info_finish);

  if (cancellable != NULL)
    {
      data->cancellable = g_object_ref (cancellable);
      data->cancelled_id = g_cancellable_connect (data->cancellable,
          G_CALLBACK (contact_info_request_cancelled_cb), data, NULL);

      /* Return early if the cancellable has already been cancelled */
      if (data->cancelled_id == 0)
        return;
    }

  data->call = tp_cli_connection_interface_contact_info_call_request_contact_info (
      self->priv->connection, 60*60*1000, self->priv->handle,
      contact_info_request_cb,
      data, (GDestroyNotify) contact_info_request_data_free,
      NULL);
}

/**
 * tp_contact_request_contact_info_finish:
 * @self: a #TpContact
 * @result: a #GAsyncResult
 * @error: a #GError to be filled
 *
 * Finishes an async request of @self info. If the operation was successful,
 * the contact's vCard can be accessed using tp_contact_get_contact_info().
 *
 * Returns: %TRUE if the request call was successful, otherwise %FALSE
 *
 * Since: 0.11.7
 */
gboolean
tp_contact_request_contact_info_finish (TpContact *self,
    GAsyncResult *result,
    GError **error)
{
  GSimpleAsyncResult *simple;

  g_return_val_if_fail (TP_IS_CONTACT (self), FALSE);
  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);

  simple = G_SIMPLE_ASYNC_RESULT (result);

  if (g_simple_async_result_propagate_error (simple, error))
    return FALSE;

  g_return_val_if_fail (g_simple_async_result_is_valid (result,
      G_OBJECT (self), tp_contact_request_contact_info_finish), FALSE);

  return TRUE;
}

/**
 * tp_connection_refresh_contact_info:
 * @self: a #TpConnection
 * @n_contacts: The number of contacts in @contacts (must be at least 1)
 * @contacts: (array length=n_contacts): An array of #TpContact objects
 *  associated with @self
 *
 * Requests to refresh the #TpContact:contact-info property on each contact from
 * @contacts, requesting it from the network if an up-to-date version is not
 * cached locally. "notify::contact-info" will be emitted when the contact's
 * information are updated.
 *
 * If %TP_CONTACT_FEATURE_CONTACT_INFO is not yet set on a contact, it will be
 * set before its property gets updated.
 *
 * Since: 0.11.7
 */
void
tp_connection_refresh_contact_info (TpConnection *self,
    guint n_contacts,
    TpContact * const *contacts)
{
  GArray *handles;
  guint i;

  g_return_if_fail (TP_IS_CONNECTION (self));
  g_return_if_fail (n_contacts >= 1);
  g_return_if_fail (contacts != NULL);

  for (i = 0; i < n_contacts; i++)
    {
      g_return_if_fail (TP_IS_CONTACT (contacts[i]));
      g_return_if_fail (contacts[i]->priv->connection == self);
    }

  contacts_bind_to_contact_info_changed (self);

  handles = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle), n_contacts);
  for (i = 0; i < n_contacts; i++)
    g_array_append_val (handles, contacts[i]->priv->handle);

  tp_cli_connection_interface_contact_info_call_refresh_contact_info (self, -1,
      handles, NULL, NULL, NULL, NULL);

  g_array_free (handles, TRUE);
}

static gboolean
contacts_context_supports_iface (ContactsContext *context,
    GQuark iface)
{
  GArray *contact_attribute_interfaces =
      context->connection->priv->contact_attribute_interfaces;
  guint i;

  if (!tp_proxy_has_interface_by_id (context->connection,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACTS))
    return FALSE;

  if (contact_attribute_interfaces == NULL)
    return FALSE;

  for (i = 0; i < contact_attribute_interfaces->len; i++)
    {
      GQuark q = g_array_index (contact_attribute_interfaces, GQuark, i);

      if (q == iface)
        return TRUE;
    }

  return FALSE;
}

static void
contacts_context_queue_features (ContactsContext *context)
{
  ContactFeatureFlags feature_flags = context->wanted;

  /* Start slow path for requested features that are not in
   * ContactAttributeInterfaces */

  if ((feature_flags & CONTACT_FEATURE_FLAG_ALIAS) != 0 &&
      !contacts_context_supports_iface (context,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_ALIASING) &&
      tp_proxy_has_interface_by_id (context->connection,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_ALIASING))
    {
      g_queue_push_tail (&context->todo, contacts_get_aliases);
    }

  if ((feature_flags & CONTACT_FEATURE_FLAG_PRESENCE) != 0 &&
      !contacts_context_supports_iface (context,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_SIMPLE_PRESENCE))
    {
      if (tp_proxy_has_interface_by_id (context->connection,
            TP_IFACE_QUARK_CONNECTION_INTERFACE_SIMPLE_PRESENCE))
        {
          g_queue_push_tail (&context->todo, contacts_get_simple_presence);
        }
#if 0
      /* FIXME: Before doing this for the first time, we'd need to download
       * from the CM the definition of what each status actually *means* */
      else if (tp_proxy_has_interface_by_id (context->connection,
            TP_IFACE_QUARK_CONNECTION_INTERFACE_PRESENCE))
        {
          g_queue_push_tail (&context->todo, contacts_get_complex_presence);
        }
#endif
    }

  if (tp_proxy_has_interface_by_id (context->connection,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_AVATARS))
    {
      if ((feature_flags & CONTACT_FEATURE_FLAG_AVATAR_TOKEN) != 0 &&
          !contacts_context_supports_iface (context,
            TP_IFACE_QUARK_CONNECTION_INTERFACE_AVATARS))
        g_queue_push_tail (&context->todo, contacts_get_avatar_tokens);

      /* There is no contact attribute for avatar data, always use the
       * slow path for it. */
      if ((feature_flags & CONTACT_FEATURE_FLAG_AVATAR_DATA) != 0)
        g_queue_push_tail (&context->todo, contacts_get_avatar_data);
    }

  if ((feature_flags & CONTACT_FEATURE_FLAG_LOCATION) != 0 &&
      !contacts_context_supports_iface (context,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_LOCATION) &&
      tp_proxy_has_interface_by_id (context->connection,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_LOCATION))
    {
      g_queue_push_tail (&context->todo, contacts_get_locations);
    }

  /* Don't implement slow path for ContactCapabilities as Contacts is now
   * mandatory so any CM supporting ContactCapabilities will implement
   * Contacts as well.
   *
   * But if ContactCapabilities is NOT supported, we fallback to connection
   * capabilities.
   * */

  if ((feature_flags & CONTACT_FEATURE_FLAG_CAPABILITIES) != 0 &&
      !tp_proxy_has_interface_by_id (context->connection,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACT_CAPABILITIES))
    {
      DEBUG ("Connection doesn't support ContactCapabilities; fallback to "
          "connection capabilities");

      g_queue_push_tail (&context->todo, contacts_get_conn_capabilities);
    }

  if ((feature_flags & CONTACT_FEATURE_FLAG_CONTACT_INFO) != 0 &&
      !contacts_context_supports_iface (context,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACT_INFO) &&
      tp_proxy_has_interface_by_id (context->connection,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACT_INFO))
    {
      g_queue_push_tail (&context->todo, contacts_get_contact_info);
    }
}

static void
contacts_got_attributes (TpConnection *connection,
                         GHashTable *attributes,
                         const GError *error,
                         gpointer user_data,
                         GObject *weak_object)
{
  ContactsContext *c = user_data;
  guint i;

  if (error != NULL)
    {
      contacts_context_fail (c, error);
      return;
    }

  i = 0;

  if (c->signature == CB_BY_HANDLE && c->contacts->len == 0)
    {
      while (i < c->handles->len)
        {
          TpHandle handle = g_array_index (c->handles, guint, i);
          GHashTable *asv = g_hash_table_lookup (attributes,
              GUINT_TO_POINTER (handle));

          if (asv == NULL)
            {
              /* not in the hash table => not valid */
              g_array_append_val (c->invalid, handle);
              g_array_remove_index_fast (c->handles, i);
            }
          else
            {
              TpContact *contact = tp_contact_ensure (connection, handle);

              g_ptr_array_add (c->contacts, contact);
              i++;
            }
        }
    }

  g_assert (c->contacts->len == c->handles->len);

  for (i = 0; i < c->handles->len; i++)
    {
      TpContact *contact = g_ptr_array_index (c->contacts, i);
      const gchar *s;
      gpointer boxed;
      GHashTable *asv = g_hash_table_lookup (attributes,
          GUINT_TO_POINTER (contact->priv->handle));

      if (asv == NULL)
        {
          GError *e = g_error_new (TP_DBUS_ERRORS, TP_DBUS_ERROR_INCONSISTENT,
              "We hold a ref to handle #%u but it appears to be invalid",
              contact->priv->handle);

          contacts_context_fail (c, e);
          g_error_free (e);
          return;
        }

      /* set up the contact with its attributes */

      s = tp_asv_get_string (asv, TP_TOKEN_CONNECTION_CONTACT_ID);

      if (s == NULL)
        {
          GError *e = g_error_new (TP_DBUS_ERRORS, TP_DBUS_ERROR_INCONSISTENT,
              "Connection manager %s is broken: contact #%u in the "
              "GetContactAttributes result has no contact-id",
              tp_proxy_get_bus_name (connection), contact->priv->handle);

          contacts_context_fail (c, e);
          g_error_free (e);
          return;
        }

      if (contact->priv->identifier == NULL)
        {
          contact->priv->identifier = g_strdup (s);
        }
      else if (tp_strdiff (contact->priv->identifier, s))
        {
          GError *e = g_error_new (TP_DBUS_ERRORS, TP_DBUS_ERROR_INCONSISTENT,
              "Connection manager %s is broken: contact #%u identifier "
              "changed from %s to %s",
              tp_proxy_get_bus_name (connection), contact->priv->handle,
              contact->priv->identifier, s);

          contacts_context_fail (c, e);
          g_error_free (e);
          return;
        }

      s = tp_asv_get_string (asv,
          TP_TOKEN_CONNECTION_INTERFACE_ALIASING_ALIAS);

      if (s != NULL)
        {
          contact->priv->has_features |= CONTACT_FEATURE_FLAG_ALIAS;
          g_free (contact->priv->alias);
          contact->priv->alias = g_strdup (s);
          g_object_notify ((GObject *) contact, "alias");
        }

      s = tp_asv_get_string (asv, TP_TOKEN_CONNECTION_INTERFACE_AVATARS_TOKEN);

      if (s != NULL)
        contact_set_avatar_token (contact, s, TRUE);

      boxed = tp_asv_get_boxed (asv,
          TP_TOKEN_CONNECTION_INTERFACE_SIMPLE_PRESENCE_PRESENCE,
          TP_STRUCT_TYPE_SIMPLE_PRESENCE);
      contact_maybe_set_simple_presence (contact, boxed);

      /* Location */
      boxed = tp_asv_get_boxed (asv,
          TP_TOKEN_CONNECTION_INTERFACE_LOCATION_LOCATION,
          TP_HASH_TYPE_LOCATION);
      contact_maybe_set_location (contact, boxed);

      /* Capabilities */
      boxed = tp_asv_get_boxed (asv,
          TP_TOKEN_CONNECTION_INTERFACE_CONTACT_CAPABILITIES_CAPABILITIES,
          TP_ARRAY_TYPE_REQUESTABLE_CHANNEL_CLASS_LIST);
      contact_maybe_set_capabilities (contact, boxed);

      /* ContactInfo */
      boxed = tp_asv_get_boxed (asv,
          TP_TOKEN_CONNECTION_INTERFACE_CONTACT_INFO_INFO,
          TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);
      contact_maybe_set_info (contact, boxed);

      /* ClientTypes */
      boxed = tp_asv_get_boxed (asv,
          TP_TOKEN_CONNECTION_INTERFACE_CLIENT_TYPES_CLIENT_TYPES,
          G_TYPE_STRV);
      contact_maybe_set_client_types (contact, boxed);
    }

  contacts_context_continue (c);
}


static void
contacts_get_attributes (ContactsContext *context)
{
  GArray *contact_attribute_interfaces =
      context->connection->priv->contact_attribute_interfaces;
  GPtrArray *array;
  const gchar **supported_interfaces;
  guint i;
  guint len = 0;

  if (contact_attribute_interfaces != NULL)
      len = contact_attribute_interfaces->len;

  /* tp_connection_get_contact_attributes insists that you have at least one
   * handle; skip it if we don't (can only happen if we started from IDs) */
  if (context->handles->len == 0)
    {
      contacts_context_continue (context);
      return;
    }

  g_assert (tp_proxy_has_interface_by_id (context->connection,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACTS));

  array = g_ptr_array_sized_new (len);

  for (i = 0; i < len; i++)
    {
      GQuark q = g_array_index (contact_attribute_interfaces, GQuark, i);

      if (q == TP_IFACE_QUARK_CONNECTION_INTERFACE_ALIASING)
        {
          if ((context->wanted & CONTACT_FEATURE_FLAG_ALIAS) != 0)
            {
              g_ptr_array_add (array,
                  TP_IFACE_CONNECTION_INTERFACE_ALIASING);
              contacts_bind_to_aliases_changed (context->connection);
            }
        }
      else if (q == TP_IFACE_QUARK_CONNECTION_INTERFACE_AVATARS)
        {
          if ((context->wanted & CONTACT_FEATURE_FLAG_AVATAR_TOKEN) != 0)
            {
              g_ptr_array_add (array,
                  TP_IFACE_CONNECTION_INTERFACE_AVATARS);
              contacts_bind_to_avatar_updated (context->connection);
            }
        }
      else if (q == TP_IFACE_QUARK_CONNECTION_INTERFACE_SIMPLE_PRESENCE)
        {
          if ((context->wanted & CONTACT_FEATURE_FLAG_PRESENCE) != 0)
            {
              g_ptr_array_add (array,
                  TP_IFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE);
              contacts_bind_to_presences_changed (context->connection);
            }
        }
      else if (q == TP_IFACE_QUARK_CONNECTION_INTERFACE_LOCATION)
        {
          if ((context->wanted & CONTACT_FEATURE_FLAG_LOCATION) != 0)
            {
              g_ptr_array_add (array,
                  TP_IFACE_CONNECTION_INTERFACE_LOCATION);
              contacts_bind_to_location_updated (context->connection);
            }
        }
      else if (q == TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACT_CAPABILITIES)
        {
          if ((context->wanted & CONTACT_FEATURE_FLAG_CAPABILITIES) != 0)
            {
              g_ptr_array_add (array,
                  TP_IFACE_CONNECTION_INTERFACE_CONTACT_CAPABILITIES);
              contacts_bind_to_capabilities_updated (context->connection);
            }
        }
      else if (q == TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACT_INFO)
        {
          if ((context->wanted & CONTACT_FEATURE_FLAG_CONTACT_INFO) != 0)
            {
              g_ptr_array_add (array,
                  TP_IFACE_CONNECTION_INTERFACE_CONTACT_INFO);
              contacts_bind_to_contact_info_changed (context->connection);
            }
        }
      else if (q == TP_IFACE_QUARK_CONNECTION_INTERFACE_CLIENT_TYPES)
        {
          if ((context->wanted & CONTACT_FEATURE_FLAG_CLIENT_TYPES) != 0)
            {
              g_ptr_array_add (array,
                  TP_IFACE_CONNECTION_INTERFACE_CLIENT_TYPES);
              contacts_bind_to_client_types_updated (context->connection);
            }
        }
    }

  if (array->len == 0 &&
      !(context->signature == CB_BY_HANDLE && context->contacts->len == 0) &&
      context->contacts_have_ids)
    {
      /* We're not going to do anything useful: we're not holding/inspecting
       * the handles, and we're not inspecting any extended interfaces
       * either. Skip it. */
      g_ptr_array_free (array, TRUE);
      contacts_context_continue (context);
      return;
    }

  g_ptr_array_add (array, NULL);
  supported_interfaces = (const gchar **) g_ptr_array_free (array, FALSE);

  /* The Hold parameter is only true if we started from handles, and we don't
   * already have all the contacts we need. */
  context->refcount++;
  tp_connection_get_contact_attributes (context->connection, -1,
      context->handles->len, (const TpHandle *) context->handles->data,
      supported_interfaces,
      (context->signature == CB_BY_HANDLE && context->contacts->len == 0),
      contacts_got_attributes,
      context, contacts_context_unref, context->weak_object);
  g_free (supported_interfaces);
}

/*
 * Returns a new GPtrArray of borrowed references to TpContacts,
 * or NULL if any contacts could not be found.
 */
static GPtrArray *
lookup_all_contacts (ContactsContext *context)
{
  GPtrArray *contacts = g_ptr_array_new ();
  guint i;

  for (i = 0; i < context->handles->len; i++)
    {
      TpContact *contact = _tp_connection_lookup_contact (context->connection,
          g_array_index (context->handles, TpHandle, i));
      if (contact != NULL)
        {
          g_ptr_array_add (contacts, contact);
        }
      else
        {
          g_ptr_array_free (contacts, TRUE);
          contacts = NULL;
          break;
        }
    }

  return contacts;
}

static gboolean
get_feature_flags (guint n_features,
    const TpContactFeature *features,
    ContactFeatureFlags *flags)
{
  ContactFeatureFlags feature_flags = 0;
  guint i;

  for (i = 0; i < n_features; i++)
    {
      g_return_val_if_fail (features[i] < NUM_TP_CONTACT_FEATURES, FALSE);
      feature_flags |= (1 << features[i]);
    }

  /* Force AVATAR_TOKEN if we have AVATAR_DATA */
  if ((feature_flags & CONTACT_FEATURE_FLAG_AVATAR_DATA) != 0)
    feature_flags |= CONTACT_FEATURE_FLAG_AVATAR_TOKEN;

  *flags = feature_flags;

  return TRUE;
}

/**
 * tp_connection_get_contacts_by_handle:
 * @self: A connection, which must be ready (#TpConnection:connection-ready
 *  must be %TRUE)
 * @n_handles: The number of handles in @handles (must be at least 1)
 * @handles: (array length=n_handles) (element-type uint): An array of handles
 *  of type %TP_HANDLE_TYPE_CONTACT representing the desired contacts
 * @n_features: The number of features in @features (may be 0)
 * @features: (array length=n_features) (allow-none) (element-type uint): An array of features that
 *  must be ready for use (if supported) before the callback is called (may
 *  be %NULL if @n_features is 0)
 * @callback: A user callback to call when the contacts are ready
 * @user_data: Data to pass to the callback
 * @destroy: Called to destroy @user_data either after @callback has been
 *  called, or if the operation is cancelled
 * @weak_object: (allow-none): An object to pass to the callback, which will be
 *  weakly referenced; if this object is destroyed, the operation will be
 *  cancelled
 *
 * Create a number of #TpContact objects and make asynchronous method calls
 * to hold their handles and ensure that all the features specified in
 * @features are ready for use (if they are supported at all).
 *
 * It is not an error to put features in @features even if the connection
 * manager doesn't support them - users of this method should have a static
 * list of features they would like to use if possible, and use it for all
 * connection managers.
 *
 * Since: 0.7.18
 */
void
tp_connection_get_contacts_by_handle (TpConnection *self,
                                      guint n_handles,
                                      const TpHandle *handles,
                                      guint n_features,
                                      const TpContactFeature *features,
                                      TpConnectionContactsByHandleCb callback,
                                      gpointer user_data,
                                      GDestroyNotify destroy,
                                      GObject *weak_object)
{
  ContactFeatureFlags feature_flags = 0;
  ContactsContext *context;
  GPtrArray *contacts;
  guint i;

  /* As an implementation detail, this method actually starts working slightly
   * before we're officially ready, but only if you don't want any features.
   * We use this to get the TpContact for the SelfHandle. */
  if (n_features != 0 || !self->priv->introspecting_after_connected)
    {
      g_return_if_fail (tp_connection_is_ready (self));
    }

  g_return_if_fail (tp_proxy_get_invalidated (self) == NULL);
  g_return_if_fail (n_handles >= 1);
  g_return_if_fail (handles != NULL);
  g_return_if_fail (n_features == 0 || features != NULL);
  g_return_if_fail (callback != NULL);

  if (!get_feature_flags (n_features, features, &feature_flags))
    return;

  context = contacts_context_new (self, n_handles, feature_flags,
      CB_BY_HANDLE, user_data, destroy, weak_object);
  context->callback.by_handle = callback;

  g_array_append_vals (context->handles, handles, n_handles);

  contacts = lookup_all_contacts (context);

  if (contacts != NULL)
    {
      ContactFeatureFlags minimal_feature_flags = 0xFFFFFFFF;

      /* We have already held (and possibly inspected) handles, so we can
       * skip that. */

      context->contacts_have_ids = TRUE;

      for (i = 0; i < n_handles; i++)
        {
          TpContact *contact = g_object_ref (g_ptr_array_index (contacts, i));

          minimal_feature_flags &= contact->priv->has_features;
          g_ptr_array_add (context->contacts, contact);

          if (contact->priv->identifier == NULL)
            context->contacts_have_ids = FALSE;
        }

      /* This context won't need to retrieve any features that every
       * contact in the list already has. */
      context->wanted &= (~minimal_feature_flags);

      /* We do need to retrieve any features that aren't there yet, though. */
      if (tp_proxy_has_interface_by_id (self,
            TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACTS))
        {
          g_queue_push_head (&context->todo, contacts_get_attributes);
        }

      contacts_context_queue_features (context);

      g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
          contacts_context_idle_continue, context, contacts_context_unref);

      g_ptr_array_free (contacts, TRUE);
      return;
    }

  if (tp_proxy_has_interface_by_id (self,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACTS))
    {
      /* we support the Contacts interface, so we can hold the handles and
       * simultaneously inspect them. After that, we'll fill in any
       * features that are necessary (this becomes a no-op if Contacts
       * will give us everything). */
      g_queue_push_head (&context->todo, contacts_get_attributes);
      contacts_context_queue_features (context);
      g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
          contacts_context_idle_continue, context, contacts_context_unref);
      return;
    }

  /* if we haven't already returned, we're on the slow path */

  /* Before we return anything we'll want to inspect the handles */
  g_queue_push_head (&context->todo, contacts_inspect);

  /* After that we'll get the features */
  contacts_context_queue_features (context);

  /* but first, we need to hold onto them */
  tp_connection_hold_handles (self, -1,
      TP_HANDLE_TYPE_CONTACT, n_handles, handles,
      contacts_held_handles, context, contacts_context_unref, weak_object);
}


/**
 * tp_connection_upgrade_contacts:
 * @self: A connection, which must be ready (#TpConnection:connection-ready
 *  must be %TRUE)
 * @n_contacts: The number of contacts in @contacts (must be at least 1)
 * @contacts: (array length=n_contacts): An array of #TpContact objects
 *  associated with @self
 * @n_features: The number of features in @features (must be at least 1)
 * @features: (array length=n_features): An array of features that must be
 *  ready for use (if supported) before the callback is called
 * @callback: A user callback to call when the contacts are ready
 * @user_data: Data to pass to the callback
 * @destroy: Called to destroy @user_data either after @callback has been
 *  called, or if the operation is cancelled
 * @weak_object: (allow-none): An object to pass to the callback, which will be
 *  weakly referenced; if this object is destroyed, the operation will be
 *  cancelled
 *
 * Given several #TpContact objects, make asynchronous method calls
 * ensure that all the features specified in @features are ready for use
 * (if they are supported at all).
 *
 * It is not an error to put features in @features even if the connection
 * manager doesn't support them - users of this method should have a static
 * list of features they would like to use if possible, and use it for all
 * connection managers.
 *
 * Since: 0.7.18
 */
void
tp_connection_upgrade_contacts (TpConnection *self,
                                guint n_contacts,
                                TpContact * const *contacts,
                                guint n_features,
                                const TpContactFeature *features,
                                TpConnectionUpgradeContactsCb callback,
                                gpointer user_data,
                                GDestroyNotify destroy,
                                GObject *weak_object)
{
  ContactFeatureFlags feature_flags = 0;
  ContactsContext *context;
  guint i;

  g_return_if_fail (tp_connection_is_ready (self));
  g_return_if_fail (tp_proxy_get_invalidated (self) == NULL);
  g_return_if_fail (n_contacts >= 1);
  g_return_if_fail (contacts != NULL);
  g_return_if_fail (n_features == 0 || features != NULL);
  g_return_if_fail (callback != NULL);

  for (i = 0; i < n_contacts; i++)
    {
      g_return_if_fail (contacts[i]->priv->connection == self);
      g_return_if_fail (contacts[i]->priv->identifier != NULL);
    }

  if (!get_feature_flags (n_features, features, &feature_flags))
    return;

  context = contacts_context_new (self, n_contacts, feature_flags,
      CB_UPGRADE, user_data, destroy, weak_object);
  context->callback.upgrade = callback;

  for (i = 0; i < n_contacts; i++)
    {
      g_ptr_array_add (context->contacts, g_object_ref (contacts[i]));
      g_array_append_val (context->handles, contacts[i]->priv->handle);
    }

  context->contacts_have_ids = TRUE;

  g_assert (context->handles->len == n_contacts);

  if (tp_proxy_has_interface_by_id (self,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACTS))
    {
      g_queue_push_head (&context->todo, contacts_get_attributes);
    }

  contacts_context_queue_features (context);

  /* use an idle to make sure the callback is called after we return,
   * even if all the contacts actually have all the features, just to be
   * consistent */
  g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
      contacts_context_idle_continue, context, contacts_context_unref);
}


static void
contacts_requested_one_handle (TpConnection *connection,
                               TpHandleType handle_type,
                               guint n_handles,
                               const TpHandle *handles,
                               const gchar * const *ids,
                               const GError *error,
                               gpointer user_data,
                               GObject *weak_object)
{
  ContactsContext *c = user_data;

  if (error == NULL)
    {
      TpContact *contact;

      g_assert (handle_type == TP_HANDLE_TYPE_CONTACT);
      /* -1 because NULL terminator is explicit */
      g_assert (c->next_index < c->request_ids->len - 1);

      g_assert (n_handles == 1);
      g_assert (handles[0] != 0);

      contact = tp_contact_ensure (connection, handles[0]);
      g_array_append_val (c->handles, handles[0]);
      g_ptr_array_add (c->contacts, contact);
      c->next_index++;
    }
  else if (error->domain == TP_ERRORS &&
      (error->code == TP_ERROR_INVALID_HANDLE ||
       error->code == TP_ERROR_NOT_AVAILABLE ||
       error->code == TP_ERROR_INVALID_ARGUMENT))
    {
      g_hash_table_insert (c->request_errors,
          g_ptr_array_index (c->request_ids, c->next_index),
          g_error_copy (error));
      /* shift the rest of the IDs down one and do not increment next_index */
      g_ptr_array_remove_index (c->request_ids, c->next_index);
    }
  else
    {
      contacts_context_fail (c, error);
      return;
    }

  contacts_context_continue (c);
}


static void
contacts_request_one_handle (ContactsContext *c)
{
  const gchar *ids[] = { NULL, NULL };

  ids[0] = g_ptr_array_index (c->request_ids, c->next_index);
  g_assert (ids[0] != NULL);

  c->refcount++;
  tp_connection_request_handles (c->connection, -1,
      TP_HANDLE_TYPE_CONTACT, ids,
      contacts_requested_one_handle, c, contacts_context_unref,
      c->weak_object);
}


static void
contacts_requested_handles (TpConnection *connection,
                            TpHandleType handle_type,
                            guint n_handles,
                            const TpHandle *handles,
                            const gchar * const *ids,
                            const GError *error,
                            gpointer user_data,
                            GObject *weak_object)
{
  ContactsContext *c = user_data;

  g_assert (handle_type == TP_HANDLE_TYPE_CONTACT);
  g_assert (weak_object == c->weak_object);

  if (error == NULL)
    {
      guint i;

      for (i = 0; i < n_handles; i++)
        {
          TpContact *contact = tp_contact_ensure (connection, handles[i]);

          g_array_append_val (c->handles, handles[i]);
          g_ptr_array_add (c->contacts, contact);
        }
    }
  else if (error->domain == TP_ERRORS &&
      (error->code == TP_ERROR_INVALID_HANDLE ||
       error->code == TP_ERROR_NOT_AVAILABLE ||
       error->code == TP_ERROR_INVALID_ARGUMENT))
    {
      /* One of the strings is bad. We don't know which, so split them. */
      guint i;

      DEBUG ("A handle was bad, trying to recover: %s %u: %s",
          g_quark_to_string (error->domain), error->code, error->message);

      /* -1 because NULL terminator is explicit */
      for (i = 0; i < c->request_ids->len - 1; i++)
        {
          g_queue_push_head (&c->todo, contacts_request_one_handle);
        }

      g_assert (c->next_index == 0);
    }
  else
    {
      DEBUG ("RequestHandles failed: %s %u: %s",
          g_quark_to_string (error->domain), error->code, error->message);
      contacts_context_fail (c, error);
      return;
    }

  contacts_context_continue (c);
}


/**
 * tp_connection_get_contacts_by_id:
 * @self: A connection, which must be ready (#TpConnection:connection-ready
 *  must be %TRUE)
 * @n_ids: The number of IDs in @ids (must be at least 1)
 * @ids: (array length=n_ids) (transfer none): An array of strings representing
 *  the desired contacts by their
 *  identifiers in the IM protocol (XMPP JIDs, SIP URIs, MSN Passports,
 *  AOL screen-names etc.)
 * @n_features: The number of features in @features (may be 0)
 * @features: (array length=n_features) (allow-none): An array of features
 *  that must be ready for use (if supported)
 *  before the callback is called (may be %NULL if @n_features is 0)
 * @callback: A user callback to call when the contacts are ready
 * @user_data: Data to pass to the callback
 * @destroy: Called to destroy @user_data either after @callback has been
 *  called, or if the operation is cancelled
 * @weak_object: (allow-none): An object to pass to the callback, which will
 *  be weakly referenced; if this object is destroyed, the operation will be
 *  cancelled
 *
 * Create a number of #TpContact objects and make asynchronous method calls
 * to obtain their handles and ensure that all the features specified in
 * @features are ready for use (if they are supported at all).
 *
 * It is not an error to put features in @features even if the connection
 * manager doesn't support them - users of this method should have a static
 * list of features they would like to use if possible, and use it for all
 * connection managers.
 *
 * Since: 0.7.18
 */
void
tp_connection_get_contacts_by_id (TpConnection *self,
                                  guint n_ids,
                                  const gchar * const *ids,
                                  guint n_features,
                                  const TpContactFeature *features,
                                  TpConnectionContactsByIdCb callback,
                                  gpointer user_data,
                                  GDestroyNotify destroy,
                                  GObject *weak_object)
{
  ContactFeatureFlags feature_flags = 0;
  ContactsContext *context;
  guint i;

  g_return_if_fail (tp_connection_is_ready (self));
  g_return_if_fail (tp_proxy_get_invalidated (self) == NULL);
  g_return_if_fail (n_ids >= 1);
  g_return_if_fail (ids != NULL);
  g_return_if_fail (ids[0] != NULL);
  g_return_if_fail (n_features == 0 || features != NULL);
  g_return_if_fail (callback != NULL);

  if (!get_feature_flags (n_features, features, &feature_flags))
    return;

  context = contacts_context_new (self, n_ids, feature_flags,
      CB_BY_ID, user_data, destroy, weak_object);
  context->callback.by_id = callback;
  context->request_errors = g_hash_table_new_full (g_str_hash, g_str_equal,
      g_free, (GDestroyNotify) g_error_free);

  context->request_ids = g_ptr_array_sized_new (n_ids);

  for (i = 0; i < n_ids; i++)
    {
      g_return_if_fail (ids[i] != NULL);
      g_ptr_array_add (context->request_ids, g_strdup (ids[i]));
    }

  g_ptr_array_add (context->request_ids, NULL);

  /* set up the queue of feature introspection */

  if (tp_proxy_has_interface_by_id (self,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACTS))
    {
      g_queue_push_head (&context->todo, contacts_get_attributes);
    }
  else
    {
      g_queue_push_head (&context->todo, contacts_inspect);
    }

  contacts_context_queue_features (context);

  /* but first, we need to get the handles in the first place */
  tp_connection_request_handles (self, -1,
      TP_HANDLE_TYPE_CONTACT,
      (const gchar * const *) context->request_ids->pdata,
      contacts_requested_handles, context, contacts_context_unref,
      weak_object);
}