summaryrefslogtreecommitdiff
path: root/TelepathyQt4/contact-manager.cpp
blob: fb5c4b62c813f601c62b84b14ab6ac4de4123ff5 (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
/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2008-2010 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008-2010 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 <TelepathyQt4/ContactManager>
#include "TelepathyQt4/contact-manager-internal.h"

#include "TelepathyQt4/_gen/contact-manager.moc.hpp"
#include "TelepathyQt4/_gen/contact-manager-internal.moc.hpp"

#include "TelepathyQt4/debug-internal.h"

#include <TelepathyQt4/AvatarData>
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/ConnectionLowlevel>
#include <TelepathyQt4/PendingChannel>
#include <TelepathyQt4/PendingContactAttributes>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/PendingFailure>
#include <TelepathyQt4/PendingHandles>
#include <TelepathyQt4/ReferencedHandles>
#include <TelepathyQt4/Utils>

#include <QMap>
#include <QWeakPointer>

namespace Tp
{

/**
 * \class ContactManager
 * \ingroup clientconn
 * \headerfile TelepathyQt4/contact-manager.h <TelepathyQt4/ContactManager>
 *
 * \brief The ContactManager class is responsible for managing contacts.
 */

struct TELEPATHY_QT4_NO_EXPORT ContactManager::Private
{
    Private(ContactManager *parent, Connection *connection);

    void ensureTracking(const Feature &feature);

    // roster specific methods
    void processContactListChanges();
    void processContactListUpdates();
    void processContactListGroupsUpdates();
    void processContactListGroupsCreated();
    void processContactListGroupRenamed();
    void processContactListGroupsRemoved();

    Contacts allKnownContactsFallback() const;
    void computeKnownContactsChangesFallback(const Contacts &added,
            const Contacts &pendingAdded, const Contacts &remotePendingAdded,
            const Contacts &removed, const Channel::GroupMemberChangeDetails &details);
    void updateContactsBlockState();
    void updateContactsPresenceStateFallback();
    PendingOperation *requestPresenceSubscriptionFallback(
            const QList<ContactPtr> &contacts, const QString &message);
    PendingOperation *removePresenceSubscriptionFallback(
            const QList<ContactPtr> &contacts, const QString &message);
    PendingOperation *authorizePresencePublicationFallback(
            const QList<ContactPtr> &contacts, const QString &message);
    PendingOperation *removePresencePublicationFallback(
            const QList<ContactPtr> &contacts, const QString &message);
    PendingOperation *removeContactsFallback(
            const QList<ContactPtr> &contacts, const QString &message);

    // roster group specific methods
    QString addContactListGroupChannelFallback(const ChannelPtr &contactListGroupChannel);
    PendingOperation *addGroupFallback(const QString &group);
    PendingOperation *removeGroupFallback(const QString &group);
    PendingOperation *addContactsToGroupFallback(const QString &group,
            const QList<ContactPtr> &contacts);
    PendingOperation *removeContactsFromGroupFallback(const QString &group,
            const QList<ContactPtr> &contacts);

    // avatar specific methods
    bool buildAvatarFileName(QString token, bool createDir,
        QString &avatarFileName, QString &mimeTypeFileName);

    struct ContactListUpdateInfo;
    struct ContactListGroupsUpdateInfo;
    struct ContactListGroupRenamedInfo;

    ContactManager *parent;
    QWeakPointer<Connection> connection;

    QMap<uint, QWeakPointer<Contact> > contacts;

    QMap<Feature, bool> tracking;
    Features supportedFeatures;

    // roster
    bool fallbackContactList;
    Contacts cachedAllKnownContacts;

    // new roster API
    bool canChangeContactList;
    bool contactListRequestUsesMessage;
    QSet<QString> allKnownGroups;
    bool contactListGroupPropertiesReceived;
    QQueue<void (Private::*)()> contactListChangesQueue;
    QQueue<ContactListUpdateInfo> contactListUpdatesQueue;
    QQueue<ContactListGroupsUpdateInfo> contactListGroupsUpdatesQueue;
    QQueue<QStringList> contactListGroupsCreatedQueue;
    QQueue<ContactListGroupRenamedInfo> contactListGroupRenamedQueue;
    QQueue<QStringList> contactListGroupsRemovedQueue;
    bool processingContactListChanges;

    // old roster API
    QMap<uint, ContactListChannel> contactListChannels;
    ChannelPtr subscribeChannel;
    ChannelPtr publishChannel;
    ChannelPtr storedChannel;
    ChannelPtr denyChannel;
    QMap<QString, ChannelPtr> contactListGroupChannels;
    QList<ChannelPtr> removedContactListGroupChannels;

    // avatar
    UIntList requestAvatarsQueue;
    bool requestAvatarsIdle;
};

struct ContactManager::Private::ContactListUpdateInfo
{
    ContactListUpdateInfo(const ContactSubscriptionMap &changes, const UIntList &removals)
        : changes(changes),
          removals(removals)
    {
    }

    ContactSubscriptionMap changes;
    UIntList removals;
};

struct ContactManager::Private::ContactListGroupsUpdateInfo
{
    ContactListGroupsUpdateInfo(const UIntList &contacts,
            const QStringList &groupsAdded, const QStringList &groupsRemoved)
        : contacts(contacts),
          groupsAdded(groupsAdded),
          groupsRemoved(groupsRemoved)
    {
    }

    UIntList contacts;
    QStringList groupsAdded;
    QStringList groupsRemoved;
};

struct ContactManager::Private::ContactListGroupRenamedInfo
{
    ContactListGroupRenamedInfo(const QString &oldName, const QString &newName)
        : oldName(oldName),
          newName(newName)
    {
    }

    QString oldName;
    QString newName;
};

ContactManager::Private::Private(ContactManager *parent, Connection *connection)
    : parent(parent),
      connection(connection),
      fallbackContactList(false),
      canChangeContactList(false),
      contactListRequestUsesMessage(false),
      contactListGroupPropertiesReceived(false),
      processingContactListChanges(false),
      requestAvatarsIdle(false)
{
}

void ContactManager::Private::ensureTracking(const Feature &feature)
{
    if (tracking[feature]) {
        return;
    }

    ConnectionPtr conn(parent->connection());

    if (feature == Contact::FeatureAlias) {
        Client::ConnectionInterfaceAliasingInterface *aliasingInterface =
            conn->interface<Client::ConnectionInterfaceAliasingInterface>();

        parent->connect(
                aliasingInterface,
                SIGNAL(AliasesChanged(Tp::AliasPairList)),
                SLOT(onAliasesChanged(Tp::AliasPairList)));
    } else if (feature == Contact::FeatureAvatarData) {
        Client::ConnectionInterfaceAvatarsInterface *avatarsInterface =
            conn->interface<Client::ConnectionInterfaceAvatarsInterface>();

        parent->connect(
                avatarsInterface,
                SIGNAL(AvatarRetrieved(uint,QString,QByteArray,QString)),
                SLOT(onAvatarRetrieved(uint,QString,QByteArray,QString)));
    } else if (feature == Contact::FeatureAvatarToken) {
        Client::ConnectionInterfaceAvatarsInterface *avatarsInterface =
            conn->interface<Client::ConnectionInterfaceAvatarsInterface>();

        parent->connect(
                avatarsInterface,
                SIGNAL(AvatarUpdated(uint,QString)),
                SLOT(onAvatarUpdated(uint,QString)));
    } else if (feature == Contact::FeatureCapabilities) {
        Client::ConnectionInterfaceContactCapabilitiesInterface *contactCapabilitiesInterface =
            conn->interface<Client::ConnectionInterfaceContactCapabilitiesInterface>();

        parent->connect(
                contactCapabilitiesInterface,
                SIGNAL(ContactCapabilitiesChanged(Tp::ContactCapabilitiesMap)),
                SLOT(onCapabilitiesChanged(Tp::ContactCapabilitiesMap)));
    } else if (feature == Contact::FeatureInfo) {
        Client::ConnectionInterfaceContactInfoInterface *contactInfoInterface =
            conn->interface<Client::ConnectionInterfaceContactInfoInterface>();

        parent->connect(
                contactInfoInterface,
                SIGNAL(ContactInfoChanged(uint,Tp::ContactInfoFieldList)),
                SLOT(onContactInfoChanged(uint,Tp::ContactInfoFieldList)));
    } else if (feature == Contact::FeatureLocation) {
        Client::ConnectionInterfaceLocationInterface *locationInterface =
            conn->interface<Client::ConnectionInterfaceLocationInterface>();

        parent->connect(
                locationInterface,
                SIGNAL(LocationUpdated(uint,QVariantMap)),
                SLOT(onLocationUpdated(uint,QVariantMap)));
    } else if (feature == Contact::FeatureSimplePresence) {
        Client::ConnectionInterfaceSimplePresenceInterface *simplePresenceInterface =
            conn->interface<Client::ConnectionInterfaceSimplePresenceInterface>();

        parent->connect(
                simplePresenceInterface,
                SIGNAL(PresencesChanged(Tp::SimpleContactPresences)),
                SLOT(onPresencesChanged(Tp::SimpleContactPresences)));
    } else if (feature == Contact::FeatureRosterGroups) {
        // nothing to do here, but we don't want to warn
        ;
    } else {
        warning() << " Unknown feature" << feature
            << "when trying to figure out how to connect change notification!";
    }

    tracking[feature] = true;
}


void ContactManager::Private::processContactListChanges()
{
    if (processingContactListChanges || contactListChangesQueue.isEmpty()) {
        return;
    }

    processingContactListChanges = true;
    (this->*(contactListChangesQueue.dequeue()))();
}

void ContactManager::Private::processContactListUpdates()
{
    ContactListUpdateInfo info = contactListUpdatesQueue.head();

    // construct Contact objects for all contacts in added to the contact list
    UIntList contacts;
    ContactSubscriptionMap::const_iterator begin = info.changes.constBegin();
    ContactSubscriptionMap::const_iterator end = info.changes.constEnd();
    for (ContactSubscriptionMap::const_iterator i = begin; i != end; ++i) {
        uint bareHandle = i.key();
        contacts << bareHandle;
    }

    Features features;
    if (parent->connection()->isReady(Connection::FeatureRosterGroups)) {
        features << Contact::FeatureRosterGroups;
    }
    PendingContacts *pc = parent->contactsForHandles(contacts, features);
    parent->connect(pc,
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onContactListNewContactsConstructed(Tp::PendingOperation*)));
}

void ContactManager::Private::processContactListGroupsUpdates()
{
    ContactListGroupsUpdateInfo info = contactListGroupsUpdatesQueue.dequeue();

    foreach (const QString &group, info.groupsAdded) {
        Contacts contacts;
        foreach (uint bareHandle, info.contacts) {
            ContactPtr contact = parent->lookupContactByHandle(bareHandle);
            if (!contact) {
                warning() << "contact with handle" << bareHandle << "was added to a group but "
                    "never added to the contact list, ignoring";
                continue;
            }
            contacts << contact;
            contact->setAddedToGroup(group);
        }

        emit parent->groupMembersChanged(group, contacts,
                Contacts(), Channel::GroupMemberChangeDetails());
    }

    foreach (const QString &group, info.groupsRemoved) {
        Contacts contacts;
        foreach (uint bareHandle, info.contacts) {
            ContactPtr contact = parent->lookupContactByHandle(bareHandle);
            if (!contact) {
                warning() << "contact with handle" << bareHandle << "was removed from a group but "
                    "never added to the contact list, ignoring";
                continue;
            }
            contacts << contact;
            contact->setRemovedFromGroup(group);
        }

        emit parent->groupMembersChanged(group, Contacts(),
                contacts, Channel::GroupMemberChangeDetails());
    }

    processingContactListChanges = false;
    processContactListChanges();
}

void ContactManager::Private::processContactListGroupsCreated()
{
    QStringList names = contactListGroupsCreatedQueue.dequeue();
    foreach (const QString &name, names) {
        allKnownGroups.insert(name);
        emit parent->groupAdded(name);
    }

    processingContactListChanges = false;
    processContactListChanges();
}

void ContactManager::Private::processContactListGroupRenamed()
{
    Private::ContactListGroupRenamedInfo info = contactListGroupRenamedQueue.dequeue();
    allKnownGroups.remove(info.oldName);
    allKnownGroups.insert(info.newName);
    emit parent->groupRenamed(info.oldName, info.newName);

    processingContactListChanges = false;
    processContactListChanges();
}

void ContactManager::Private::processContactListGroupsRemoved()
{
    QStringList names = contactListGroupsRemovedQueue.dequeue();
    foreach (const QString &name, names) {
        allKnownGroups.remove(name);
        emit parent->groupRemoved(name);
    }

    processingContactListChanges = false;
    processContactListChanges();
}

Contacts ContactManager::Private::allKnownContactsFallback() const
{
    Contacts contacts;
    foreach (const ContactListChannel &contactListChannel, contactListChannels) {
        ChannelPtr channel = contactListChannel.channel;
        if (!channel) {
            continue;
        }
        contacts.unite(channel->groupContacts());
        contacts.unite(channel->groupLocalPendingContacts());
        contacts.unite(channel->groupRemotePendingContacts());
    }
    return contacts;
}

void ContactManager::Private::computeKnownContactsChangesFallback(const Tp::Contacts& added,
        const Tp::Contacts& pendingAdded, const Tp::Contacts& remotePendingAdded,
        const Tp::Contacts& removed, const Channel::GroupMemberChangeDetails &details)
{
    // First of all, compute the real additions/removals based upon our cache
    Tp::Contacts realAdded;
    realAdded.unite(added);
    realAdded.unite(pendingAdded);
    realAdded.unite(remotePendingAdded);
    realAdded.subtract(cachedAllKnownContacts);
    Tp::Contacts realRemoved = removed;
    realRemoved.intersect(cachedAllKnownContacts);

    // Check if realRemoved have been _really_ removed from all lists
    foreach (const ContactListChannel &contactListChannel, contactListChannels) {
        ChannelPtr channel = contactListChannel.channel;
        if (!channel) {
            continue;
        }
        realRemoved.subtract(channel->groupContacts());
        realRemoved.subtract(channel->groupLocalPendingContacts());
        realRemoved.subtract(channel->groupRemotePendingContacts());
    }

    // Are there any real changes?
    if (!realAdded.isEmpty() || !realRemoved.isEmpty()) {
        // Yes, update our "cache" and emit the signal
        cachedAllKnownContacts.unite(realAdded);
        cachedAllKnownContacts.subtract(realRemoved);
        emit parent->allKnownContactsChanged(realAdded, realRemoved, details);
    }
}

void ContactManager::Private::updateContactsBlockState()
{
    if (!denyChannel) {
        return;
    }

    Contacts denyContacts;
    if (denyChannel) {
        denyContacts = denyChannel->groupContacts();
    }

    foreach (ContactPtr contact, denyContacts) {
        contact->setBlocked(true);
    }
}

void ContactManager::Private::updateContactsPresenceStateFallback()
{
    if (!subscribeChannel && !publishChannel) {
        return;
    }

    Contacts subscribeContacts;
    Contacts subscribeContactsRP;

    if (subscribeChannel) {
        subscribeContacts = subscribeChannel->groupContacts();
        subscribeContactsRP = subscribeChannel->groupRemotePendingContacts();
    }

    Contacts publishContacts;
    Contacts publishContactsLP;
    if (publishChannel) {
        publishContacts = publishChannel->groupContacts();
        publishContactsLP = publishChannel->groupLocalPendingContacts();
    }

    Contacts contacts = allKnownContactsFallback();
    foreach (ContactPtr contact, contacts) {
        if (subscribeChannel) {
            // not in "subscribe" -> No, in "subscribe" lp -> Ask, in "subscribe" current -> Yes
            if (subscribeContacts.contains(contact)) {
                contact->setSubscriptionState(SubscriptionStateYes);
            } else if (subscribeContactsRP.contains(contact)) {
                contact->setSubscriptionState(SubscriptionStateAsk);
            } else {
                contact->setSubscriptionState(SubscriptionStateNo);
            }
        }

        if (publishChannel) {
            // not in "publish" -> No, in "subscribe" rp -> Ask, in "publish" current -> Yes
            if (publishContacts.contains(contact)) {
                contact->setPublishState(SubscriptionStateYes);
            } else if (publishContactsLP.contains(contact)) {
                contact->setPublishState(SubscriptionStateAsk,
                        publishChannel->groupLocalPendingContactChangeInfo(contact).message());
            } else {
                contact->setPublishState(SubscriptionStateNo);
            }
        }
    }
}

PendingOperation *ContactManager::Private::requestPresenceSubscriptionFallback(
        const QList<ContactPtr> &contacts, const QString &message)
{
    if (!subscribeChannel) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
                QLatin1String("Cannot subscribe to contacts' presence on this protocol"),
                parent->connection());
    }

    return subscribeChannel->groupAddContacts(contacts, message);
}

PendingOperation *ContactManager::Private::removePresenceSubscriptionFallback(
        const QList<ContactPtr> &contacts, const QString &message)
{
    if (!subscribeChannel) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
                QLatin1String("Cannot subscribe to contacts' presence on this protocol"),
                parent->connection());
    }

    return subscribeChannel->groupRemoveContacts(contacts, message);
}

PendingOperation *ContactManager::Private::authorizePresencePublicationFallback(
        const QList<ContactPtr> &contacts, const QString &message)
{
    if (!publishChannel) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
                QLatin1String("Cannot control publication of presence on this protocol"),
                parent->connection());
    }

    return publishChannel->groupAddContacts(contacts, message);
}

PendingOperation *ContactManager::Private::removePresencePublicationFallback(
        const QList<ContactPtr> &contacts, const QString &message)
{
    if (!publishChannel) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
                QLatin1String("Cannot control publication of presence on this protocol"),
                parent->connection());
    }

    return publishChannel->groupRemoveContacts(contacts, message);
}

PendingOperation *ContactManager::Private::removeContactsFallback(
        const QList<ContactPtr> &contacts, const QString &message)
{
    /* If the CM implements stored channel correctly, it should have the
     * wanted behaviour. Otherwise we have to fallback to remove from publish
     * and subscribe channels.
     */

    if (storedChannel &&
        storedChannel->groupCanRemoveContacts()) {
        debug() << "Removing contacts from stored list";
        return storedChannel->groupRemoveContacts(contacts, message);
    }

    QList<PendingOperation*> operations;

    if (parent->canRemovePresenceSubscription()) {
        debug() << "Removing contacts from subscribe list";
        operations << parent->removePresenceSubscription(contacts, message);
    }

    if (parent->canRemovePresencePublication()) {
        debug() << "Removing contacts from publish list";
        operations << parent->removePresencePublication(contacts, message);
    }

    if (operations.isEmpty()) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
                QLatin1String("Cannot remove contacts on this protocol"),
                parent->connection());
    }

    return new PendingComposite(operations, parent->connection());
}

QString ContactManager::Private::addContactListGroupChannelFallback(
        const ChannelPtr &contactListGroupChannel)
{
    QString id = contactListGroupChannel->immutableProperties().value(
            QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetID")).toString();
    contactListGroupChannels.insert(id, contactListGroupChannel);
    parent->connect(contactListGroupChannel.data(),
            SIGNAL(groupMembersChanged(
                   Tp::Contacts,
                   Tp::Contacts,
                   Tp::Contacts,
                   Tp::Contacts,
                   Tp::Channel::GroupMemberChangeDetails)),
            SLOT(onContactListGroupMembersChangedFallback(
                   Tp::Contacts,
                   Tp::Contacts,
                   Tp::Contacts,
                   Tp::Contacts,
                   Tp::Channel::GroupMemberChangeDetails)));
    parent->connect(contactListGroupChannel.data(),
            SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
            SLOT(onContactListGroupRemovedFallback(Tp::DBusProxy*,QString,QString)));

    foreach (const ContactPtr &contact, contactListGroupChannel->groupContacts()) {
        contact->setAddedToGroup(id);
    }
    return id;
}

PendingOperation *ContactManager::Private::addGroupFallback(const QString &group)
{
    QVariantMap request;
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"),
                                 QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_CONTACT_LIST));
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"),
                                 (uint) Tp::HandleTypeGroup);
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetID"),
                                 group);
    return parent->connection()->lowlevel()->ensureChannel(request);
}

PendingOperation *ContactManager::Private::removeGroupFallback(const QString &group)
{
    if (!contactListGroupChannels.contains(group)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT),
                QLatin1String("Invalid group"),
                parent->connection());
    }

    ChannelPtr channel = contactListGroupChannels[group];
    PendingContactManagerRemoveContactListGroup *op =
        new PendingContactManagerRemoveContactListGroup(channel);
    return op;
}

PendingOperation *ContactManager::Private::addContactsToGroupFallback(const QString &group,
        const QList<ContactPtr> &contacts)
{
    if (!contactListGroupChannels.contains(group)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT),
                QLatin1String("Invalid group"),
                parent->connection());
    }

    ChannelPtr channel = contactListGroupChannels[group];
    return channel->groupAddContacts(contacts);
}

PendingOperation *ContactManager::Private::removeContactsFromGroupFallback(const QString &group,
        const QList<ContactPtr> &contacts)
{
    if (!contactListGroupChannels.contains(group)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT),
                QLatin1String("Invalid group"),
                parent->connection());
    }

    ChannelPtr channel = contactListGroupChannels[group];
    return channel->groupRemoveContacts(contacts);
}

bool ContactManager::Private::buildAvatarFileName(QString token, bool createDir,
        QString &avatarFileName, QString &mimeTypeFileName)
{
    QString cacheDir = QString(QLatin1String(qgetenv("XDG_CACHE_HOME")));
    if (cacheDir.isEmpty()) {
        cacheDir = QString(QLatin1String("%1/.cache")).arg(QLatin1String(qgetenv("HOME")));
    }

    ConnectionPtr conn(parent->connection());
    QString path = QString(QLatin1String("%1/telepathy/avatars/%2/%3")).
        arg(cacheDir).arg(conn->cmName()).arg(conn->protocolName());

    if (createDir && !QDir().mkpath(path)) {
        return false;
    }

    avatarFileName = QString(QLatin1String("%1/%2")).arg(path).arg(escapeAsIdentifier(token));
    mimeTypeFileName = QString(QLatin1String("%1.mime")).arg(avatarFileName);

    return true;
}

ContactManager::ContactManager(Connection *connection)
    : Object(),
      mPriv(new Private(this, connection))
{
}

ContactManager::~ContactManager()
{
    delete mPriv;
}

ConnectionPtr ContactManager::connection() const
{
    return ConnectionPtr(mPriv->connection);
}

Features ContactManager::supportedFeatures() const
{
    if (mPriv->supportedFeatures.isEmpty() &&
        connection()->interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_CONTACTS))) {
        Features allFeatures = Features()
            << Contact::FeatureAlias
            << Contact::FeatureAvatarToken
            << Contact::FeatureAvatarData
            << Contact::FeatureSimplePresence
            << Contact::FeatureCapabilities
            << Contact::FeatureLocation
            << Contact::FeatureInfo;
        QStringList interfaces = connection()->lowlevel()->contactAttributeInterfaces();
        foreach (const Feature &feature, allFeatures) {
            if (interfaces.contains(featureToInterface(feature))) {
                mPriv->supportedFeatures.insert(feature);
            }
        }

        debug() << mPriv->supportedFeatures.size() << "contact features supported using" << this;
    }

    return mPriv->supportedFeatures;
}

/**
 * Return a list of relevant contacts (a reasonable guess as to what should
 * be displayed as "the contact list").
 *
 * This may include any or all of: contacts whose presence the user receives,
 * contacts who are allowed to see the user's presence, contacts stored in
 * some persistent contact list on the server, contacts who the user
 * has blocked from communicating with them, or contacts who are relevant
 * in some other way.
 *
 * User interfaces displaying a contact list will probably want to filter this
 * list and display some suitable subset of it.
 *
 * On protocols where there is no concept of presence or a centrally-stored
 * contact list (like IRC), this method may return an empty list.
 *
 * \return Some contacts
 */
Contacts ContactManager::allKnownContacts() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return Contacts();
    }

    if (mPriv->fallbackContactList) {
        return mPriv->allKnownContactsFallback();
    }

    return mPriv->cachedAllKnownContacts;
}

/**
 * Return a list of user-defined contact list groups' names.
 *
 * This method requires Connection::FeatureRosterGroups to be enabled.
 *
 * \return List of user-defined contact list groups names.
 */
QStringList ContactManager::allKnownGroups() const
{
    if (!connection()->isReady(Connection::FeatureRosterGroups)) {
        return QStringList();
    }

    if (mPriv->fallbackContactList) {
        return mPriv->contactListGroupChannels.keys();
    }

    return mPriv->allKnownGroups.toList();
}

/**
 * Attempt to add an user-defined contact list group named \a group.
 *
 * This method requires Connection::FeatureRosterGroups to be enabled.
 *
 * On some protocols (e.g. XMPP) empty groups are not represented on the server,
 * so disconnecting from the server and reconnecting might cause empty groups to
 * vanish.
 *
 * The returned pending operation will finish successfully if the group already
 * exists.
 *
 * FIXME: currently, the returned pending operation will finish as soon as the
 * CM EnsureChannel has returned. At this point however the NewChannels
 * mechanism hasn't yet populated our contactListGroupChannels member, which
 * means one has to wait for groupAdded before being able to actually do
 * something with the group (which is error-prone!). This is fd.o #29728.
 *
 * \param group Group name.
 * \return A pending operation which will return when an attempt has been made
 *         to add an user-defined contact list group.
 * \sa groupAdded(), addContactsToGroup()
 */
PendingOperation *ContactManager::addGroup(const QString &group)
{
    if (!connection()->isValid()) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"),
                connection());
    } else if (!connection()->isReady(Connection::FeatureRosterGroups)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureRosterGroups is not ready"),
                connection());
    }

    if (mPriv->fallbackContactList) {
        return mPriv->addGroupFallback(group);
    }

    if (!connection()->hasInterface(TP_QT4_IFACE_CONNECTION_INTERFACE_CONTACT_GROUPS)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
                QLatin1String("Not implemented"),
                connection());
    }

    Client::ConnectionInterfaceContactGroupsInterface *iface =
        connection()->interface<Client::ConnectionInterfaceContactGroupsInterface>();
    Q_ASSERT(iface);
    return new PendingVoid(iface->AddToGroup(group, UIntList()), connection());
}

/**
 * Attempt to remove an user-defined contact list group named \a group.
 *
 * This method requires Connection::FeatureRosterGroups to be enabled.
 *
 * FIXME: currently, the returned pending operation will finish as soon as the
 * CM close() has returned. At this point however the invalidated()
 * mechanism hasn't yet removed the channel from our contactListGroupChannels
 * member, which means contacts can seemingly still be added to the group etc.
 * until the change is picked up (and groupRemoved is emitted). This is fd.o
 * #29728.
 *
 * \param group Group name.
 * \return A pending operation which will return when an attempt has been made
 *         to remove an user-defined contact list group.
 * \sa groupRemoved(), removeContactsFromGroup()
 */
PendingOperation *ContactManager::removeGroup(const QString &group)
{
    if (!connection()->isValid()) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"),
                connection());
    } else if (!connection()->isReady(Connection::FeatureRosterGroups)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureRosterGroups is not ready"),
                connection());
    }

    if (mPriv->fallbackContactList) {
        return mPriv->removeGroupFallback(group);
    }

    if (!connection()->hasInterface(TP_QT4_IFACE_CONNECTION_INTERFACE_CONTACT_GROUPS)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
                QLatin1String("Not implemented"),
                connection());
    }

    Client::ConnectionInterfaceContactGroupsInterface *iface =
        connection()->interface<Client::ConnectionInterfaceContactGroupsInterface>();
    Q_ASSERT(iface);
    return new PendingVoid(iface->RemoveGroup(group), connection());
}

/**
 * Return the contacts in the given user-defined contact list group
 * named \a group.
 *
 * This method requires Connection::FeatureRosterGroups to be enabled.
 *
 * \param group Group name.
 * \return List of contacts on a user-defined contact list group, or an empty
 *         list if the group does not exist.
 * \sa allKnownGroups(), contactGroups()
 */
Contacts ContactManager::groupContacts(const QString &group) const
{
    if (!connection()->isReady(Connection::FeatureRosterGroups)) {
        return Contacts();
    }

    if (mPriv->fallbackContactList) {
        if (!mPriv->contactListGroupChannels.contains(group)) {
            return Contacts();
        }

        ChannelPtr channel = mPriv->contactListGroupChannels[group];
        return channel->groupContacts();
    }

    Contacts ret;
    foreach (const ContactPtr &contact, allKnownContacts()) {
        if (contact->groups().contains(group))
            ret << contact;
    }
    return ret;
}

/**
 * Attempt to add the given \a contacts to the user-defined contact list
 * group named \a group.
 *
 * This method requires Connection::FeatureRosterGroups to be enabled.
 *
 * \param group Group name.
 * \param contacts Contacts to add.
 * \return A pending operation which will return when an attempt has been made
 *         to add the contacts to the user-defined contact list group.
 */
PendingOperation *ContactManager::addContactsToGroup(const QString &group,
        const QList<ContactPtr> &contacts)
{
    if (!connection()->isValid()) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"),
                connection());
    } else if (!connection()->isReady(Connection::FeatureRosterGroups)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureRosterGroups is not ready"),
                connection());
    }

    if (mPriv->fallbackContactList) {
        return mPriv->addContactsToGroupFallback(group, contacts);
    }

    if (!connection()->hasInterface(TP_QT4_IFACE_CONNECTION_INTERFACE_CONTACT_GROUPS)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
                QLatin1String("Not implemented"),
                connection());
    }

    UIntList handles;
    foreach (const ContactPtr &contact, contacts) {
        handles << contact->handle()[0];
    }

    Client::ConnectionInterfaceContactGroupsInterface *iface =
        connection()->interface<Client::ConnectionInterfaceContactGroupsInterface>();
    Q_ASSERT(iface);
    return new PendingVoid(iface->AddToGroup(group, handles), connection());
}

/**
 * Attempt to remove the given \a contacts from the user-defined contact list
 * group named \a group.
 *
 * This method requires Connection::FeatureRosterGroups to be enabled.
 *
 * \param group Group name.
 * \param contacts Contacts to remove.
 * \return A pending operation which will return when an attempt has been made
 *         to remove the contacts from the user-defined contact list group.
 */
PendingOperation *ContactManager::removeContactsFromGroup(const QString &group,
        const QList<ContactPtr> &contacts)
{
    if (!connection()->isValid()) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"),
                connection());
    } else if (!connection()->isReady(Connection::FeatureRosterGroups)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureRosterGroups is not ready"),
                connection());
    }

    if (mPriv->fallbackContactList) {
        return mPriv->removeContactsFromGroupFallback(group, contacts);
    }

    if (!connection()->hasInterface(TP_QT4_IFACE_CONNECTION_INTERFACE_CONTACT_GROUPS)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
                QLatin1String("Not implemented"),
                connection());
    }

    UIntList handles;
    foreach (const ContactPtr &contact, contacts) {
        handles << contact->handle()[0];
    }

    Client::ConnectionInterfaceContactGroupsInterface *iface =
        connection()->interface<Client::ConnectionInterfaceContactGroupsInterface>();
    Q_ASSERT(iface);
    return new PendingVoid(iface->RemoveFromGroup(group, handles), connection());
}

/**
 * Return whether subscribing to additional contacts' presence is supported
 * on this channel.
 *
 * In some protocols, the list of contacts whose presence can be seen is
 * fixed, so we can't subscribe to the presence of additional contacts.
 *
 * Notably, in link-local XMPP, you can see the presence of everyone on the
 * local network, and trying to add more subscriptions would be meaningless.
 *
 * \return Whether Contact::requestPresenceSubscription and
 *         requestPresenceSubscription are likely to succeed
 */
bool ContactManager::canRequestPresenceSubscription() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return false;
    }

    if (mPriv->fallbackContactList) {
        return mPriv->subscribeChannel &&
            mPriv->subscribeChannel->groupCanAddContacts();
    }

    return mPriv->canChangeContactList;
}

/**
 * Return whether a message can be sent when subscribing to contacts'
 * presence.
 *
 * If no message will actually be sent, user interfaces should avoid prompting
 * the user for a message, and use an empty string for the message argument.
 *
 * \return Whether the message argument to
 *         Contact::requestPresenceSubscription and
 *         requestPresenceSubscription is actually used
 */
bool ContactManager::subscriptionRequestHasMessage() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return false;
    }

    if (mPriv->fallbackContactList) {
        return mPriv->subscribeChannel &&
            (mPriv->subscribeChannel->groupFlags() &
             ChannelGroupFlagMessageAdd);
    }

    return mPriv->contactListRequestUsesMessage;
}

/**
 * Attempt to subscribe to the presence of the given contacts.
 *
 * This operation is sometimes called "adding contacts to the buddy
 * list" or "requesting authorization".
 *
 * This method requires Connection::FeatureRoster to be ready.
 *
 * On most protocols, the contacts will need to give permission
 * before the user will be able to receive their presence: if so, they will
 * be in presence state Contact::PresenceStateAsk until they authorize
 * or deny the request.
 *
 * The returned PendingOperation will return successfully when a request to
 * subscribe to the contacts' presence has been submitted, or fail if this
 * cannot happen. In particular, it does not wait for the contacts to give
 * permission for the presence subscription.
 *
 * \param contacts Contacts whose presence is desired
 * \param message A message from the user which is either transmitted to the
 *                contacts, or ignored, depending on the protocol
 * \return A pending operation which will return when an attempt has been made
 *         to subscribe to the contacts' presence
 */
PendingOperation *ContactManager::requestPresenceSubscription(
        const QList<ContactPtr> &contacts, const QString &message)
{
    if (!connection()->isValid()) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"),
                connection());
    } else if (!connection()->isReady(Connection::FeatureRoster)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureRoster is not ready"),
                connection());
    }

    if (mPriv->fallbackContactList) {
        return mPriv->requestPresenceSubscriptionFallback(contacts, message);
    }

    UIntList handles;
    foreach (const ContactPtr &contact, contacts) {
        handles << contact->handle()[0];
    }

    Client::ConnectionInterfaceContactListInterface *iface =
        connection()->interface<Client::ConnectionInterfaceContactListInterface>();
    Q_ASSERT(iface);
    return new PendingVoid(iface->RequestSubscription(handles, message), connection());
}

/**
 * Return whether the user can stop receiving the presence of a contact
 * whose presence they have subscribed to.
 *
 * \return Whether removePresenceSubscription and
 *         Contact::removePresenceSubscription are likely to succeed
 *         for contacts with subscription state Contact::PresenceStateYes
 */
bool ContactManager::canRemovePresenceSubscription() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return false;
    }

    if (mPriv->fallbackContactList) {
        return mPriv->subscribeChannel &&
            mPriv->subscribeChannel->groupCanRemoveContacts();
    }

    return mPriv->canChangeContactList;
}

/**
 * Return whether a message can be sent when removing an existing subscription
 * to the presence of a contact.
 *
 * If no message will actually be sent, user interfaces should avoid prompting
 * the user for a message, and use an empty string for the message argument.
 *
 * \return Whether the message argument to
 *         Contact::removePresenceSubscription and
 *         removePresenceSubscription is actually used,
 *         for contacts with subscription state Contact::PresenceStateYes
 */
bool ContactManager::subscriptionRemovalHasMessage() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return false;
    }

    if (mPriv->fallbackContactList) {
        return mPriv->subscribeChannel &&
            (mPriv->subscribeChannel->groupFlags() &
             ChannelGroupFlagMessageRemove);
    }

    return false;
}

/**
 * Return whether the user can cancel a request to subscribe to a contact's
 * presence before that contact has responded.
 *
 * \return Whether removePresenceSubscription and
 *         Contact::removePresenceSubscription are likely to succeed
 *         for contacts with subscription state Contact::PresenceStateAsk
 */
bool ContactManager::canRescindPresenceSubscriptionRequest() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return false;
    }

    if (mPriv->fallbackContactList) {
        return mPriv->subscribeChannel &&
            mPriv->subscribeChannel->groupCanRescindContacts();
    }

    return mPriv->canChangeContactList;
}

/**
 * Return whether a message can be sent when cancelling a request to
 * subscribe to the presence of a contact.
 *
 * If no message will actually be sent, user interfaces should avoid prompting
 * the user for a message, and use an empty string for the message argument.
 *
 * \return Whether the message argument to
 *         Contact::removePresenceSubscription and
 *         removePresenceSubscription is actually used,
 *         for contacts with subscription state Contact::PresenceStateAsk
 */
bool ContactManager::subscriptionRescindingHasMessage() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return false;
    }

    if (mPriv->fallbackContactList) {
        return mPriv->subscribeChannel &&
            (mPriv->subscribeChannel->groupFlags() &
             ChannelGroupFlagMessageRescind);
    }

    return false;
}

/**
 * Attempt to stop receiving the presence of the given contacts, or cancel
 * a request to subscribe to their presence that was previously sent.
 *
 * This method requires Connection::FeatureRoster to be ready.
 *
 * \param contacts Contacts whose presence is no longer required
 * \message A message from the user which is either transmitted to the
 *          contacts, or ignored, depending on the protocol
 * \return A pending operation which will return when an attempt has been made
 *         to remove any subscription to the contacts' presence
 */
PendingOperation *ContactManager::removePresenceSubscription(
        const QList<ContactPtr> &contacts, const QString &message)
{
    if (!connection()->isValid()) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"),
                connection());
    } else if (!connection()->isReady(Connection::FeatureRoster)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureRoster is not ready"),
                connection());
    }

    if (mPriv->fallbackContactList) {
        return mPriv->removePresenceSubscriptionFallback(contacts, message);
    }

    UIntList handles;
    foreach (const ContactPtr &contact, contacts) {
        handles << contact->handle()[0];
    }

    Client::ConnectionInterfaceContactListInterface *iface =
        connection()->interface<Client::ConnectionInterfaceContactListInterface>();
    Q_ASSERT(iface);
    return new PendingVoid(iface->Unsubscribe(handles), connection());
}

/**
 * Return true if the publication of the user's presence to contacts can be
 * authorized.
 *
 * This is always true, unless the protocol has no concept of authorizing
 * publication (in which case contacts' publication status can never be
 * Contact::PresenceStateAsk).
 */
bool ContactManager::canAuthorizePresencePublication() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return false;
    }

    if (mPriv->fallbackContactList) {
        // do not check for Channel::groupCanAddContacts as all contacts in local
        // pending can be added, even if the Channel::groupFlags() does not contain
        // the flag CanAdd
        return (bool) mPriv->publishChannel;
    }

    return mPriv->canChangeContactList;
}

/**
 * Return whether a message can be sent when authorizing a request from a
 * contact that the user's presence is published to them.
 *
 * If no message will actually be sent, user interfaces should avoid prompting
 * the user for a message, and use an empty string for the message argument.
 *
 * \return Whether the message argument to
 *         Contact::authorizePresencePublication and
 *         authorizePresencePublication is actually used,
 *         for contacts with subscription state Contact::PresenceStateAsk
 */
bool ContactManager::publicationAuthorizationHasMessage() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return false;
    }

    if (mPriv->fallbackContactList) {
        return mPriv->subscribeChannel &&
            (mPriv->subscribeChannel->groupFlags() &
             ChannelGroupFlagMessageAccept);
    }

    return false;
}

/**
 * If the given contacts have asked the user to publish presence to them,
 * grant permission for this publication to take place.
 *
 * This method requires Connection::FeatureRoster to be ready.
 *
 * \param contacts Contacts who should be allowed to receive the user's
 *                 presence
 * \message A message from the user which is either transmitted to the
 *          contacts, or ignored, depending on the protocol
 * \return A pending operation which will return when an attempt has been made
 *         to authorize publication of the user's presence to the contacts
 */
PendingOperation *ContactManager::authorizePresencePublication(
        const QList<ContactPtr> &contacts, const QString &message)
{
    if (!connection()->isValid()) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"),
                connection());
    } else if (!connection()->isReady(Connection::FeatureRoster)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureRoster is not ready"),
                connection());
    }

    if (mPriv->fallbackContactList) {
        return mPriv->authorizePresencePublicationFallback(contacts, message);
    }

    UIntList handles;
    foreach (const ContactPtr &contact, contacts) {
        handles << contact->handle()[0];
    }

    Client::ConnectionInterfaceContactListInterface *iface =
        connection()->interface<Client::ConnectionInterfaceContactListInterface>();
    Q_ASSERT(iface);
    return new PendingVoid(iface->AuthorizePublication(handles), connection());
}

/**
 * Return whether a message can be sent when rejecting a request from a
 * contact that the user's presence is published to them.
 *
 * If no message will actually be sent, user interfaces should avoid prompting
 * the user for a message, and use an empty string for the message argument.
 *
 * \return Whether the message argument to
 *         Contact::removePresencePublication and
 *         removePresencePublication is actually used,
 *         for contacts with subscription state Contact::PresenceStateAsk
 */
bool ContactManager::publicationRejectionHasMessage() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return false;
    }

    if (mPriv->fallbackContactList) {
        return mPriv->subscribeChannel &&
            (mPriv->subscribeChannel->groupFlags() &
             ChannelGroupFlagMessageReject);
    }

    return false;
}

/**
 * Return true if the publication of the user's presence to contacts can be
 * removed, even after permission has been given.
 *
 * (Rejecting requests for presence to be published is always allowed.)
 *
 * \return Whether removePresencePublication and
 *         Contact::removePresencePublication are likely to succeed
 *         for contacts with subscription state Contact::PresenceStateYes
 */
bool ContactManager::canRemovePresencePublication() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return false;
    }

    if (mPriv->fallbackContactList) {
        return mPriv->publishChannel &&
            mPriv->publishChannel->groupCanRemoveContacts();
    }

    return mPriv->canChangeContactList;
}

/**
 * Return whether a message can be sent when revoking earlier permission
 * that the user's presence is published to a contact.
 *
 * If no message will actually be sent, user interfaces should avoid prompting
 * the user for a message, and use an empty string for the message argument.
 *
 * \return Whether the message argument to
 *         Contact::removePresencePublication and
 *         removePresencePublication is actually used,
 *         for contacts with subscription state Contact::PresenceStateYes
 */
bool ContactManager::publicationRemovalHasMessage() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return false;
    }

    if (mPriv->fallbackContactList) {
        return mPriv->subscribeChannel &&
            (mPriv->subscribeChannel->groupFlags() &
             ChannelGroupFlagMessageRemove);
    }

    return false;
}

/**
 * If the given contacts have asked the user to publish presence to them,
 * deny this request (this should always succeed, unless a network error
 * occurs).
 *
 * This method requires Connection::FeatureRoster to be ready.
 *
 * If the given contacts already have permission to receive
 * the user's presence, attempt to revoke that permission (this might not
 * be supported by the protocol - canRemovePresencePublication
 * indicates whether it is likely to succeed).
 *
 * \param contacts Contacts who should no longer be allowed to receive the
 *                 user's presence
 * \message A message from the user which is either transmitted to the
 *          contacts, or ignored, depending on the protocol
 * \return A pending operation which will return when an attempt has been made
 *         to remove any publication of the user's presence to the contacts
 */
PendingOperation *ContactManager::removePresencePublication(
        const QList<ContactPtr> &contacts, const QString &message)
{
    if (!connection()->isValid()) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"),
                connection());
    } else if (!connection()->isReady(Connection::FeatureRoster)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureRoster is not ready"),
                connection());
    }

    if (mPriv->fallbackContactList) {
        return mPriv->removePresencePublicationFallback(contacts, message);
    }

    UIntList handles;
    foreach (const ContactPtr &contact, contacts) {
        handles << contact->handle()[0];
    }

    Client::ConnectionInterfaceContactListInterface *iface =
        connection()->interface<Client::ConnectionInterfaceContactListInterface>();
    Q_ASSERT(iface);
    return new PendingVoid(iface->Unpublish(handles), connection());
}

/**
 * Remove completely contacts from the server. It has the same effect than
 * calling removePresencePublication() and removePresenceSubscription(),
 * but also remove from 'stored' list if it exists.
 *
 * \param contacts Contacts who should be removed
 * \message A message from the user which is either transmitted to the
 *          contacts, or ignored, depending on the protocol
 * \return A pending operation which will return when an attempt has been made
 *         to remove any publication of the user's presence to the contacts
 */
PendingOperation *ContactManager::removeContacts(
        const QList<ContactPtr> &contacts, const QString &message)
{
    if (!connection()->isValid()) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"),
                connection());
    } else if (!connection()->isReady(Connection::FeatureRoster)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureRoster is not ready"),
                connection());
    }

    if (mPriv->fallbackContactList) {
        return mPriv->removeContactsFallback(contacts, message);
    }

    UIntList handles;
    foreach (const ContactPtr &contact, contacts) {
        handles << contact->handle()[0];
    }

    Client::ConnectionInterfaceContactListInterface *iface =
        connection()->interface<Client::ConnectionInterfaceContactListInterface>();
    Q_ASSERT(iface);
    return new PendingVoid(iface->RemoveContacts(handles), connection());
}

/**
 * Return whether this protocol has a list of blocked contacts.
 *
 * \return Whether blockContacts is likely to succeed
 */
bool ContactManager::canBlockContacts() const
{
    if (!connection()->isReady(Connection::FeatureRoster)) {
        return false;
    }

    return (bool) mPriv->denyChannel;
}

/**
 * Set whether the given contacts are blocked. Blocked contacts cannot send
 * messages to the user; depending on the protocol, blocking a contact may
 * have other effects.
 *
 * This method requires Connection::FeatureRoster to be ready.
 *
 * \param contacts Contacts who should be added to, or removed from, the list
 *                 of blocked contacts
 * \param value If true, add the contacts to the list of blocked contacts;
 *              if false, remove them from the list
 * \return A pending operation which will return when an attempt has been made
 *         to take the requested action
 */
PendingOperation *ContactManager::blockContacts(
        const QList<ContactPtr> &contacts, bool value)
{
    if (!connection()->isValid()) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"),
                connection());
    } else if (!connection()->isReady(Connection::FeatureRoster)) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureRoster is not ready"),
                connection());
    }

    if (!mPriv->denyChannel) {
        return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
                QLatin1String("Cannot block contacts on this protocol"),
                connection());
    }

    if (value) {
        return mPriv->denyChannel->groupAddContacts(contacts);
    } else {
        return mPriv->denyChannel->groupRemoveContacts(contacts);
    }
}

PendingContacts *ContactManager::contactsForHandles(const UIntList &handles,
        const Features &features)
{
    QMap<uint, ContactPtr> satisfyingContacts;
    QSet<uint> otherContacts;
    Features missingFeatures;

    // FeatureAvatarData depends on FeatureAvatarToken
    Features realFeatures(features);
    if (realFeatures.contains(Contact::FeatureAvatarData) &&
        !realFeatures.contains(Contact::FeatureAvatarToken)) {
        realFeatures.insert(Contact::FeatureAvatarToken);
    }

    if (!connection()->isValid()) {
        return new PendingContacts(ContactManagerPtr(this), handles, realFeatures, QStringList(),
                satisfyingContacts, otherContacts, QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"));
    } else if (!connection()->isReady(Connection::FeatureCore)) {
        return new PendingContacts(ContactManagerPtr(this), handles, realFeatures, QStringList(),
                satisfyingContacts, otherContacts, QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureCore is not ready"));
    }

    foreach (uint handle, handles) {
        ContactPtr contact = lookupContactByHandle(handle);
        if (contact) {
            if ((realFeatures - contact->requestedFeatures()).isEmpty()) {
                // Contact exists and has all the requested features
                satisfyingContacts.insert(handle, contact);
            } else {
                // Contact exists but is missing features
                otherContacts.insert(handle);
                missingFeatures.unite(realFeatures - contact->requestedFeatures());
            }
        } else {
            // Contact doesn't exist - we need to get all of the features (same as unite(features))
            missingFeatures = realFeatures;
            otherContacts.insert(handle);
        }
    }

    Features supported = supportedFeatures();
    QSet<QString> interfaces;
    foreach (const Feature &feature, missingFeatures) {
        mPriv->ensureTracking(feature);

        if (supported.contains(feature)) {
            // Only query interfaces which are reported as supported to not get an error
            interfaces.insert(featureToInterface(feature));
        }
    }

    PendingContacts *contacts =
        new PendingContacts(ContactManagerPtr(this), handles, realFeatures, interfaces.toList(),
                satisfyingContacts, otherContacts);
    return contacts;
}

PendingContacts *ContactManager::contactsForHandles(const ReferencedHandles &handles,
        const Features &features)
{
    return contactsForHandles(handles.toList(), features);
}

PendingContacts *ContactManager::contactsForIdentifiers(const QStringList &identifiers,
        const Features &features)
{
    if (!connection()->isValid()) {
        return new PendingContacts(ContactManagerPtr(this), identifiers, features,
                QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"));
    } else if (!connection()->isReady(Connection::FeatureCore)) {
        return new PendingContacts(ContactManagerPtr(this), identifiers, features,
                QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureCore is not ready"));
    }

    PendingContacts *contacts = new PendingContacts(ContactManagerPtr(this), identifiers, features);
    return contacts;
}

PendingContacts *ContactManager::upgradeContacts(const QList<ContactPtr> &contacts,
        const Features &features)
{
    if (!connection()->isValid()) {
        return new PendingContacts(ContactManagerPtr(this), contacts, features,
                QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection is invalid"));
    } else if (!connection()->isReady(Connection::FeatureCore)) {
        return new PendingContacts(ContactManagerPtr(this), contacts, features,
                QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
                QLatin1String("Connection::FeatureCore is not ready"));
    }

    return new PendingContacts(ContactManagerPtr(this), contacts, features);
}

ContactPtr ContactManager::lookupContactByHandle(uint handle)
{
    ContactPtr contact;

    if (mPriv->contacts.contains(handle)) {
        contact = ContactPtr(mPriv->contacts.value(handle));
        if (!contact) {
            // Dangling weak pointer, remove it
            mPriv->contacts.remove(handle);
        }
    }

    return contact;
}

void ContactManager::requestContactAvatar(Contact *contact)
{
    QString token = contact->avatarToken();
    QString avatarFileName;
    QString mimeTypeFileName;

    bool success = mPriv->buildAvatarFileName(token, false, avatarFileName,
        mimeTypeFileName);

    /* Check if the avatar is already in the cache */
    if (success && QFile::exists(avatarFileName)) {
        QFile mimeTypeFile(mimeTypeFileName);
        mimeTypeFile.open(QIODevice::ReadOnly);
        QString mimeType = QString(QLatin1String(mimeTypeFile.readAll()));
        mimeTypeFile.close();

        debug() << "Avatar found in cache for handle" << contact->handle()[0];
        debug() << "Filename:" << avatarFileName;
        debug() << "MimeType:" << mimeType;

        contact->receiveAvatarData(AvatarData(avatarFileName, mimeType));

        return;
    }

    /* Not found in cache, queue this contact. We do this to group contacts
     * for the AvatarRequest call */
    debug() << "Need to request avatar for handle" << contact->handle()[0];
    if (!mPriv->requestAvatarsIdle) {
        QTimer::singleShot(0, this, SLOT(doRequestAvatars()));
        mPriv->requestAvatarsIdle = true;
    }
    mPriv->requestAvatarsQueue.append(contact->handle()[0]);
}

void ContactManager::onAliasesChanged(const AliasPairList &aliases)
{
    debug() << "Got AliasesChanged for" << aliases.size() << "contacts";

    foreach (AliasPair pair, aliases) {
        ContactPtr contact = lookupContactByHandle(pair.handle);

        if (contact) {
            contact->receiveAlias(pair.alias);
        }
    }
}

void ContactManager::doRequestAvatars()
{
    debug() << "Request" << mPriv->requestAvatarsQueue.size() << "avatar(s)";

    Client::ConnectionInterfaceAvatarsInterface *avatarsInterface =
        connection()->interface<Client::ConnectionInterfaceAvatarsInterface>();
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
        avatarsInterface->RequestAvatars(mPriv->requestAvatarsQueue),
        this);
    connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), watcher,
        SLOT(deleteLater()));

    mPriv->requestAvatarsQueue = UIntList();
    mPriv->requestAvatarsIdle = false;
}

void ContactManager::onAvatarUpdated(uint handle, const QString &token)
{
    debug() << "Got AvatarUpdate for contact with handle" << handle;

    ContactPtr contact = lookupContactByHandle(handle);
    if (contact) {
        contact->receiveAvatarToken(token);
    }
}

void ContactManager::onAvatarRetrieved(uint handle, const QString &token,
    const QByteArray &data, const QString &mimeType)
{
    QString avatarFileName;
    QString mimeTypeFileName;

    debug() << "Got AvatarRetrieved for contact with handle" << handle;

    bool success = mPriv->buildAvatarFileName(token, true, avatarFileName,
        mimeTypeFileName);

    if (success) {
        QFile mimeTypeFile(mimeTypeFileName);
        QFile avatarFile(avatarFileName);

        debug() << "Write avatar in cache for handle" << handle;
        debug() << "Filename:" << avatarFileName;
        debug() << "MimeType:" << mimeType;

        mimeTypeFile.open(QIODevice::WriteOnly);
        mimeTypeFile.write(mimeType.toLatin1());
        mimeTypeFile.close();

        avatarFile.open(QIODevice::WriteOnly);
        avatarFile.write(data);
        avatarFile.close();
    }

    ContactPtr contact = lookupContactByHandle(handle);
    if (contact) {
        contact->setAvatarToken(token);
        contact->receiveAvatarData(AvatarData(avatarFileName, mimeType));
    }
}

void ContactManager::onPresencesChanged(const SimpleContactPresences &presences)
{
    debug() << "Got PresencesChanged for" << presences.size() << "contacts";

    foreach (uint handle, presences.keys()) {
        ContactPtr contact = lookupContactByHandle(handle);

        if (contact) {
            contact->receiveSimplePresence(presences[handle]);
        }
    }
}

void ContactManager::onCapabilitiesChanged(const ContactCapabilitiesMap &caps)
{
    debug() << "Got ContactCapabilitiesChanged for" << caps.size() << "contacts";

    foreach (uint handle, caps.keys()) {
        ContactPtr contact = lookupContactByHandle(handle);

        if (contact) {
            contact->receiveCapabilities(caps[handle]);
        }
    }
}

void ContactManager::onLocationUpdated(uint handle, const QVariantMap &location)
{
    debug() << "Got LocationUpdated for contact with handle" << handle;

    ContactPtr contact = lookupContactByHandle(handle);

    if (contact) {
        contact->receiveLocation(location);
    }
}

void ContactManager::onContactInfoChanged(uint handle,
        const Tp::ContactInfoFieldList &info)
{
    debug() << "Got ContactInfoChanged for contact with handle" << handle;

    ContactPtr contact = lookupContactByHandle(handle);

    if (contact) {
        contact->receiveInfo(info);
    }
}

void ContactManager::onContactListNewContactsConstructed(Tp::PendingOperation *op)
{
    if (op->isError()) {
        mPriv->contactListUpdatesQueue.dequeue();
        mPriv->processingContactListChanges = false;
        mPriv->processContactListChanges();
        return;
    }

    Private::ContactListUpdateInfo info = mPriv->contactListUpdatesQueue.dequeue();

    Tp::Contacts added;
    Tp::Contacts removed;

    ContactSubscriptionMap::const_iterator begin = info.changes.constBegin();
    ContactSubscriptionMap::const_iterator end = info.changes.constEnd();
    for (ContactSubscriptionMap::const_iterator i = begin; i != end; ++i) {
        uint bareHandle = i.key();
        ContactSubscriptions subscriptions = i.value();

        ContactPtr contact = lookupContactByHandle(bareHandle);
        if (!contact) {
            warning() << "Unable to construct contact for handle" << bareHandle;
            continue;
        }

        if (!mPriv->cachedAllKnownContacts.contains(contact)) {
            mPriv->cachedAllKnownContacts.insert(contact);
            added << contact;
        }

        contact->setSubscriptionState((SubscriptionState) subscriptions.subscribe);
        if (!subscriptions.publishRequest.isEmpty() &&
            subscriptions.publish == SubscriptionStateAsk) {
            Channel::GroupMemberChangeDetails publishRequestDetails;
            QVariantMap detailsMap;
            detailsMap.insert(QLatin1String("message"), subscriptions.publishRequest);
            publishRequestDetails = Channel::GroupMemberChangeDetails(ContactPtr(), detailsMap);
            // FIXME (API/ABI break) remove signal with details
            emit presencePublicationRequested(Contacts() << contact, publishRequestDetails);

            emit presencePublicationRequested(Contacts() << contact, subscriptions.publishRequest);
        }
        contact->setPublishState((SubscriptionState) subscriptions.publish,
                subscriptions.publishRequest);
    }

    foreach (uint bareHandle, info.removals) {
        ContactPtr contact = lookupContactByHandle(bareHandle);
        if (!contact) {
            warning() << "Unable to find removed contact with handle" << bareHandle;
            continue;
        }

        Q_ASSERT(mPriv->cachedAllKnownContacts.contains(contact));

        contact->setSubscriptionState(SubscriptionStateNo);
        contact->setPublishState(SubscriptionStateNo);
        mPriv->cachedAllKnownContacts.remove(contact);
        removed << contact;
    }

    if (!added.isEmpty() || !removed.isEmpty()) {
        emit allKnownContactsChanged(added, removed, Channel::GroupMemberChangeDetails());
    }

    mPriv->processingContactListChanges = false;
    mPriv->processContactListChanges();
}

void ContactManager::onContactListGroupsChanged(const Tp::UIntList &contacts,
        const QStringList &added, const QStringList &removed)
{
    Q_ASSERT(mPriv->fallbackContactList == false);

    if (!mPriv->contactListGroupPropertiesReceived) {
        return;
    }

    mPriv->contactListGroupsUpdatesQueue.enqueue(Private::ContactListGroupsUpdateInfo(contacts,
                added, removed));
    mPriv->contactListChangesQueue.enqueue(&Private::processContactListGroupsUpdates);
    mPriv->processContactListChanges();
}

void ContactManager::onContactListGroupsCreated(const QStringList &names)
{
    Q_ASSERT(mPriv->fallbackContactList == false);

    if (!mPriv->contactListGroupPropertiesReceived) {
        return;
    }

    mPriv->contactListGroupsCreatedQueue.enqueue(names);
    mPriv->contactListChangesQueue.enqueue(&Private::processContactListGroupsCreated);
    mPriv->processContactListChanges();
}

void ContactManager::onContactListGroupRenamed(const QString &oldName, const QString &newName)
{
    Q_ASSERT(mPriv->fallbackContactList == false);

    if (!mPriv->contactListGroupPropertiesReceived) {
        return;
    }

    mPriv->contactListGroupRenamedQueue.enqueue(
            Private::ContactListGroupRenamedInfo(oldName, newName));
    mPriv->contactListChangesQueue.enqueue(&Private::processContactListGroupRenamed);
    mPriv->processContactListChanges();
}

void ContactManager::onContactListGroupsRemoved(const QStringList &names)
{
    Q_ASSERT(mPriv->fallbackContactList == false);

    if (!mPriv->contactListGroupPropertiesReceived) {
        return;
    }

    mPriv->contactListGroupsRemovedQueue.enqueue(names);
    mPriv->contactListChangesQueue.enqueue(&Private::processContactListGroupsRemoved);
    mPriv->processContactListChanges();
}

void ContactManager::onStoredChannelMembersChangedFallback(
        const Contacts &groupMembersAdded,
        const Contacts &groupLocalPendingMembersAdded,
        const Contacts &groupRemotePendingMembersAdded,
        const Contacts &groupMembersRemoved,
        const Channel::GroupMemberChangeDetails &details)
{
    if (!groupLocalPendingMembersAdded.isEmpty()) {
        warning() << "Found local pending contacts on stored list";
    }

    if (!groupRemotePendingMembersAdded.isEmpty()) {
        warning() << "Found remote pending contacts on stored list";
    }

    foreach (ContactPtr contact, groupMembersAdded) {
        debug() << "Contact" << contact->id() << "on stored list";
    }

    foreach (ContactPtr contact, groupMembersRemoved) {
        debug() << "Contact" << contact->id() << "removed from stored list";
    }

    // Perform the needed computation for allKnownContactsChanged
    mPriv->computeKnownContactsChangesFallback(groupMembersAdded,
            groupLocalPendingMembersAdded, groupRemotePendingMembersAdded,
            groupMembersRemoved, details);
}

void ContactManager::onSubscribeChannelMembersChangedFallback(
        const Contacts &groupMembersAdded,
        const Contacts &groupLocalPendingMembersAdded,
        const Contacts &groupRemotePendingMembersAdded,
        const Contacts &groupMembersRemoved,
        const Channel::GroupMemberChangeDetails &details)
{
    if (!groupLocalPendingMembersAdded.isEmpty()) {
        warning() << "Found local pending contacts on subscribe list";
    }

    foreach (ContactPtr contact, groupMembersAdded) {
        debug() << "Contact" << contact->id() << "on subscribe list";
        contact->setSubscriptionState(SubscriptionStateYes);
    }

    foreach (ContactPtr contact, groupRemotePendingMembersAdded) {
        debug() << "Contact" << contact->id() << "added to subscribe list";
        contact->setSubscriptionState(SubscriptionStateAsk);
    }

    foreach (ContactPtr contact, groupMembersRemoved) {
        debug() << "Contact" << contact->id() << "removed from subscribe list";
        contact->setSubscriptionState(SubscriptionStateNo);
    }

    // Perform the needed computation for allKnownContactsChanged
    mPriv->computeKnownContactsChangesFallback(groupMembersAdded,
            groupLocalPendingMembersAdded, groupRemotePendingMembersAdded,
            groupMembersRemoved, details);
}

void ContactManager::onPublishChannelMembersChangedFallback(
        const Contacts &groupMembersAdded,
        const Contacts &groupLocalPendingMembersAdded,
        const Contacts &groupRemotePendingMembersAdded,
        const Contacts &groupMembersRemoved,
        const Channel::GroupMemberChangeDetails &details)
{
    if (!groupRemotePendingMembersAdded.isEmpty()) {
        warning() << "Found remote pending contacts on publish list";
    }

    foreach (ContactPtr contact, groupMembersAdded) {
        debug() << "Contact" << contact->id() << "on publish list";
        contact->setPublishState(SubscriptionStateYes);
    }

    foreach (ContactPtr contact, groupLocalPendingMembersAdded) {
        debug() << "Contact" << contact->id() << "added to publish list";
        contact->setPublishState(SubscriptionStateAsk, details.message());
    }

    foreach (ContactPtr contact, groupMembersRemoved) {
        debug() << "Contact" << contact->id() << "removed from publish list";
        contact->setPublishState(SubscriptionStateNo);
    }

    if (!groupLocalPendingMembersAdded.isEmpty()) {
        // FIXME (API/ABI break) remove signal with details
        emit presencePublicationRequested(groupLocalPendingMembersAdded,
            details);

        emit presencePublicationRequested(groupLocalPendingMembersAdded,
            details.message());
    }

    // Perform the needed computation for allKnownContactsChanged
    mPriv->computeKnownContactsChangesFallback(groupMembersAdded,
            groupLocalPendingMembersAdded, groupRemotePendingMembersAdded,
            groupMembersRemoved, details);
}

void ContactManager::onDenyChannelMembersChanged(
        const Contacts &groupMembersAdded,
        const Contacts &groupLocalPendingMembersAdded,
        const Contacts &groupRemotePendingMembersAdded,
        const Contacts &groupMembersRemoved,
        const Channel::GroupMemberChangeDetails &details)
{
    if (!groupLocalPendingMembersAdded.isEmpty()) {
        warning() << "Found local pending contacts on deny list";
    }

    if (!groupRemotePendingMembersAdded.isEmpty()) {
        warning() << "Found remote pending contacts on deny list";
    }

    foreach (ContactPtr contact, groupMembersAdded) {
        debug() << "Contact" << contact->id() << "added to deny list";
        contact->setBlocked(true);
    }

    foreach (ContactPtr contact, groupMembersRemoved) {
        debug() << "Contact" << contact->id() << "removed from deny list";
        contact->setBlocked(false);
    }
}

void ContactManager::onContactListGroupMembersChangedFallback(
        const Tp::Contacts &groupMembersAdded,
        const Tp::Contacts &groupLocalPendingMembersAdded,
        const Tp::Contacts &groupRemotePendingMembersAdded,
        const Tp::Contacts &groupMembersRemoved,
        const Tp::Channel::GroupMemberChangeDetails &details)
{
    ChannelPtr contactListGroupChannel = ChannelPtr(
            qobject_cast<Channel*>(sender()));
    QString id = contactListGroupChannel->immutableProperties().value(
            QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetID")).toString();

    foreach (const ContactPtr &contact, groupMembersAdded) {
        contact->setAddedToGroup(id);
    }
    foreach (const ContactPtr &contact, groupMembersRemoved) {
        contact->setRemovedFromGroup(id);
    }

    emit groupMembersChanged(id, groupMembersAdded, groupMembersRemoved, details);
}

void ContactManager::onContactListGroupRemovedFallback(Tp::DBusProxy *proxy,
        const QString &errorName, const QString &errorMessage)
{
    Q_UNUSED(errorName);
    Q_UNUSED(errorMessage);

    // Is it correct to assume that if an user-defined contact list
    // gets invalidated it means it was removed? Spec states that if a
    // user-defined contact list gets closed it was removed, and Channel
    // invalidates itself when it gets closed.
    ChannelPtr contactListGroupChannel = ChannelPtr(qobject_cast<Channel*>(proxy));
    QString id = contactListGroupChannel->immutableProperties().value(
            QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetID")).toString();
    mPriv->contactListGroupChannels.remove(id);
    mPriv->removedContactListGroupChannels.append(contactListGroupChannel);
    disconnect(contactListGroupChannel.data(), 0, 0, 0);
    emit groupRemoved(id);
}

ContactPtr ContactManager::ensureContact(const ReferencedHandles &handle,
        const Features &features, const QVariantMap &attributes)
{
    uint bareHandle = handle[0];
    ContactPtr contact = lookupContactByHandle(bareHandle);

    if (!contact) {
        contact = ContactPtr(new Contact(this, handle, features, attributes));
        mPriv->contacts.insert(bareHandle, contact.data());
    } else {
        contact->augment(features, attributes);
    }

    return contact;
}

void ContactManager::setUseFallbackContactList(bool value)
{
    mPriv->fallbackContactList = value;
}

void ContactManager::setContactListProperties(const QVariantMap &props)
{
    Q_ASSERT(mPriv->fallbackContactList == false);

    mPriv->canChangeContactList = qdbus_cast<uint>(props[QLatin1String("CanChangeContactList")]);
    mPriv->contactListRequestUsesMessage = qdbus_cast<uint>(props[QLatin1String("RequestUsesMessage")]);
}

void ContactManager::setContactListContacts(const ContactAttributesMap &attrsMap)
{
    Q_ASSERT(mPriv->fallbackContactList == false);

    ContactAttributesMap::const_iterator begin = attrsMap.constBegin();
    ContactAttributesMap::const_iterator end = attrsMap.constEnd();
    for (ContactAttributesMap::const_iterator i = begin; i != end; ++i) {
        uint bareHandle = i.key();
        QVariantMap attrs = i.value();

        ContactPtr contact = ensureContact(ReferencedHandles(connection(),
                    HandleTypeContact, UIntList() << bareHandle),
                Features(), attrs);
        mPriv->cachedAllKnownContacts.insert(contact);
    }
}

void ContactManager::updateContactListContacts(const ContactSubscriptionMap &changes,
        const UIntList &removals)
{
    Q_ASSERT(mPriv->fallbackContactList == false);

    mPriv->contactListUpdatesQueue.enqueue(Private::ContactListUpdateInfo(changes, removals));
    mPriv->contactListChangesQueue.enqueue(&Private::processContactListUpdates);
    mPriv->processContactListChanges();
}

void ContactManager::setContactListGroupsProperties(const QVariantMap &props)
{
    Q_ASSERT(mPriv->fallbackContactList == false);
    Q_ASSERT(mPriv->contactListGroupPropertiesReceived == false);

    mPriv->allKnownGroups = qdbus_cast<QStringList>(props[QLatin1String("Groups")]).toSet();
    mPriv->contactListGroupPropertiesReceived = true;
}

void ContactManager::setContactListChannels(
        const QMap<uint, ContactListChannel> &contactListChannels)
{
    if (!mPriv->fallbackContactList) {
        Q_ASSERT(!contactListChannels.contains(ContactListChannel::TypeSubscribe));
        Q_ASSERT(!contactListChannels.contains(ContactListChannel::TypePublish));
        Q_ASSERT(!contactListChannels.contains(ContactListChannel::TypeStored));
    }

    mPriv->contactListChannels = contactListChannels;

    if (mPriv->contactListChannels.contains(ContactListChannel::TypeSubscribe)) {
        mPriv->subscribeChannel = mPriv->contactListChannels[ContactListChannel::TypeSubscribe].channel;
    }

    if (mPriv->contactListChannels.contains(ContactListChannel::TypePublish)) {
        mPriv->publishChannel = mPriv->contactListChannels[ContactListChannel::TypePublish].channel;
    }

    if (mPriv->contactListChannels.contains(ContactListChannel::TypeStored)) {
        mPriv->storedChannel = mPriv->contactListChannels[ContactListChannel::TypeStored].channel;
    }

    if (mPriv->contactListChannels.contains(ContactListChannel::TypeDeny)) {
        mPriv->denyChannel = mPriv->contactListChannels[ContactListChannel::TypeDeny].channel;
    }

    mPriv->updateContactsBlockState();

    if (mPriv->fallbackContactList) {
        mPriv->updateContactsPresenceStateFallback();
        // Refresh the cache for the current known contacts
        mPriv->cachedAllKnownContacts = allKnownContacts();
    }

    uint type;
    ChannelPtr channel;
    const char *method;
    for (QMap<uint, ContactListChannel>::const_iterator i = contactListChannels.constBegin();
            i != contactListChannels.constEnd(); ++i) {
        type = i.key();
        channel = i.value().channel;
        if (!channel) {
            continue;
        }

        if (type == ContactListChannel::TypeStored) {
            method = SLOT(onStoredChannelMembersChangedFallback(
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Channel::GroupMemberChangeDetails));
        }else if (type == ContactListChannel::TypeSubscribe) {
            method = SLOT(onSubscribeChannelMembersChangedFallback(
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Channel::GroupMemberChangeDetails));
        } else if (type == ContactListChannel::TypePublish) {
            method = SLOT(onPublishChannelMembersChangedFallback(
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Channel::GroupMemberChangeDetails));
        } else if (type == ContactListChannel::TypeDeny) {
            method = SLOT(onDenyChannelMembersChanged(
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Channel::GroupMemberChangeDetails));
        } else {
            continue;
        }

        connect(channel.data(),
                SIGNAL(groupMembersChanged(
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Contacts,
                        Tp::Channel::GroupMemberChangeDetails)),
                method);
    }
}

void ContactManager::setContactListGroupChannelsFallback(
        const QList<ChannelPtr> &contactListGroupChannels)
{
    Q_ASSERT(mPriv->fallbackContactList == true);

    Q_ASSERT(mPriv->contactListGroupChannels.isEmpty());

    foreach (const ChannelPtr &contactListGroupChannel, contactListGroupChannels) {
        mPriv->addContactListGroupChannelFallback(contactListGroupChannel);
    }
}

void ContactManager::addContactListGroupChannelFallback(
        const ChannelPtr &contactListGroupChannel)
{
    Q_ASSERT(mPriv->fallbackContactList == true);

    QString id = mPriv->addContactListGroupChannelFallback(contactListGroupChannel);
    emit groupAdded(id);
}

void ContactManager::resetContactListChannels()
{
    mPriv->contactListChannels.clear();
    mPriv->subscribeChannel.reset();
    mPriv->publishChannel.reset();
    mPriv->storedChannel.reset();
    mPriv->denyChannel.reset();
    mPriv->contactListGroupChannels.clear();
    mPriv->removedContactListGroupChannels.clear();
}

QString ContactManager::featureToInterface(const Feature &feature)
{
    if (feature == Contact::FeatureAlias) {
        return TP_QT4_IFACE_CONNECTION_INTERFACE_ALIASING;
    } else if (feature == Contact::FeatureAvatarToken) {
        return TP_QT4_IFACE_CONNECTION_INTERFACE_AVATARS;
    } else if (feature == Contact::FeatureAvatarData) {
        return TP_QT4_IFACE_CONNECTION_INTERFACE_AVATARS;
    } else if (feature == Contact::FeatureSimplePresence) {
        return TP_QT4_IFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE;
    } else if (feature == Contact::FeatureCapabilities) {
        return TP_QT4_IFACE_CONNECTION_INTERFACE_CONTACT_CAPABILITIES;
    } else if (feature == Contact::FeatureLocation) {
        return TP_QT4_IFACE_CONNECTION_INTERFACE_LOCATION;
    } else if (feature == Contact::FeatureInfo) {
        return TP_QT4_IFACE_CONNECTION_INTERFACE_CONTACT_INFO;
    } else if (feature == Contact::FeatureRosterGroups) {
        return TP_QT4_IFACE_CONNECTION_INTERFACE_CONTACT_GROUPS;
    } else {
        warning() << "ContactManager doesn't know which interface corresponds to feature"
            << feature;
        return QString();
    }
}

QString ContactManager::ContactListChannel::identifierForType(Type type)
{
    static QString identifiers[LastType] = {
        QLatin1String("subscribe"),
        QLatin1String("publish"),
        QLatin1String("stored"),
        QLatin1String("deny"),
    };
    return identifiers[type];
}

uint ContactManager::ContactListChannel::typeForIdentifier(const QString &identifier)
{
    static QHash<QString, uint> types;
    if (types.isEmpty()) {
        types.insert(QLatin1String("subscribe"), TypeSubscribe);
        types.insert(QLatin1String("publish"), TypePublish);
        types.insert(QLatin1String("stored"), TypeStored);
        types.insert(QLatin1String("deny"), TypeDeny);
    }
    if (types.contains(identifier)) {
        return types[identifier];
    }
    return (uint) -1;
}

/**
 * \fn void ContactManager::presencePublicationRequested(const Tp::Contacts &contacts,
 *          const QString &message);
 *
 * This signal is emitted whenever some contacts request for presence publication.
 *
 * \param contacts A set of contacts which requested presence publication.
 * \param message An optional message that was sent by the contacts asking to receive the local
 *                user's presence.
 */

/**
 * \fn void ContactManager::presencePublicationRequested(const Tp::Contacts &contacts,
 *          const Tp::Channel::GroupMemberChangeDetails &details);
 *
 * \deprecated Use presencePublicationRequested(const Tp::Contacts &contact, const QString &message)
 *             instead.
 */

/**
 * \fn void ContactManager::groupMembersChanged(const QString &group,
 *          const Tp::Contacts &groupMembersAdded,
 *          const Tp::Contacts &groupMembersRemoved,
 *          const Tp::Channel::GroupMemberChangeDetails &details);
 *
 * This signal is emitted whenever some contacts got removed or added from
 * a group.
 *
 * \param group The name of the group that changed.
 * \param groupMembersAdded A set of contacts which were added to the group \a group.
 * \param groupMembersRemoved A set of contacts which were removed from the group \a group.
 * \param details The change details.
 */

/**
 * \fn void ContactManager::allKnownContactsChanged(const Tp::Contacts &contactsAdded,
 *          const Tp::Contacts &contactsRemoved,
 *          const Tp::Channel::GroupMemberChangeDetails &details);
 *
 * This signal is emitted whenever some contacts got removed or added from
 * ContactManager's known contact list. It is useful for monitoring which contacts
 * are currently known by ContactManager.
 *
 * \param contactsAdded A set of contacts which were added to the known contact list.
 * \param contactsRemoved A set of contacts which were removed from the known contact list.
 * \param details The change details.
 *
 * \note Please note that, in some protocols, this signal could stream newly added contacts
 *       with both presence subscription and publication state set to No. Be sure to watch
 *       over publication and/or subscription state changes if that is the case.
 */

PendingContactManagerRemoveContactListGroup::PendingContactManagerRemoveContactListGroup(
        const ChannelPtr &channel)
    : PendingOperation(channel)
{
    Contacts contacts = channel->groupContacts();
    if (!contacts.isEmpty()) {
        connect(channel->groupRemoveContacts(contacts.toList()),
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(onContactsRemoved(Tp::PendingOperation*)));
    } else {
        connect(channel->requestClose(),
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(onChannelClosed(Tp::PendingOperation*)));
    }
}

void PendingContactManagerRemoveContactListGroup::onContactsRemoved(PendingOperation *op)
{
    if (op->isError()) {
        setFinishedWithError(op->errorName(), op->errorMessage());
        return;
    }

    // Let's ignore possible errors and try to remove the group
    ChannelPtr channel = ChannelPtr(qobject_cast<Channel*>((Channel *) object().data()));
    connect(channel->requestClose(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onChannelClosed(Tp::PendingOperation*)));
}

void PendingContactManagerRemoveContactListGroup::onChannelClosed(PendingOperation *op)
{
    if (!op->isError()) {
        setFinished();
    } else {
        setFinishedWithError(op->errorName(), op->errorMessage());
    }
}

void ContactManager::connectNotify(const char *signalName)
{
    if (qstrcmp(signalName, SIGNAL(presencePublicationRequested(Tp::Contacts,Tp::Channel::GroupMemberChangeDetails))) == 0) {
        warning() << "Connecting to deprecated signal presencePublicationRequested(Tp::Contacts,Tp::Channel::GroupMemberChangeDetails)";
    }
}

} // Tp