summaryrefslogtreecommitdiff
path: root/src/mcd-connection.c
blob: da2ae300931c97197c23a65d7ee8657133e801d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 8 -*- */
/*
 * This file is part of mission-control
 *
 * Copyright (C) 2007 Nokia Corporation. 
 *
 * Contact: Naba Kumar  <naba.kumar@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * 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
 *
 */

/**
 * SECTION:mcd-connection
 * @title: McdConnection
 * @short_description: Connection class representing Telepathy connection class
 * @see_also: 
 * @stability: Unstable
 * @include: mcd-connection.h
 * 
 * FIXME
 */

#include <string.h>
#include <sys/types.h>
#include <sched.h>

#include <glib.h>
#include <glib/gi18n.h>
#include <glib/gstdio.h>

#include <string.h>
#include <stdlib.h>
#include <dlfcn.h>

#include <libmissioncontrol/mc-manager.h>
#include <libmissioncontrol/mc-account.h>
#include <libmissioncontrol/mc-protocol.h>
#include <libmissioncontrol/mc-profile.h>
#include <libtelepathy/tp-connmgr.h>
#include <libtelepathy/tp-interfaces.h>
#include <libtelepathy/tp-constants.h>
#include <libtelepathy/tp-chan.h>
#include <libtelepathy/tp-conn.h>
#include <libtelepathy/tp-conn-gen.h>
#include <libtelepathy/tp-conn-iface-presence-gen.h>
#include <libtelepathy/tp-conn-iface-capabilities-gen.h>
#include <libtelepathy/tp-conn-iface-avatars-gen.h>
#include <libtelepathy/tp-conn-iface-aliasing-gen.h>
#include <libtelepathy/tp-helpers.h>

#include "mcd-connection.h"
#include "mcd-channel.h"
#include "mcd-provisioning-factory.h"

#define MAX_REF_PRESENCE 4

#define MCD_CONNECTION_PRIV(mcdconn) (G_TYPE_INSTANCE_GET_PRIVATE ((mcdconn), \
				      MCD_TYPE_CONNECTION, \
				      McdConnectionPrivate))

G_DEFINE_TYPE (McdConnection, mcd_connection, MCD_TYPE_OPERATION);

/* Private */
typedef struct
{
    /* DBUS connection */
    DBusGConnection *dbus_connection;

    /* DBus bus name */
    gchar *bus_name;

    /* Presence frame */
    McdPresenceFrame *presence_frame;

    /* Channel dispatcher */
    McdDispatcher *dispatcher;

    McdProvisioning *provisioning;

    /* Account */
    McAccount *account;

    /* Associated profile */
    /* McProfile *profile; */

    /* Telepathy connection manager */
    TpConnMgr *tp_conn_mgr;

    /* Telepathy connection */
    TpConn *tp_conn;
    guint self_handle;

    /* Presence proxy */
    DBusGProxy *presence_proxy;

    DBusGProxy *avatars_proxy;
    DBusGProxy *alias_proxy;

    /* Capabilities proxy */
    DBusGProxy *capabilities_proxy;
    
    /* Capabilities timer */
    guint capabilities_timer;

    guint reconnect_timer; 	/* timer for reconnection */
    guint reconnect_interval;
    gboolean reconnection_requested;

    /* Supported presences */
    GArray *recognized_presence_info_array;
    struct presence_info *presence_to_set[LAST_MC_PRESENCE - 1];

    /* List of pending channels which has been requested to telepathy,
     * but telepathy hasn't yet responded with the channel object
     */
    GList *pending_channels;
    
    TelepathyConnectionStatusReason abort_reason;
    gboolean got_capabilities;

    gchar *alias;

    gboolean is_disposed;
    
} McdConnectionPrivate;

struct presence_info
{
    gchar *presence_str;
    gboolean allow_message;
};

struct param_data
{
    GSList *pr_params;
    GHashTable *dest;
};

typedef struct {
    guint handle_type;
    guint handle;
    const gchar *type;
    McdChannel *channel;
} McdPendingChannel;

enum
{
    PROP_0,
    PROP_DBUS_CONNECTION,
    PROP_BUS_NAME,
    PROP_TP_MANAGER,
    PROP_TP_CONNECTION,
    PROP_ACCOUNT,
    PROP_PRESENCE_FRAME,
    PROP_DISPATCHER,
};

/* This table lists the Telepathy well-known statuses and the corresponding
 * McPresence values; the order in which the items appear is only important for
 * those statuses which map to the same McPresence value: for them, the first
 * ones will be preferred. */
static const struct _presence_mapping {
    gchar *presence_str;
    McPresence mc_presence;
} presence_mapping[] = {
    { "offline", MC_PRESENCE_OFFLINE },
    { "available", MC_PRESENCE_AVAILABLE },
    { "away", MC_PRESENCE_AWAY },
    { "xa", MC_PRESENCE_EXTENDED_AWAY },
    { "hidden", MC_PRESENCE_HIDDEN },
    { "dnd", MC_PRESENCE_DO_NOT_DISTURB },
    { "brb", MC_PRESENCE_AWAY },
    { "busy", MC_PRESENCE_DO_NOT_DISTURB },
    { NULL, 0 },
};

static const McPresence fallback_presence
    [LAST_MC_PRESENCE - 1][MAX_REF_PRESENCE] = {
    { 0 },	/* MC_PRESENCE_OFFLINE */
    { 0 },	/* MC_PRESENCE_AVAILABLE */
    { MC_PRESENCE_AVAILABLE, 0 },	/* MC_PRESENCE_AWAY */
    { MC_PRESENCE_AWAY, MC_PRESENCE_AVAILABLE, 0 },	/* MC_PRESENCE_EXTENDED_AWAY */
    { MC_PRESENCE_DO_NOT_DISTURB, MC_PRESENCE_EXTENDED_AWAY, MC_PRESENCE_AVAILABLE, 0 }, /* MC_PRESENCE_HIDDEN */
    { 0 }	/* MC_PRESENCE_DO_NOT_DISTURB */
};

struct request_id {
    guint requestor_serial;
    const gchar *requestor_client_id;
};

struct capabilities_wait_data {
    GError *error; /* error originally received when channel request failed */
    McdChannel *channel;
    McdConnectionPrivate *priv;
};

static void mcd_async_request_chan_callback (DBusGProxy *proxy,
					     gchar *channel_path,
					     GError *error,
					     gpointer user_data);
static GError * map_tp_error_to_mc_error (McdChannel *channel, GError *tp_error);
static void _mcd_connection_setup (McdConnection * connection);
static void _mcd_connection_release_tp_connection (McdConnection *connection);
static void request_avatar_cb (DBusGProxy *, GArray *, char *, GError *,
			       gpointer);

static McPresence presence_str_to_enum (const gchar *presence_str)
{
    const struct _presence_mapping *mapping;
    for (mapping = presence_mapping; mapping->presence_str; mapping++)
	if (strcmp (presence_str, mapping->presence_str) == 0)
	    return mapping->mc_presence;
    return MC_PRESENCE_UNSET;
}

/* Free dynamic members and presence_info itself */
static void
_mcd_connection_free_presence_info (McdConnection * conn)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (conn);

    if (priv->recognized_presence_info_array != NULL)
    {
	struct presence_info *pi;
	gint i;

	for (i = 0; i < priv->recognized_presence_info_array->len; i++)
	{
	    pi = &g_array_index (priv->recognized_presence_info_array,
				 struct presence_info, i);
	    g_free (pi->presence_str);
	}
	g_array_free (priv->recognized_presence_info_array, TRUE);
	priv->recognized_presence_info_array = NULL;
    }
}

/* Fill empty presence_to_set elements with fallback presence values */
static void
_mcd_connection_set_fallback_presences (McdConnection * connection, gint i)
{
    gint j;
    McdConnectionPrivate *priv;

    g_return_if_fail (MCD_IS_CONNECTION (connection));

    priv = MCD_CONNECTION_PRIV (connection);

    for (j = 0; j < MAX_REF_PRESENCE; j++)
    {
	struct presence_info *presence;

	if (fallback_presence[i][j] == 0) break;
	presence = priv->presence_to_set[fallback_presence[i][j] - 1];
	if (presence != NULL)
	{
	    priv->presence_to_set[i] = presence;
	    g_debug ("Fallback for McPresence %d set to %s",
		     i + 1, presence->presence_str);
	    return;
	}
    }
}

/* Used for initializing recognized_presence_info_array. */
static void
recognize_presence (gpointer key, gpointer value, gpointer user_data)
{
    guint telepathy_enum;
    GHashTable *ht;
    struct presence_info pi;
    GValueArray *status;
    McdConnectionPrivate *priv = (McdConnectionPrivate *) user_data;
    gint j;

    status = (GValueArray *) value;

    /* Pull out the arguments of Telepathy GetStatuses */
    ht = (GHashTable *) g_value_get_boxed (g_value_array_get_nth (status, 3));
    pi.allow_message = g_hash_table_lookup (ht, "message") ? TRUE : FALSE;

    /* Look up which MC_PRESENCE this presence string corresponds */
    pi.presence_str = g_strdup ((const gchar *) key);

    j = presence_str_to_enum (pi.presence_str);
    if (j == MC_PRESENCE_UNSET)
    {
	/* Didn't find match by comparing strings so map using the telepathy enum. */
	telepathy_enum = g_value_get_uint (g_value_array_get_nth (status, 0));
	switch (telepathy_enum)
	{
	case TP_CONN_PRESENCE_TYPE_OFFLINE:
	    j = MC_PRESENCE_OFFLINE;
	    break;
	case TP_CONN_PRESENCE_TYPE_AVAILABLE:
	    j = MC_PRESENCE_AVAILABLE;
	    break;
	case TP_CONN_PRESENCE_TYPE_AWAY:
	    j = MC_PRESENCE_AWAY;
	    break;
	case TP_CONN_PRESENCE_TYPE_EXTENDED_AWAY:
	    j = MC_PRESENCE_EXTENDED_AWAY;
	    break;
	case TP_CONN_PRESENCE_TYPE_HIDDEN:
	    j = MC_PRESENCE_HIDDEN;
	    break;
	default:
	    g_debug ("Unknown Telepathy presence type. Presence %s "
		     "with Telepathy enum %d ignored.", pi.presence_str,
		     telepathy_enum);
	    g_free (pi.presence_str);
	    return;
	    break;
	}
    }
    g_array_append_val (priv->recognized_presence_info_array, pi);
}

static void
enable_well_known_presences (McdConnectionPrivate *priv)
{
    const struct _presence_mapping *mapping;
    struct presence_info *pi;

    /* Loop the presence_mappinges; if one of the basic McPresences is not set,
     * check if an mapping is supported by the connection and, if so, use it */
    for (mapping = presence_mapping; mapping->presence_str; mapping++)
    {
	if (priv->presence_to_set[mapping->mc_presence - 1] == NULL)
	{
	    gint i;
	    /* see if this presence is supported by the connection */
	    for (i = 0; i < priv->recognized_presence_info_array->len; i++)
	    {
		pi = &g_array_index (priv->recognized_presence_info_array,
				     struct presence_info, i);
		if (strcmp (pi->presence_str, mapping->presence_str) == 0)
		{
		    g_debug ("Using %s status for McPresence %d",
			     mapping->presence_str, mapping->mc_presence);
		    /* Presence values used when setting the presence status */
		    priv->presence_to_set[mapping->mc_presence - 1] = pi;
		    break;
		}
	    }
	}
    }
}

static void
_mcd_connection_set_presence (McdConnection * connection,
			      McPresence presence,
			      const gchar * presence_message)
{
    const gchar *presence_str;
    GHashTable *presence_ht;
    GHashTable *params_ht;
    struct presence_info *supported_presence_info;
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    GError *error = NULL;
    GValue msg_gval = { 0, };

    if (!priv->tp_conn)
    {
	_mcd_connection_setup (connection);
	return;
    }
    g_return_if_fail (TELEPATHY_IS_CONN (priv->tp_conn));
    g_return_if_fail (priv->bus_name != NULL);

    if (priv->presence_proxy == NULL)
    {
	GHashTable *status_hash;
	guint i;
	GError *error = NULL;

	/* Gets a reference to it */
	priv->presence_proxy =
	    tp_conn_get_interface (priv->tp_conn,
				   TELEPATHY_CONN_IFACE_PRESENCE_QUARK);
	if (priv->presence_proxy == NULL)
	{
	    g_warning ("%s: Account %s has no presence interface", G_STRFUNC,
		       mc_account_get_unique_name (priv->account));
	    return;
	}
	g_object_add_weak_pointer (G_OBJECT (priv->presence_proxy), (gpointer)&priv->presence_proxy);

	if (tp_conn_iface_presence_get_statuses (priv->presence_proxy,
						 &status_hash, &error) == FALSE)
	{
	    g_warning ("%s: Get statuses failed for account %s: %s", G_STRFUNC,
		       mc_account_get_unique_name (priv->account),
		       error->message);
	    g_error_free (error);
	    return;
	}

	/* Everything went well so pack the available presences into
	 * connection info
	 */
	/* Initialize presence info array and pointers for setting presences */
	for (i = 0; i < LAST_MC_PRESENCE - 1; i++)
	    priv->presence_to_set[i] = NULL;
	priv->recognized_presence_info_array =
	    g_array_new (FALSE, FALSE, sizeof (struct presence_info));
	g_hash_table_foreach (status_hash, recognize_presence, priv);
	g_hash_table_destroy (status_hash);

	enable_well_known_presences (priv);

	/* Set the fallback presence values */
	for (i = 0; i < LAST_MC_PRESENCE - 1; i++)
	{
	    if (priv->presence_to_set[i] == NULL)
		_mcd_connection_set_fallback_presences (connection, i);
	}
    }

    supported_presence_info = priv->presence_to_set[presence - 1];

    if (supported_presence_info == NULL)
    {
	g_debug ("No matching supported presence found. "
		 "Account presence has not been changed.");
	return;
    }

    presence_str = g_strdup (supported_presence_info->presence_str);
    presence = presence_str_to_enum (supported_presence_info->presence_str);

    /* Add the presence by libtelepathy */
    /* FIXME: what should we do when this is NULL? */
    if (presence_str != NULL)
    {
	presence_ht = g_hash_table_new_full (g_str_hash, g_str_equal,
					     g_free, NULL);
	params_ht = g_hash_table_new (g_str_hash, g_str_equal);

	/* 
	 * Note that we silently ignore the message if Connection Manager
	 * doesn't support it for this presence state!
	 */
	if (supported_presence_info->allow_message && presence_message)
	{
	    g_value_init (&msg_gval, G_TYPE_STRING);
	    g_value_set_string (&msg_gval, presence_message);
	    g_hash_table_insert (params_ht, "message", &msg_gval);
	}

	g_hash_table_insert (presence_ht, (gpointer) presence_str, params_ht);

	if (tp_conn_iface_presence_set_status (priv->presence_proxy,
					       presence_ht, &error) == FALSE)
	{
	    g_warning ("%s: Setting presence of %s to %s (%d) failed: %s",
		       G_STRFUNC, mc_account_get_unique_name (priv->account),
		       presence_str, presence, error->message);
	}
	else
	{
	    mcd_presence_frame_set_account_presence (priv->presence_frame,
						     priv->account,
						     presence,
						     presence_message);
	}

	if (supported_presence_info->allow_message && presence_message)
	    g_value_unset (&msg_gval);

	g_hash_table_destroy (presence_ht);
	g_hash_table_destroy (params_ht);
    }
}


/* This handler should update the presence of the tp_connection. 
 * Note, that the only presence transition not served by this function 
 * is getting to non-offline state since when presence is offline this object 
 * does not exist.
 *
 * So, here we just submit the request to the tp_connection object. The return off 
 * the operation is handled by (yet to be written) handler
 */
static void
on_presence_requested (McdPresenceFrame * presence_frame,
		       McPresence presence,
		       const gchar * presence_message, gpointer user_data)
{
    McdConnection *connection = MCD_CONNECTION (user_data);
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    GError *error = NULL;

    g_debug ("Presence requested: %d", presence);
    if (presence == TP_CONN_PRESENCE_TYPE_OFFLINE ||
	presence == TP_CONN_PRESENCE_TYPE_UNSET)
    {
	/* Connection Proxy */
	priv->abort_reason = TP_CONN_STATUS_REASON_REQUESTED;
	mcd_mission_disconnect (MCD_MISSION (connection));
	if (priv->tp_conn)
	    tp_conn_disconnect (DBUS_G_PROXY (priv->tp_conn), &error);
    }
    else
    {
	_mcd_connection_set_presence (connection, presence, presence_message);
    }
}

static void
_mcd_connection_new_channel_cb (DBusGProxy * tp_conn_proxy,
				const gchar * chan_obj_path,
				const gchar * chan_type,
				guint handle_type,
				guint handle,
				gboolean suppress_handler,
				McdConnection * connection)
{
    TpChan *tp_chan;
    McdChannel *channel;
    McdConnectionPrivate *priv;
    
    priv = MCD_CONNECTION_PRIV (connection);

    /* ignore all our own requests (they have always suppress_handler = 1) as
     * well as other requests for which our intervention has not been requested
     * */
    if (suppress_handler) return;
    
    /* g_return_if_fail (TELEPATHY_IS_CHAN (tp_chan)); */
    tp_chan = tp_chan_new (priv->dbus_connection, priv->bus_name,
			   chan_obj_path, chan_type, handle_type, handle);

    /* It's an incoming channel, so we create a new McdChannel for it */
    channel = mcd_channel_new (tp_chan,
			       chan_obj_path,
			       chan_type,
			       handle,
			       handle_type,
			       FALSE, /* incoming */
			       0, 0); /* There is no requestor, obviously */
    
    mcd_operation_take_mission (MCD_OPERATION (connection),
				MCD_MISSION (channel));

    /* Channel about to be dispatched */
    mcd_channel_set_status (channel, MCD_CHANNEL_DISPATCHING);
    
    /* Dispatch the incoming channel */
    mcd_dispatcher_send (priv->dispatcher, channel);
    
    g_object_unref (tp_chan);
}

static void
_foreach_channel_remove (McdMission * mission, McdOperation * operation)
{
    g_assert (MCD_IS_MISSION (mission));
    g_assert (MCD_IS_OPERATION (operation));

    mcd_operation_remove_mission (operation, mission);
}

static void
on_capabilities_changed (DBusGProxy *tp_conn_proxy,
			 GPtrArray *caps, McdChannel *channel)
{
    McdConnection *connection;
    McdConnectionPrivate *priv;
    gboolean found = FALSE;
    GType type;
    gchar *chan_type;
    guint chan_handle, chan_handle_type;
    DBusGProxyCall *call;
    gint i;

    connection = g_object_get_data (G_OBJECT (channel), "temporary_connection");
    priv = MCD_CONNECTION_PRIV (connection);

    g_debug ("%s: got capabilities for channel %p handle %d, type %s",
	     G_STRFUNC, channel, mcd_channel_get_handle (channel), mcd_channel_get_channel_type (channel));
    type = dbus_g_type_get_struct ("GValueArray", G_TYPE_UINT, G_TYPE_STRING,
				   G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT,
				   G_TYPE_UINT, G_TYPE_INVALID);
    for (i = 0; i < caps->len; i++)
    {
	GValue cap = { 0 };

	g_value_init (&cap, type);
	g_value_set_static_boxed (&cap, g_ptr_array_index(caps, i));
	dbus_g_type_struct_get (&cap, 0, &chan_handle, 1, &chan_type, G_MAXUINT);
	if (chan_handle == mcd_channel_get_handle (channel) &&
	    strcmp (chan_type, mcd_channel_get_channel_type (channel)) == 0)
	{
	    found = TRUE;
	    break;
	}
	g_free (chan_type);
    }

    if (!found) return;
    /* Return also if the "tp_chan_call" data is set (which means that a
     * request for this channel has already been made) */
    if (g_object_get_data (G_OBJECT (channel), "tp_chan_call") != NULL)
	goto done;
    chan_handle_type = mcd_channel_get_handle_type (channel);
    g_debug ("%s: requesting channel again (type = %s, handle_type = %u, handle = %u)",
	     G_STRFUNC, chan_type, chan_handle_type, chan_handle);
    call = tp_conn_request_channel_async(DBUS_G_PROXY(priv->tp_conn),
					 chan_type,
					 chan_handle_type,
					 chan_handle, TRUE,
					 mcd_async_request_chan_callback,
					 channel);
    g_object_set_data (G_OBJECT (channel), "tp_chan_call", call);
done:
    g_free (chan_type);
}

static gboolean
on_channel_capabilities_timeout (McdChannel *channel,
				 McdConnection *connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    struct capabilities_wait_data *cwd;
    GError *mc_error;

    cwd = g_object_get_data (G_OBJECT (channel), "error_on_creation");
    if (!cwd) return FALSE;

    /* We reach this point if this channel was waiting for capabilities; we
     * abort it and return the original error */
    g_debug ("%s: channel %p timed out, returning error!", G_STRFUNC, channel);

    mc_error = map_tp_error_to_mc_error (channel, cwd->error);
    g_signal_emit_by_name (G_OBJECT(priv->dispatcher), "dispatch-failed",
			   channel, mc_error);
    g_error_free (mc_error);
    g_object_set_data (G_OBJECT (channel), "error_on_creation", NULL);

    /* No abort on channel, because we are the only one holding the only
     * reference to this temporary channel.
     */
    return TRUE;
}

static inline void
pending_channel_free (McdPendingChannel *pc)
{
    g_object_unref (pc->channel);
    g_free (pc);
}

static gboolean
on_capabilities_timeout (McdConnection *connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    GList *list, *list_curr;

    g_debug ("%s: got_capabilities is %d", G_STRFUNC, priv->got_capabilities);
    priv->got_capabilities = TRUE;
    list = priv->pending_channels;
    while (list)
    {
	McdPendingChannel *pc = list->data;

	list_curr = list;
	list = list->next;
	if (on_channel_capabilities_timeout (pc->channel, connection))
	{
	    pending_channel_free (pc);
	    priv->pending_channels =
	       	g_list_delete_link (priv->pending_channels, list_curr);
	}
    }
    priv->capabilities_timer = 0;
    return FALSE;
}

static void
_mcd_connection_setup_capabilities (McdConnection *connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    GPtrArray *capabilities;
    GError *error = NULL;
    const gchar *remove = NULL;
    McProfile *profile;
    const gchar *protocol_name;
    GType type;
    gint i;

    priv->capabilities_proxy = tp_conn_get_interface (priv->tp_conn,
				    TELEPATHY_CONN_IFACE_CAPABILITIES_QUARK);
    if (!priv->capabilities_proxy)
    {
	g_debug ("%s: connection does not support capabilities interface", G_STRFUNC);
	priv->got_capabilities = TRUE;
	return;
    }
    g_object_add_weak_pointer (G_OBJECT (priv->capabilities_proxy), (gpointer)&priv->capabilities_proxy);
    profile = mc_account_get_profile (priv->account);
    protocol_name = mc_profile_get_protocol_name (profile);
    capabilities = mcd_dispatcher_get_channel_capabilities (priv->dispatcher,
							    protocol_name);
    g_object_unref (profile);
    g_debug ("%s: advertising capabilities", G_STRFUNC);
    tp_conn_iface_capabilities_advertise_capabilities (priv->capabilities_proxy,
						       capabilities,
						       &remove, NULL,
						       &error);
    if (error)
    {
	g_warning ("%s: AdvertiseCapabilities failed: %s", G_STRFUNC, error->message);
	g_error_free(error);
    }
    
    if (priv->capabilities_timer)
    {
	g_warning ("This connection still has dangling capabilities timer on");
	g_source_remove (priv->capabilities_timer);
    }
    priv->capabilities_timer =
	g_timeout_add (1000 * 10, (GSourceFunc)on_capabilities_timeout, connection);

    /* free the connection capabilities */
    type = dbus_g_type_get_struct ("GValueArray", G_TYPE_STRING,
				   G_TYPE_UINT, G_TYPE_INVALID);
    for (i = 0; i < capabilities->len; i++)
	g_boxed_free (type, g_ptr_array_index (capabilities, i));
    g_ptr_array_free (capabilities, TRUE);
}

static void
_mcd_connection_get_self_handle (McdConnectionPrivate *priv)
{
    GError *error = NULL;
    tp_conn_get_self_handle (DBUS_G_PROXY (priv->tp_conn),
			     &priv->self_handle, &error);
    if (error)
    {
	g_warning ("%s: tp_conn_get_self_handle failed: %s",
		   G_STRFUNC, error->message);
	g_error_free (error);
    }
}

static void
_mcd_connection_get_normalized_name (McdConnectionPrivate *priv)
{
    GArray *handles;
    gchar **names = NULL;
    GError *error = NULL;

    handles = g_array_sized_new (FALSE, FALSE, sizeof (guint), 1);
    g_array_append_val (handles, priv->self_handle);
    tp_conn_inspect_handles (DBUS_G_PROXY (priv->tp_conn),
			     TP_CONN_HANDLE_TYPE_CONTACT, handles,
			     &names, &error);
    g_array_free (handles, TRUE); 
    if (error)
    {
	g_warning ("%s: tp_conn_inspect_handles failed: %s",
		   G_STRFUNC, error->message);
	g_error_free (error);
	return;
    }
    if (names)
    {
	g_return_if_fail (names[0] != 0);
	mc_account_set_normalized_name (priv->account, names[0]);
	g_strfreev (names);
    }
}

static void
set_avatar_cb (DBusGProxy *proxy, char *token, GError *error, gpointer userdata)
{
    McdConnectionPrivate *priv = (McdConnectionPrivate *)userdata;
    if (error)
    {
	g_warning ("%s: error: %s", G_STRFUNC, error->message);
	g_error_free (error);
	return;
    }
    g_debug ("%s: received token: %s", G_STRFUNC, token);
    mc_account_set_avatar_token (priv->account, token);
    g_free (token);
}

static void
clear_avatar_cb (DBusGProxy *proxy, GError *error, gpointer userdata)
{
    gchar *filename = userdata;
    if (!error)
    {
	g_debug ("%s: Clear avatar succeeded, removing %s", G_STRFUNC, filename);
	g_remove (filename);
    }
    else
    {
	g_warning ("%s: error: %s", G_STRFUNC, error->message);
	g_error_free (error);
    }
    g_free (filename);
}

static gboolean
on_avatar_updated (DBusGProxy *proxy, guint contact_id, const gchar *token,
		   gpointer userdata)
{
    McdConnectionPrivate *priv = (McdConnectionPrivate *)userdata;
    gboolean changed = FALSE;
    gchar *prev_token;

#ifndef NO_AVATAR_UPDATED
    if (contact_id != priv->self_handle) return FALSE;
#endif
    g_debug ("%s: contact %d, token: %s", G_STRFUNC, contact_id, token);
    if (!mc_account_get_avatar (priv->account, NULL, NULL, &prev_token))
	return FALSE;

    if (!prev_token || strcmp (token, prev_token) != 0)
    {
	g_debug ("%s: avatar has changed", G_STRFUNC);
	/* the avatar has changed, let's retrieve the new one */
	tp_conn_iface_avatars_request_avatar_async (proxy, contact_id,
						request_avatar_cb,
						priv);
	mc_account_set_avatar_token (priv->account, token);
	changed = TRUE;
    }
    g_free (prev_token);
    return changed;
}

static void
_mcd_connection_set_avatar (McdConnectionPrivate *priv, gchar *filename,
			    gchar *mime_type)
{
    GError *error = NULL;
    gchar *data = NULL;
    size_t length;

    if (filename == NULL || !g_file_test (filename, G_FILE_TEST_EXISTS))
    {
	return;
    }

    if (g_file_get_contents (filename, &data, &length, &error))
    {
	if (length > 0 && length < G_MAXUINT)
	{
	    GArray avatar;
	    avatar.data = data;
	    avatar.len = (guint)length;
	    tp_conn_iface_avatars_set_avatar_async (priv->avatars_proxy,
						    &avatar, mime_type, set_avatar_cb, priv);
	}
	else
	    tp_conn_iface_avatars_clear_avatar_async(priv->avatars_proxy,
						     clear_avatar_cb, g_strdup (filename));

    }
    else
    {
	g_debug ("%s: error reading %s: %s", G_STRFUNC, filename,
		 error->message);
	g_error_free (error);
    }
    g_free(data);
}

static void
request_tokens_cb (DBusGProxy *proxy, GHashTable *tokens,
		   GError *error, gpointer user_data)
{
    McdConnectionPrivate *priv = (McdConnectionPrivate *)user_data;
    const gchar *token;
    gchar *filename, *mime_type;

    if (error)
    {
	g_warning ("%s: error: %s", G_STRFUNC, error->message);
	g_error_free (error);
	return;
    }

    token = g_hash_table_lookup (tokens, GUINT_TO_POINTER (priv->self_handle));
    if (token)
	return;

    if (!mc_account_get_avatar (priv->account, &filename, &mime_type, NULL))
    {
	g_debug ("%s: mc_account_get_avatar() returned FALSE", G_STRFUNC);
	return;
    }

    g_debug ("No avatar set, setting our own");
    _mcd_connection_set_avatar (priv, filename, mime_type);

    g_free (filename);
    g_free (mime_type);
}

static void
_mcd_connection_setup_avatar (McdConnectionPrivate *priv)
{
    gchar *filename, *mime_type, *token;

    priv->avatars_proxy = tp_conn_get_interface (priv->tp_conn,
				    TELEPATHY_CONN_IFACE_AVATARS_QUARK);
    if (!priv->avatars_proxy)
    {
	g_debug ("%s: connection does not support avatar interface", G_STRFUNC);
	return;
    }
    g_object_ref (priv->avatars_proxy);
#ifndef NO_AVATAR_UPDATED
    dbus_g_proxy_connect_signal (priv->avatars_proxy,
				 "AvatarUpdated",
				 G_CALLBACK (on_avatar_updated),
				 priv, NULL);
#endif
    if (!mc_account_get_avatar (priv->account, &filename, &mime_type, &token))
    {
	g_debug ("%s: mc_account_get_avatar() returned FALSE", G_STRFUNC);
	return;
    }

    if (filename)
    {
	if (!token)
	    _mcd_connection_set_avatar (priv, filename, mime_type);
	else
	{
	    GArray handles;

	    /* Set the avatar only if no other one was set */
	    handles.len = 1;
	    handles.data = (gchar *)&priv->self_handle;
	    tp_conn_iface_avatars_get_known_avatar_tokens_async (priv->avatars_proxy,
								 &handles,
								 request_tokens_cb,
								 priv);
	}
    }
    g_free (filename);
    g_free (mime_type);
    g_free (token);
}

static void
on_aliases_changed (DBusGProxy *tp_conn_proxy, GPtrArray *aliases,
		    McdConnectionPrivate *priv)
{
    GType type;
    gchar *alias;
    guint contact;
    gint i;

    g_debug ("%s called", G_STRFUNC);
    type = dbus_g_type_get_struct ("GValueArray", G_TYPE_UINT, G_TYPE_STRING,
				   G_TYPE_INVALID);
    for (i = 0; i < aliases->len; i++)
    {
	GValue data = { 0 };

	g_value_init (&data, type);
	g_value_set_static_boxed (&data, g_ptr_array_index(aliases, i));
	dbus_g_type_struct_get (&data, 0, &contact, 1, &alias, G_MAXUINT);
	g_debug("Got alias for contact %u: %s", contact, alias);
	if (contact == priv->self_handle)
	{
	    g_debug("This is our alias");
	    if (!priv->alias || strcmp (priv->alias, alias) != 0)
	    {
		g_free (priv->alias);
		priv->alias = alias;
		mc_account_set_alias (priv->account, alias);
	    }
	    break;
	}
	g_free (alias);
    }
}

static void
set_alias_cb (DBusGProxy *proxy, GError *error, gpointer userdata)
{
    if (error)
    {
	g_warning ("%s: error: %s", G_STRFUNC, error->message);
	g_error_free (error);
    }
}

static void
_mcd_connection_setup_alias (McdConnectionPrivate *priv)
{
    GHashTable *aliases;
    gchar *alias;

    if (!priv->alias_proxy)
    {
	priv->alias_proxy = tp_conn_get_interface (priv->tp_conn,
					TELEPATHY_CONN_IFACE_ALIASING_QUARK);
	if (!priv->alias_proxy)
	{
	    g_debug ("%s: connection does not support aliasing interface", G_STRFUNC);
	    return;
	}
	dbus_g_proxy_connect_signal (priv->alias_proxy,
				     "AliasesChanged",
				     G_CALLBACK (on_aliases_changed),
				     priv, NULL);
	g_object_ref (priv->alias_proxy);
    }
    alias = mc_account_get_alias (priv->account);
    if (alias && (!priv->alias || strcmp (priv->alias, alias) != 0))
    {
	g_debug ("%s: setting alias '%s'", G_STRFUNC, alias);

	aliases = g_hash_table_new (NULL, NULL);
	g_hash_table_insert (aliases, GINT_TO_POINTER(priv->self_handle), alias);
	tp_conn_iface_aliasing_set_aliases_async (priv->alias_proxy, aliases,
						  set_alias_cb, priv);
	g_hash_table_destroy (aliases);
    }
    g_free (alias);
}

static gboolean
mcd_connection_reconnect (McdConnection *connection)
{
    g_debug ("%s: %p", G_STRFUNC, connection);
    _mcd_connection_setup (connection);
    return FALSE;
}

static void
_mcd_connection_status_changed_cb (DBusGProxy * tp_conn_proxy,
				   TelepathyConnectionStatus conn_status,
				   TelepathyConnectionStatusReason
				   conn_reason, McdConnection * connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    g_debug ("%s: status_changed called from tp (%d)", G_STRFUNC, conn_status);

    switch (conn_status)
    {
    case TP_CONN_STATUS_CONNECTING:
	mcd_presence_frame_set_account_status (priv->presence_frame,
					       priv->account,
					       conn_status, conn_reason);
	priv->abort_reason = TP_CONN_STATUS_REASON_NONE_SPECIFIED;
	break;
    case TP_CONN_STATUS_CONNECTED:
	{
	    const gchar *presence_message;
	    McPresence requested_presence;

	    mcd_presence_frame_set_account_status (priv->presence_frame,
						   priv->account,
						   conn_status, conn_reason);
	    requested_presence =
		mcd_presence_frame_get_requested_presence (priv->presence_frame);
	    presence_message =
		mcd_presence_frame_get_requested_presence_message (priv->presence_frame);
	    _mcd_connection_set_presence (connection, requested_presence,
					  presence_message);
	    _mcd_connection_get_self_handle (priv);
	    _mcd_connection_setup_capabilities (connection);
	    _mcd_connection_setup_avatar (priv);
	    _mcd_connection_setup_alias (priv);
	    _mcd_connection_get_normalized_name (priv);
	    priv->reconnect_interval = 30 * 1000; /* reset it to 30 seconds */
	}
	break;
    case TP_CONN_STATUS_DISCONNECTED:
	/* Connection could die during account status updated if its
	 * manager is the only one holding the reference to it (manager will
	 * remove the connection from itself). To ensure we get a chance to
	 * emit abort signal (there could be others holding a ref to it), we
	 * will hold a temporary ref to it.
	 */
	priv->abort_reason = conn_reason;
	
	/* Destroy any pending timer */
	if (priv->capabilities_timer)
	    g_source_remove (priv->capabilities_timer);
	priv->capabilities_timer = 0;
	
	/* Notify connection abort */
	if (conn_reason == TP_CONN_STATUS_REASON_NETWORK_ERROR ||
	    conn_reason == TP_CONN_STATUS_REASON_NONE_SPECIFIED ||
	    priv->reconnection_requested)
	{
	    /* we were disconnected by a network error or by a gabble crash (in
	     * the latter case, we get NoneSpecified as a reason): don't abort
	     * the connection but try to reconnect later */
	    _mcd_connection_release_tp_connection (connection);
	    priv->reconnect_timer = g_timeout_add (priv->reconnect_interval,
					(GSourceFunc)mcd_connection_reconnect,
					connection);
	    priv->reconnect_interval *= 2;
	    if (priv->reconnect_interval >= 30 * 60 * 1000)
		/* no more than 30 minutes! */
		priv->reconnect_interval = 30 * 60 * 1000;
	    /* FIXME HACK: since we want presence-applet to immediately start
	     * displaying a blinking icon, we must set the account status to
	     * CONNECTING now */
	    mcd_presence_frame_set_account_status (priv->presence_frame,
						   priv->account,
						   TP_CONN_STATUS_CONNECTING,
						   TP_CONN_STATUS_REASON_REQUESTED);
	    priv->reconnection_requested = FALSE;
	    return;
	}

	g_object_ref (connection);
	/* Notify connection abort */
	mcd_mission_abort (MCD_MISSION (connection));
	g_object_unref (connection);
	break;
    default:
	g_warning ("Unknown telepathy connection status");
    }
}

static void proxy_destroyed (DBusGProxy *tp_conn, McdConnection *connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    g_debug ("Proxy destroyed!");
    priv->tp_conn = NULL;
    _mcd_connection_status_changed_cb (tp_conn,
				       TP_CONN_STATUS_DISCONNECTED,
				       TP_CONN_STATUS_REASON_NONE_SPECIFIED,
				       connection);
    g_object_unref (tp_conn);
}

static void
mcd_async_connect_cb (DBusGProxy *proxy, GError *error, gpointer userdata)
{
    McdConnection *connection = userdata;

    g_debug ("%s called for connection %p", G_STRFUNC, connection);

    g_object_set_data (G_OBJECT (connection), "connect_call", NULL);
    if (error)
    {
	McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
	g_warning ("%s: tp_conn_connect failed: %s",
		   G_STRFUNC, error->message);
	mcd_presence_frame_set_account_status (priv->presence_frame,
					       priv->account,
					       TP_CONN_STATUS_DISCONNECTED,
					       TP_CONN_STATUS_REASON_NETWORK_ERROR);
	g_error_free (error);
    }
}

static GHashTable *
get_extra_parameters (McdConnection *connection)
{
    McdMission *mission;
 
    mission = mcd_mission_get_parent (MCD_MISSION (connection));
    g_return_val_if_fail (mission != NULL, NULL);
    mission = mcd_mission_get_parent (mission);
    g_return_val_if_fail (mission != NULL && MCD_IS_MASTER (mission), NULL);
    return mcd_master_get_connection_parameters (MCD_MASTER (mission));
}

static void
add_supported_param (gpointer key, gpointer value, gpointer userdata)
{
    struct param_data *pd = (struct param_data *)userdata;
    gboolean found = FALSE;
    GSList *list;
 
    for (list = pd->pr_params; list != NULL; list = list->next)
    {
	McProtocolParam *param = list->data;
	if (strcmp (param->name, key) == 0)
	{
	    found = TRUE;
	    break;
	}
    }
    if (found && !g_hash_table_lookup (pd->dest, key))
    {
	g_debug ("%s: adding parameter %s", G_STRFUNC, (gchar *)key);
	g_hash_table_insert (pd->dest, key, value);
    }
}

static void
add_supported_extra_parameters (GHashTable *extra, McProfile *profile,
				GHashTable *params)
{
    McProtocol *protocol;
    struct param_data pd;
    GSList *pr_params;

    protocol = mc_profile_get_protocol (profile);
    g_return_if_fail (protocol != NULL);

    pr_params = mc_protocol_get_params (protocol);
    pd.pr_params = pr_params;
    pd.dest = params;
    g_hash_table_foreach (extra, add_supported_param, &pd);
    mc_protocol_free_params_list (pr_params);
    g_object_unref (protocol);
}

static void
remove_extra_parameter (gpointer key, gpointer value, gpointer userdata)
{
    GHashTable *params = (GHashTable *)userdata;
    g_hash_table_steal (params, key);
}

static void
remove_extra_parameters (GHashTable *extra_parameters, GHashTable *params)
{
    /* we need to remove the extra parameters from the parameters hash table
     * because otherwise whey will be freed twice (and possibly in a wrong way)
     * by the two g_hash_table_destroy() calls, since we didn't copy them */
    g_hash_table_foreach (extra_parameters, remove_extra_parameter, params);
    g_hash_table_destroy (extra_parameters);
}

static void
_mcd_connection_connect (McdConnection *connection, GHashTable *params)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    TelepathyConnectionStatus conn_status;
    McProfile *profile;
    const gchar *protocol_name;
    const gchar *account_name;
    gchar *conn_bus_name, *conn_obj_path;
    GHashTable *extra_parameters;
    GError *error = NULL;
    gboolean ret;

    profile = mc_account_get_profile (priv->account);
    protocol_name = mc_profile_get_protocol_name (profile);
    account_name = mc_account_get_unique_name (priv->account);

    g_debug ("%s: Trying connect account: %s",
	     G_STRFUNC, (gchar *) account_name);

    extra_parameters = get_extra_parameters (connection);
    add_supported_extra_parameters (extra_parameters, profile, params);
    ret = tp_connmgr_request_connection (DBUS_G_PROXY (priv->tp_conn_mgr),
					 protocol_name, params,
					 &conn_bus_name, &conn_obj_path,
					 &error);
    remove_extra_parameters (extra_parameters, params);
    g_object_unref (profile);
    if (!ret)
    {
	if (error)
	{
	    g_warning ("%s: tp_connmgr_request_connection failed: %s",
		       G_STRFUNC, error->message);
	    g_error_free (error);
	}
	mcd_presence_frame_set_account_status (priv->presence_frame,
					       priv->account,
					       TP_CONN_STATUS_DISCONNECTED,
					       TP_CONN_STATUS_REASON_NETWORK_ERROR);
	return;
    }

    priv->tp_conn = tp_conn_new_without_connect (priv->dbus_connection,
						 conn_bus_name,
						 conn_obj_path,
						 &conn_status, &error);
    g_free (conn_bus_name);
    g_free (conn_obj_path);
    if (!priv->tp_conn)
    {
	g_warning ("%s: tp_conn_new_without_connect failed: %s",
		   G_STRFUNC, error->message);
	mcd_presence_frame_set_account_status (priv->presence_frame,
					       priv->account,
					       TP_CONN_STATUS_DISCONNECTED,
					       TP_CONN_STATUS_REASON_NETWORK_ERROR);
	g_error_free (error);
	return;
    }

    /* Setup signals */
    g_signal_connect (priv->tp_conn, "destroy",
		      G_CALLBACK (proxy_destroyed), connection);
    dbus_g_proxy_connect_signal (DBUS_G_PROXY (priv->tp_conn), "NewChannel",
				 G_CALLBACK
				 (_mcd_connection_new_channel_cb),
				 connection, NULL);
    dbus_g_proxy_connect_signal (DBUS_G_PROXY (priv->tp_conn),
				 "StatusChanged",
				 G_CALLBACK
				 (_mcd_connection_status_changed_cb),
				 connection, NULL);

    /* if this was an already existing connection, it might be that it was
     * already connected/connecting, in which case we done. */
    if (conn_status != TP_CONN_STATUS_DISCONNECTED)
	mcd_presence_frame_set_account_status (priv->presence_frame,
					       priv->account,
					       conn_status,
					       TP_CONN_STATUS_REASON_NONE_SPECIFIED);
    else
    {
	DBusGProxyCall *call;
	/* Try to connect the connection */
	call = tp_conn_connect_async (DBUS_G_PROXY (priv->tp_conn),
				      mcd_async_connect_cb, connection);
	g_object_set_data (G_OBJECT (connection), "connect_call", call);
    }
}

static void
provisioning_cb (McdProvisioning *prov, GHashTable *parameters, GError *error,
		 gpointer user_data)
{
    McdConnection *connection = MCD_CONNECTION (user_data);
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    g_debug ("%s called", G_STRFUNC);
    priv->provisioning = NULL;
    if (error)
    {
	g_warning ("%s failed: %s", G_STRFUNC, error->message);
	g_error_free (error);
	mcd_presence_frame_set_account_status (priv->presence_frame,
					       priv->account,
					       TP_CONN_STATUS_DISCONNECTED,
					       TP_CONN_STATUS_REASON_AUTHENTICATION_FAILED);
	return;
    }
    _mcd_connection_connect (connection, parameters);
    g_hash_table_destroy (parameters);
}

static void
mcd_connection_get_params_and_connect (McdConnection *connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    GHashTable *params = NULL;
    McAccountSettingState state;
    gchar *url = NULL;
    McProfile *profile;
    const gchar *protocol_name;
    const gchar *account_name;
    gboolean requesting_provisioning = FALSE;

    mcd_presence_frame_set_account_status (priv->presence_frame,
					   priv->account,
					   TP_CONN_STATUS_CONNECTING,
					   TP_CONN_STATUS_REASON_REQUESTED);

    profile = mc_account_get_profile (priv->account);
    if (!profile)
    {
	mcd_presence_frame_set_account_status (priv->presence_frame,
					       priv->account,
					       TP_CONN_STATUS_DISCONNECTED,
					       TP_CONN_STATUS_REASON_AUTHENTICATION_FAILED);
	return;
    }
    protocol_name = mc_profile_get_protocol_name (profile);
    account_name = mc_account_get_unique_name (priv->account);

    g_debug ("%s: Trying connect account: %s",
	     G_STRFUNC, (gchar *) account_name);

    state = mc_account_get_param_string (priv->account, "prov-url", &url);
    if (state != MC_ACCOUNT_SETTING_ABSENT && url != NULL)
    {
	gchar *service = NULL, *username = NULL, *password = NULL;
	/* get parameters from provisioning service */
	mc_account_get_param_string (priv->account, "prov-service", &service);
	mc_account_get_param_string (priv->account, "prov-username", &username);
	mc_account_get_param_string (priv->account, "prov-password", &password);
	if (service)
	{
	    McdProvisioningFactory *factory;
	    McdProvisioning *prov;

	    factory = mcd_provisioning_factory_get ();
	    g_assert (factory != NULL);
	    prov = mcd_provisioning_factory_lookup (factory, service);
	    if (prov)
	    {
		g_debug ("%s: requesting parameters from provisioning service %s",
			 G_STRFUNC, service);
		/* if there was already a request, cancel it */
		if (priv->provisioning)
		    mcd_provisioning_cancel_request (priv->provisioning,
						     provisioning_cb,
						     connection);
		mcd_provisioning_request_parameters (prov, url,
						     username, password,
						     provisioning_cb,
						     connection);
		requesting_provisioning = TRUE;
		priv->provisioning = prov;
	    }
	    else
		g_debug ("%s: provisioning service %s not found",
			 G_STRFUNC, service);
	}
	g_free (service);
	g_free (url);
	g_free (username);
	g_free (password);
    }
    if (!requesting_provisioning)
    {
	params = mc_account_get_params (priv->account);
	_mcd_connection_connect (connection, params);
	g_hash_table_destroy (params);
    }
    g_object_unref (profile);
}

static void
_mcd_connection_setup (McdConnection * connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    g_return_if_fail (priv->bus_name);
    g_return_if_fail (priv->tp_conn_mgr);
    g_return_if_fail (priv->account);

    if (priv->reconnect_timer)
    {
	g_source_remove (priv->reconnect_timer);
	priv->reconnect_timer = 0;
    }

    /* FIXME HACK: the correct test is

    if (mcd_connection_get_connection_status (connection) ==
	TP_CONN_STATUS_DISCONNECTED)
     * but since we set the account status to CONNECTING as soon as we got
     * disconnected by a network error, we must accept that status, too */
    if (mcd_connection_get_connection_status (connection) !=
	TP_CONN_STATUS_CONNECTED)
    {
	mcd_connection_get_params_and_connect (connection);
    }
    else
    {
	g_debug ("%s: Not connecting because not disconnected (%i)",
		 G_STRFUNC, mcd_connection_get_connection_status (connection));
	return;
    }
}

static void
_mcd_connection_finalize (GObject * object)
{
    McdConnection *connection = MCD_CONNECTION (object);
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    g_free (priv->bus_name);
    
    _mcd_connection_free_presence_info (connection);

    G_OBJECT_CLASS (mcd_connection_parent_class)->finalize (object);
}

static void
_mcd_connection_release_tp_connection (McdConnection *connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    g_debug ("%s(%p) called", G_STRFUNC, connection);
    mcd_presence_frame_set_account_status (priv->presence_frame,
					   priv->account,
					   TP_CONN_STATUS_DISCONNECTED, 
					   priv->abort_reason);
    if (priv->tp_conn)
    {
	DBusGProxyCall *call;
	/* Disconnect signals */
	dbus_g_proxy_disconnect_signal (DBUS_G_PROXY (priv->tp_conn),
					"StatusChanged",
					G_CALLBACK
					(_mcd_connection_status_changed_cb),
					connection);
	dbus_g_proxy_disconnect_signal (DBUS_G_PROXY (priv->tp_conn),
					"NewChannel",
					G_CALLBACK
					(_mcd_connection_new_channel_cb),
					connection);
	g_signal_handlers_disconnect_by_func (G_OBJECT (priv->tp_conn),
					      G_CALLBACK (proxy_destroyed),
					      connection);

	/* cancel pending calls */
	call = g_object_get_data (G_OBJECT (connection), "connect_call");
	if (call)
	{
	    dbus_g_proxy_cancel_call (DBUS_G_PROXY (priv->tp_conn), call);
	    g_object_set_data (G_OBJECT (connection), "connect_call", NULL);
	}
        
	tp_conn_disconnect (DBUS_G_PROXY (priv->tp_conn), NULL);
	g_object_unref (priv->tp_conn);
	priv->tp_conn = NULL;
    }

    /* the interface proxies obtained from this connection must be deleted, too
     */
    if (priv->presence_proxy)
    {
	g_object_remove_weak_pointer (G_OBJECT(priv->presence_proxy),
				      (gpointer)&priv->presence_proxy);
	priv->presence_proxy = NULL;
    }
    if (priv->capabilities_proxy)
    {
	g_object_remove_weak_pointer (G_OBJECT(priv->capabilities_proxy),
				      (gpointer)&priv->capabilities_proxy);
	priv->capabilities_proxy = NULL;
    }
    if (priv->avatars_proxy)
    {
#ifndef NO_AVATAR_UPDATED
	dbus_g_proxy_disconnect_signal (priv->avatars_proxy,
					"AvatarUpdated",
					G_CALLBACK (on_avatar_updated),
					priv);
#endif
	g_object_unref (priv->avatars_proxy);
	priv->avatars_proxy = NULL;
    }
    if (priv->alias_proxy)
    {
	dbus_g_proxy_disconnect_signal (priv->alias_proxy,
					"AliasesChanged",
					G_CALLBACK (on_aliases_changed),
					priv);
	g_object_unref (priv->alias_proxy);
	priv->alias_proxy = NULL;
    }
    g_free (priv->alias);
    priv->alias = NULL;
    _mcd_connection_free_presence_info (connection);
}

static void
_mcd_connection_dispose (GObject * object)
{
    McdConnection *connection = MCD_CONNECTION (object);
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    g_debug ("%s called for object %p", G_STRFUNC, object);

    if (priv->is_disposed)
    {
	return;
    }

    priv->is_disposed = TRUE;

    /* Remove any pending source: timer and idle */
    g_source_remove_by_user_data (connection);
    priv->capabilities_timer = 0;
    
    mcd_operation_foreach (MCD_OPERATION (connection),
			   (GFunc) _foreach_channel_remove, connection);

    /* Unref pending channels */
    g_list_foreach (priv->pending_channels, (GFunc)pending_channel_free, NULL);
    g_list_free (priv->pending_channels);

    _mcd_connection_release_tp_connection (connection);
    
    if (priv->presence_frame != NULL)
    {
	g_signal_handlers_disconnect_by_func (G_OBJECT
					      (priv->presence_frame),
					      G_CALLBACK
					      (on_presence_requested), object);
	g_object_unref (priv->presence_frame);
	priv->presence_frame = NULL;
    }

    if (priv->account)
    {
	g_object_unref (priv->account);
	priv->account = NULL;
    }

    if (priv->tp_conn_mgr)
    {
	g_object_unref (priv->tp_conn_mgr);
	priv->tp_conn_mgr = NULL;
    }

    if (priv->dispatcher)
    {
	g_object_unref (priv->dispatcher);
	priv->dispatcher = NULL;
    }

    if (priv->provisioning)
    {
	mcd_provisioning_cancel_request (priv->provisioning, provisioning_cb,
					 connection);
	priv->provisioning = NULL;
    }
    G_OBJECT_CLASS (mcd_connection_parent_class)->dispose (object);
}

static void
_mcd_connection_set_property (GObject * obj, guint prop_id,
			      const GValue * val, GParamSpec * pspec)
{
    McdPresenceFrame *presence_frame;
    McdDispatcher *dispatcher;
    DBusGConnection *dbus_connection;
    McAccount *account;
    TpConnMgr *tp_conn_mgr;
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (obj);

    switch (prop_id)
    {
    case PROP_PRESENCE_FRAME:
	presence_frame = g_value_get_object (val);
	if (presence_frame)
	{
	    g_return_if_fail (MCD_IS_PRESENCE_FRAME (presence_frame));
	    g_object_ref (presence_frame);
	}

	if (priv->presence_frame)
	{
	    g_signal_handlers_disconnect_by_func (G_OBJECT
						  (priv->presence_frame),
						  G_CALLBACK
						  (on_presence_requested), obj);
	    g_object_unref (priv->presence_frame);
	}
	priv->presence_frame = presence_frame;
	if (priv->presence_frame)
	{
	    g_signal_connect_after (G_OBJECT (priv->presence_frame),
				    "presence-requested",
				    G_CALLBACK (on_presence_requested), obj);
	}
	break;
    case PROP_DISPATCHER:
	dispatcher = g_value_get_object (val);
	if (dispatcher)
	{
	    g_return_if_fail (MCD_IS_DISPATCHER (dispatcher));
	    g_object_ref (dispatcher);
	}
	if (priv->dispatcher)
	{
	    g_object_unref (priv->dispatcher);
	}
	priv->dispatcher = dispatcher;
	break;
    case PROP_DBUS_CONNECTION:
	dbus_connection = g_value_get_pointer (val);
	dbus_g_connection_ref (dbus_connection);
	if (priv->dbus_connection)
	    dbus_g_connection_unref (priv->dbus_connection);
	priv->dbus_connection = dbus_connection;
	break;
    case PROP_BUS_NAME:
	g_return_if_fail (g_value_get_string (val) != NULL);
	g_free (priv->bus_name);
	priv->bus_name = g_strdup (g_value_get_string (val));
	break;
    case PROP_TP_MANAGER:
	tp_conn_mgr = g_value_get_object (val);
	g_return_if_fail (TELEPATHY_IS_CONNMGR (tp_conn_mgr));
	g_object_ref (tp_conn_mgr);
	if (priv->tp_conn_mgr)
	    g_object_unref (priv->tp_conn_mgr);
	priv->tp_conn_mgr = tp_conn_mgr;
	break;
    case PROP_ACCOUNT:
	account = g_value_get_object (val);
	g_return_if_fail (MC_IS_ACCOUNT (account));
	g_object_ref (account);
	if (priv->account)
	    g_object_unref (priv->account);
	priv->account = account;
	break;
    default:
	G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
	break;
    }
}

static void
_mcd_connection_get_property (GObject * obj, guint prop_id,
			      GValue * val, GParamSpec * pspec)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (obj);

    switch (prop_id)
    {
    case PROP_DBUS_CONNECTION:
	g_value_set_pointer (val, priv->dbus_connection);
	break;
    case PROP_BUS_NAME:
	g_value_set_string (val, priv->bus_name);
	break;
    case PROP_ACCOUNT:
	g_value_set_object (val, priv->account);
	break;
    case PROP_TP_MANAGER:
	g_value_set_object (val, priv->tp_conn_mgr);
	break;
    case PROP_TP_CONNECTION:
	g_value_set_object (val, priv->tp_conn);
	break;
    case PROP_PRESENCE_FRAME:
	g_value_set_object (val, priv->presence_frame);
	break;
    case PROP_DISPATCHER:
	g_value_set_object (val, priv->dispatcher);
	break;
    default:
	G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
	break;
    }
}

static void
mcd_connection_class_init (McdConnectionClass * klass)
{
    GObjectClass *object_class = G_OBJECT_CLASS (klass);
    g_type_class_add_private (object_class, sizeof (McdConnectionPrivate));

    object_class->finalize = _mcd_connection_finalize;
    object_class->dispose = _mcd_connection_dispose;
    object_class->set_property = _mcd_connection_set_property;
    object_class->get_property = _mcd_connection_get_property;

    /* Properties */
    g_object_class_install_property (object_class,
				     PROP_PRESENCE_FRAME,
				     g_param_spec_object ("presence-frame",
							  _
							  ("Presence Frame Object"),
							  _
							  ("Presence frame Object used by connections to update presence"),
							  MCD_TYPE_PRESENCE_FRAME,
							  G_PARAM_READWRITE |
							  G_PARAM_CONSTRUCT_ONLY));
    g_object_class_install_property (object_class,
				     PROP_DISPATCHER,
				     g_param_spec_object ("dispatcher",
							  _("Dispatcher Object"),
							  _("Dispatcher to dispatch channels"),
							  MCD_TYPE_DISPATCHER,
							  G_PARAM_READWRITE |
							  G_PARAM_CONSTRUCT_ONLY));
    g_object_class_install_property (object_class, PROP_DBUS_CONNECTION,
				     g_param_spec_pointer ("dbus-connection",
							   _("DBus Connection"),
							   _
							   ("DBus connection to use by us"),
							   G_PARAM_READWRITE |
							   G_PARAM_CONSTRUCT_ONLY));
    g_object_class_install_property (object_class, PROP_BUS_NAME,
				     g_param_spec_string ("bus-name",
							  _("DBus Bus name"),
							  _
							  ("DBus Bus name to use by us"),
							  NULL,
							  G_PARAM_READWRITE |
							  G_PARAM_CONSTRUCT_ONLY));
    g_object_class_install_property (object_class, PROP_TP_MANAGER,
				     g_param_spec_object ("tp-manager",
							  _
							  ("Telepathy Manager Object"),
							  _
							  ("Telepathy Manager Object which this connection uses"),
							  TELEPATHY_CONNMGR_TYPE,
							  G_PARAM_READWRITE |
							  G_PARAM_CONSTRUCT_ONLY));
    g_object_class_install_property (object_class, PROP_TP_CONNECTION,
				     g_param_spec_object ("tp-connection",
							  _
							  ("Telepathy Connection Object"),
							  _
							  ("Telepathy Connection Object which this connection uses"),
							  TELEPATHY_CONN_TYPE,
							  G_PARAM_READABLE));
    g_object_class_install_property (object_class, PROP_ACCOUNT,
				     g_param_spec_object ("account",
							  _("Account Object"),
							  _
							  ("Account that will be used to create this connection"),
							  MC_TYPE_ACCOUNT,
							  G_PARAM_READWRITE |
							  G_PARAM_CONSTRUCT_ONLY));
}

static void
mcd_connection_init (McdConnection * connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    priv->abort_reason = TP_CONN_STATUS_REASON_NONE_SPECIFIED;

    priv->reconnect_interval = 30 * 1000; /* 30 seconds */
}

/* Public methods */

/* Creates a new connection object. Increases a refcount of account.
 * Uses mcd_get_manager function to get TpConnManager
 */
McdConnection *
mcd_connection_new (DBusGConnection * dbus_connection,
		    const gchar * bus_name,
		    TpConnMgr * tp_conn_mgr,
		    McAccount * account,
		    McdPresenceFrame * presence_frame,
		    McdDispatcher *dispatcher)
{
    McdConnection *mcdconn = NULL;
    g_return_val_if_fail (dbus_connection != NULL, NULL);
    g_return_val_if_fail (bus_name != NULL, NULL);
    g_return_val_if_fail (TELEPATHY_IS_CONNMGR (tp_conn_mgr), NULL);
    g_return_val_if_fail (MC_IS_ACCOUNT (account), NULL);
    g_return_val_if_fail (MCD_IS_PRESENCE_FRAME (presence_frame), NULL);

    mcdconn = g_object_new (MCD_TYPE_CONNECTION,
			    "dbus-connection", dbus_connection,
			    "bus-name", bus_name,
			    "tp-manager", tp_conn_mgr,
			    "presence-frame", presence_frame,
			    "dispatcher", dispatcher,
			    "account", account, NULL);
    return mcdconn;
}

/* Constant getters. These should probably be removed */

McAccount *
mcd_connection_get_account (McdConnection * id)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (id);
    return priv->account;
}

TelepathyConnectionStatus
mcd_connection_get_connection_status (McdConnection * id)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (id);
    return mcd_presence_frame_get_account_status (priv->presence_frame,
						  priv->account);
}

gboolean
mcd_connection_get_telepathy_details (McdConnection * id,
				      gchar ** ret_servname,
				      gchar ** ret_objpath)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (id);

    g_return_val_if_fail (priv->tp_conn != NULL, FALSE);
    g_return_val_if_fail (TELEPATHY_IS_CONN (priv->tp_conn), FALSE);

    /* Query the properties required for creation of identical TpConn object */
    *ret_objpath =
	g_strdup (dbus_g_proxy_get_path (DBUS_G_PROXY (priv->tp_conn)));
    *ret_servname =
	g_strdup (dbus_g_proxy_get_bus_name (DBUS_G_PROXY (priv->tp_conn)));

    return TRUE;
}

static GError *
map_tp_error_to_mc_error (McdChannel *channel, GError *tp_error)
{
    MCError mc_error_code = MC_CHANNEL_REQUEST_GENERIC_ERROR;
    
    g_warning ("Telepathy Error = %s", tp_error->message);
    
    /* TODO : Are there still more specific errors we need
     * to distinguish?
     */
    if (mcd_channel_get_channel_type_quark (channel) ==
	TELEPATHY_CHAN_IFACE_STREAMED_QUARK &&
	dbus_g_error_has_name(tp_error, "org.freedesktop.Telepathy.Error.NotAvailable"))
    {
	mc_error_code = MC_CONTACT_DOES_NOT_SUPPORT_VOICE_ERROR;
    }
    else if (dbus_g_error_has_name(tp_error, "org.freedesktop.Telepathy.Error.Channel.Banned"))
    {
	mc_error_code = MC_CHANNEL_BANNED_ERROR;
    }
    else if (dbus_g_error_has_name(tp_error, "org.freedesktop.Telepathy.Error.Channel.Full"))
    {
	mc_error_code = MC_CHANNEL_FULL_ERROR;
    }
    else if (dbus_g_error_has_name(tp_error, "org.freedesktop.Telepathy.Error.Channel.InviteOnly"))
    {
	mc_error_code = MC_CHANNEL_INVITE_ONLY_ERROR;
    }
    else if (dbus_g_error_has_name(tp_error, "org.freedesktop.Telepathy.Error.InvalidHandle"))
    {
	mc_error_code = MC_INVALID_HANDLE_ERROR;
    }
    return g_error_new (MC_ERROR, mc_error_code, "Telepathy Error: %s",
			tp_error->message);
}

static void
remove_capabilities_refs (gpointer data)
{
    struct capabilities_wait_data *cwd = data;

    g_debug ("\n\n\n%s called\n\n\n", G_STRFUNC);
    dbus_g_proxy_disconnect_signal (cwd->priv->capabilities_proxy,
				    "CapabilitiesChanged",
				    G_CALLBACK (on_capabilities_changed),
				    cwd->channel);
    g_error_free (cwd->error);
    g_free (cwd);
}

static gint
pending_channel_cmp (const McdPendingChannel *a, const McdPendingChannel *b)
{
    return a->handle == b->handle &&
	a->handle_type == b->handle_type &&
	strcmp (a->type, b->type);
}

static void
mcd_async_request_chan_callback (DBusGProxy *proxy,
				 gchar *channel_path,
				 GError *error,
				 gpointer user_data)
{
    McdChannel *channel;
    McdConnection *connection;
    McdConnectionPrivate *priv;
    GError *error_on_creation;
    struct capabilities_wait_data *cwd;
    gchar *chan_type;
    TelepathyHandleType chan_handle_type;
    guint chan_handle;
    TpChan *tp_chan;
    McdPendingChannel pc;
    GList *list;
    /* We handle only the dbus errors */
    
    /* ChannelRequestor *chan_req = (ChannelRequestor *)user_data; */
    channel = MCD_CHANNEL (user_data); /* the not-yet-added channel */
    connection = g_object_get_data (G_OBJECT (channel), "temporary_connection");
    g_object_steal_data (G_OBJECT (channel), "tp_chan_call");
    priv = MCD_CONNECTION_PRIV (connection);

    g_object_get (channel,
		  "channel-handle", &chan_handle,
		  "channel-handle-type", &chan_handle_type,
		  "channel-type", &chan_type,
		  NULL);

    pc.handle = chan_handle;
    pc.handle_type = chan_handle_type;
    pc.type = chan_type;
    pc.channel = NULL;

    cwd = g_object_get_data (G_OBJECT (channel), "error_on_creation");
    if (cwd)
    {
	error_on_creation = cwd->error;
	g_object_set_data (G_OBJECT (channel), "error_on_creation", NULL);
    }
    else
	error_on_creation = NULL;

    
    if (error != NULL)
    {
	g_debug ("%s: Got error: %s", G_STRFUNC, error->message);
	if (error_on_creation != NULL)
	{
	    /* replace the error, so that the initial one is reported */
	    g_error_free (error);
	    error = error_on_creation;
	}

	if (priv->got_capabilities || error_on_creation)
	{
	    /* Faild dispatch */
	    GError *mc_error = map_tp_error_to_mc_error (channel, error);
	    g_signal_emit_by_name (G_OBJECT(priv->dispatcher), "dispatch-failed",
				   channel, mc_error);
	    g_error_free (mc_error);
	    g_error_free (error);
	    
	    /* No abort on channel, because we are the only one holding the only
	     * reference to this temporary channel.
	     * This should also unref the channel object
	     */
	    list = g_list_find_custom (priv->pending_channels, &pc,
				       (GCompareFunc)pending_channel_cmp);
	    if (list)
	    {
		pending_channel_free (list->data);
		priv->pending_channels =
		    g_list_delete_link (priv->pending_channels, list);
	    }
	}
	else
	{
	    /* the channel request has failed probably because we are just
	     * connected and we didn't recive the contact capabilities yet. In
	     * this case, wait for this contact's capabilities to arrive */
	    g_debug ("%s: listening for remote capabilities on channel handle %d, type %d",
		     G_STRFUNC, chan_handle, mcd_channel_get_handle_type (channel));
	    dbus_g_proxy_connect_signal (priv->capabilities_proxy,
					 "CapabilitiesChanged",
					 G_CALLBACK (on_capabilities_changed),
					 channel, NULL);
	    /* Store the error, we might need it later */
	    cwd = g_malloc (sizeof (struct capabilities_wait_data));
	    g_assert (cwd != NULL);
	    cwd->error = error;
	    cwd->channel = channel;
	    cwd->priv = priv;
	    g_object_set_data_full (G_OBJECT (channel), "error_on_creation", cwd,
				    remove_capabilities_refs);
	}
	g_free (chan_type);
	return;
    }
    
    if (channel_path == NULL)
    {
	GError *mc_error;
	g_warning ("Returned channel_path from telepathy is NULL");
	
	mc_error = g_error_new (MC_ERROR,
				MC_CHANNEL_REQUEST_GENERIC_ERROR,
				"Returned channel_path from telepathy is NULL");
	g_signal_emit_by_name (G_OBJECT(priv->dispatcher),
			       "dispatch-failed", channel, mc_error);
	g_error_free (mc_error);
	
	/* No abort on channel, because we are the only one holding the only
	 * reference to this temporary channel.
	 * This should also unref the channel object
	 */
	list = g_list_find_custom (priv->pending_channels, &pc,
				   (GCompareFunc)pending_channel_cmp);
	if (list)
	{
	    pending_channel_free (list->data);
	    priv->pending_channels =
	       	g_list_delete_link (priv->pending_channels, list);
	}
	g_free (chan_type);
	return;
    }
    
    /* Everything here is well and fine. We can create the channel. */
    list = g_list_find_custom (priv->pending_channels, &pc,
			       (GCompareFunc)pending_channel_cmp);
    channel = ((McdPendingChannel *)list->data)->channel;
    if (!channel)
    {
	g_warning ("%s: channel not found among the pending ones", G_STRFUNC);
	g_free (chan_type);
	return;
    }

    tp_chan = tp_chan_new (priv->dbus_connection, priv->bus_name,
			   channel_path, chan_type, chan_handle_type, chan_handle);
    g_object_set (channel,
		  "channel-object-path", channel_path,
		  "tp-channel", tp_chan,
		  NULL);

    /* The channel is no longer pending. We increase the reference count, since
     * pending_channel_free() will decrease it */
    g_object_ref (channel);
    pending_channel_free (list->data);
    priv->pending_channels = g_list_delete_link (priv->pending_channels, list);
    mcd_operation_take_mission (MCD_OPERATION (connection),
				MCD_MISSION (channel));

    /* Channel about to be dispatched */
    mcd_channel_set_status (channel, MCD_CHANNEL_DISPATCHING);
    
    /* Dispatch the incoming channel */
    mcd_dispatcher_send (priv->dispatcher, channel);
    
    g_free (chan_type);
    g_free (channel_path);
    g_object_unref (tp_chan);
}

static void
mcd_async_request_handle_callback(DBusGProxy *proxy, GArray *handles,
				  GError *error, gpointer user_data)
{
    McdChannel *channel, *existing_channel;
    McdConnection *connection;
    McdConnectionPrivate *priv;
    guint chan_handle, chan_handle_type;
    const gchar *chan_type;
    const GList *channels;
    DBusGProxyCall *call;
    McdPendingChannel *pc;
    
    channel = MCD_CHANNEL (user_data);
    connection = g_object_get_data (G_OBJECT (channel), "temporary_connection");
    priv = MCD_CONNECTION_PRIV (connection);
    
    if (error != NULL)
    {
	GError *mc_error;
	g_warning ("Could not map string handle to a valid handle!: %s",
		   error->message);
	
	/* Fail dispatch */
	mc_error = g_error_new (MC_ERROR, MC_INVALID_HANDLE_ERROR,
		     "Could not map string handle to a valid handle!: %s",
				error->message);
	g_signal_emit_by_name (priv->dispatcher, "dispatch-failed",
			       channel, mc_error);
	g_error_free (mc_error);
	g_error_free(error);
	
	/* No abort, because we are the only one holding the only reference
	 * to this temporary channel
	 */
	g_object_unref (channel);
	return;
    }
    
    chan_type = mcd_channel_get_channel_type (channel),
    chan_handle_type = mcd_channel_get_handle_type (channel),
    chan_handle = g_array_index (handles, guint, 0);
    g_array_free(handles, TRUE);
    
    g_debug ("Got handle %u", chan_handle);
    
    /* Is the handle we got valid? */
    if (chan_handle == 0)
    {
	GError *mc_error;
	g_warning ("Could not map the string  to a valid handle!");
	
	/* Fail dispatch */
	mc_error = g_error_new (MC_ERROR, MC_INVALID_HANDLE_ERROR,
			     "Could not map string handle to a valid handle!");
	g_signal_emit_by_name (priv->dispatcher, "dispatch-failed",
			       channel, mc_error);
	g_error_free (mc_error);
	
	/* No abort, because we are the only one holding the only reference
	 * to this temporary channel
	 */
	g_object_unref (channel);
	return;
    }
    
    /* Check if a telepathy channel has already been created; this could happen
     * in the case we had a chat window open, the UI crashed and now the same
     * channel is requested. */
    channels = mcd_operation_get_missions (MCD_OPERATION (connection));
    while (channels)
    {
	existing_channel = MCD_CHANNEL (channels->data);
	g_debug ("Chan: %d, handle type %d, channel type %s",
		 mcd_channel_get_handle (existing_channel),
		 mcd_channel_get_handle_type (existing_channel),
		 mcd_channel_get_channel_type (existing_channel));
	if (chan_handle == mcd_channel_get_handle (existing_channel) &&
	    chan_handle_type == mcd_channel_get_handle_type (existing_channel) &&
	    strcmp(chan_type,
		   mcd_channel_get_channel_type (existing_channel)) == 0)
	{
	    guint requestor_serial;
	    gchar *requestor_client_id;

	    g_debug ("%s: Channel already existing, returning old one", G_STRFUNC);
	    /* we retrieve the information we need from the newly created
	     * channel object and set them to the "old" channel */
	    g_object_get (channel,
			  "requestor-serial", &requestor_serial,
			  "requestor-client-id", &requestor_client_id,
			  NULL);
	    g_object_set (existing_channel,
			  "requestor-serial", requestor_serial,
			  "requestor-client-id", requestor_client_id,
			  NULL);
	    g_free (requestor_client_id);
	    /* we no longer need the new channel */
	    g_object_unref (channel);
	    /* notify the dispatcher again */
	    mcd_dispatcher_send (priv->dispatcher, existing_channel);
	    return;
	}
	channels = channels->next;
    }

    /* Update our newly acquired information */
    g_object_set (channel, "channel-handle", chan_handle, NULL);
 
    /* The channel is temporary and stays in priv->pending_channels until
     * a telepathy channel for it is created
     */
    pc = g_malloc (sizeof(McdPendingChannel));
    pc->handle = chan_handle;
    pc->handle_type = chan_handle_type;
    pc->type = chan_type;
    pc->channel = channel;
    priv->pending_channels = g_list_prepend (priv->pending_channels, pc);
    
    /* Now, request the corresponding telepathy channel. */
    call = tp_conn_request_channel_async(DBUS_G_PROXY(proxy),
					 mcd_channel_get_channel_type (channel),
					 mcd_channel_get_handle_type (channel),
					 chan_handle, TRUE,
					 mcd_async_request_chan_callback,
					 channel);
    g_object_set_data (G_OBJECT (channel), "tp_chan_call", call);
}

gboolean
mcd_connection_request_channel (McdConnection *connection,
				const struct mcd_channel_request *req,
			       	GError ** error)
{
    McdChannel *channel;
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    
    g_return_val_if_fail (priv->tp_conn != NULL, FALSE);
    g_return_val_if_fail (TELEPATHY_IS_CONN (priv->tp_conn), FALSE);
    
    /* The channel is temporary */
    channel = mcd_channel_new (NULL,
			       NULL,
			       req->channel_type,
			       req->channel_handle,
			       req->channel_handle_type,
			       TRUE, /* outgoing */
			       req->requestor_serial,
			       req->requestor_client_id);
    
    /* We do not add the channel in connection until tp_channel is created */
    g_object_set_data (G_OBJECT (channel), "temporary_connection", connection);
    
    if (req->channel_handle != 0 || req->channel_handle_type == 0)
    {
	DBusGProxyCall *call;
	McdPendingChannel *pc;

	/* the channel stays in priv->pending_channels until a telepathy
	 * channel for it is created */
	pc = g_malloc (sizeof(McdPendingChannel));
	pc->handle = req->channel_handle;
	pc->handle_type = req->channel_handle_type;
	pc->type = req->channel_type;
	pc->channel = channel;
	priv->pending_channels = g_list_prepend (priv->pending_channels, pc);

	call = tp_conn_request_channel_async(DBUS_G_PROXY(priv->tp_conn),
					     req->channel_type,
					     req->channel_handle_type,
					     req->channel_handle, TRUE,
					     mcd_async_request_chan_callback,
					     channel);
	g_object_set_data (G_OBJECT (channel), "tp_chan_call", call);
    }
    else
    {
	/* if channel handle is 0, this means that the channel was requested by
	 * a string handle; in that case, we must first request a channel
	 * handle for it */
	const gchar *name_array[2];
	g_return_val_if_fail (req->channel_handle_string != NULL, FALSE);

	name_array[0] = req->channel_handle_string;
	name_array[1] = NULL;

	/* Channel is temporary and will enter priv->pending_channels list
	 * only when we successfully resolve the handle. */
	tp_conn_request_handles_async (DBUS_G_PROXY(priv->tp_conn),
				       req->channel_handle_type,
				       name_array,
				       mcd_async_request_handle_callback,
				       channel);
    }
    return TRUE;
}

static gboolean
channel_matches_request (McdChannel *channel,
			 struct request_id *req_id)
{
    guint requestor_serial;
    gchar *requestor_client_id;
    gboolean found;

    g_object_get (channel,
		  "requestor-serial", &requestor_serial,
		  "requestor-client-id", &requestor_client_id,
		  NULL);
    if (requestor_serial == req_id->requestor_serial &&
	strcmp (requestor_client_id, req_id->requestor_client_id) == 0)
	found = TRUE;
    else
	found = FALSE;
    g_free (requestor_client_id);
    return found;
}

gboolean
mcd_connection_cancel_channel_request (McdConnection *connection,
				       guint operation_id,
				       const gchar *requestor_client_id,
				       GError **error)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    struct request_id req_id;
    const GList *channels, *node;
    GList *list;
    McdChannel *channel;

    /* first, see if the channel is in the list of the pending channels */
    req_id.requestor_serial = operation_id;
    req_id.requestor_client_id = requestor_client_id;

    for (list = priv->pending_channels; list; list = list->next)
    {
	DBusGProxyCall *call;
	McdPendingChannel *pc = list->data;

	if (!channel_matches_request (pc->channel, &req_id)) continue;
	channel = pc->channel;

	g_debug ("%s: requested channel found in the pending_channels list (%p)", G_STRFUNC, channel);
	/* check for pending dbus calls to be cancelled */
	call = g_object_get_data (G_OBJECT (channel), "tp_chan_call");
	dbus_g_proxy_cancel_call (DBUS_G_PROXY(priv->tp_conn), call);
	/* No abort on channel, because we are the only one holding the only
	 * reference to this temporary channel.
	 * This should also unref the channel object.
	 * No other actions needed; if a NewChannel signal will be emitted for
	 * this channel, it will be ignored since it has the suppress_handler
	 * flag set.
	 */
	pending_channel_free (pc);
	priv->pending_channels = g_list_delete_link (priv->pending_channels, list);
	return TRUE;
    }

    /* the channel might already have a TpChan created for it, and either be in
     * the dispatcher or be already handled. Aborting in any case. */
    channels = mcd_operation_get_missions (MCD_OPERATION (connection));
    if (!channels) return FALSE;

    for (node = channels; node; node = node->next)
    {
	guint chan_requestor_serial;
	gchar *chan_requestor_client_id;

	channel = MCD_CHANNEL (node->data);
	g_object_get (channel,
		      "requestor-serial", &chan_requestor_serial,
		      "requestor-client-id", &chan_requestor_client_id,
		      NULL);
	if (chan_requestor_serial == operation_id &&
	    strcmp (chan_requestor_client_id, requestor_client_id) == 0)
	{
	    g_debug ("%s: requested channel found (%p)", G_STRFUNC, channel);
	    mcd_mission_abort (MCD_MISSION (channel));
	    g_free (chan_requestor_client_id);
	    return TRUE;
	}
	g_free (chan_requestor_client_id);
    }
    g_debug ("%s: requested channel not found!", G_STRFUNC);
    return FALSE;
}

static void
request_avatar_cb (DBusGProxy *proxy, GArray *avatar, char *mime_type,
		   GError *error, gpointer userdata)
{
    McdConnectionPrivate *priv = (McdConnectionPrivate *)userdata;
    gchar *filename;
    if (error)
    {
	g_warning ("%s: error: %s", G_STRFUNC, error->message);
	g_error_free (error);
	return;
    }
    g_debug ("%s: received mime-type: %s", G_STRFUNC, mime_type);
    if (mc_account_get_avatar (priv->account, &filename, NULL, NULL))
    {
	g_file_set_contents (filename, avatar->data, avatar->len, NULL);
	mc_account_set_avatar_mime_type (priv->account, mime_type);
	mc_account_reset_avatar_id (priv->account);
	g_free (filename);
    }
    g_free (mime_type);
}

/**
 * mcd_connection_remote_avatar_changed:
 * @connection: the #McdConnection.
 * @contact_id: the own contact id in Telepathy.
 * @token: the new avatar token.
 *
 * This function is to be called when Telepathy signals that our own avatar has
 * been updated. It takes care of checking if the remote avatar has to be
 * retrieved and stored in the account.
 *
 * Returns: %TRUE if the local avatar has been updated.
 */
gboolean mcd_connection_remote_avatar_changed (McdConnection *connection,
					       guint contact_id,
					       const gchar *token)
{
#ifdef NO_AVATAR_UPDATED
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    if (!priv->avatars_proxy)
    {
	g_warning ("%s: avatar proxy is gone", G_STRFUNC);
	return FALSE;
    }

    return on_avatar_updated (priv->avatars_proxy, contact_id, token, priv);
#else
    g_debug ("%s called, but it's a stub", G_STRFUNC);
    return FALSE;
#endif
}

void
mcd_connection_close (McdConnection *connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    priv->abort_reason = TP_CONN_STATUS_REASON_REQUESTED;
    mcd_mission_abort (MCD_MISSION (connection));
}

/**
 * mcd_connection_account_changed:
 * @connection: the #McdConnection.
 *
 * This function must be called when the account this connection refers to is
 * modified.
 * Note: ideally, this should be a private method and the connection should
 * monitor the account itself; but since the monitoring is already done by
 * McdMaster for all accounts, it seemed more convenient to let it call this
 * function whenever needed.
 */
void
mcd_connection_account_changed (McdConnection *connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    if (priv->tp_conn) 
    {
	/* setup the avatar (if it has not been changed, this function does
	 * nothing) */
	_mcd_connection_setup_avatar (priv);
	_mcd_connection_setup_alias (priv);
    }
}

/**
 * mcd_connection_restart:
 * @connection: the #McdConnection.
 *
 * Disconnect the connection and reconnect it. This can be useful when some
 * account parameter changes.
 */
void
mcd_connection_restart (McdConnection *connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    g_debug ("%s called", G_STRFUNC);
    priv->reconnection_requested = TRUE;
    priv->reconnect_interval = 500; /* half a second */
    mcd_mission_disconnect (MCD_MISSION (connection));
    if (priv->tp_conn)
	tp_conn_disconnect (DBUS_G_PROXY (priv->tp_conn), NULL);
}

/**
 * mcd_connection_connect:
 * @connection: the #McdConnection.
 *
 * Activate @connection.
 */
void
mcd_connection_connect (McdConnection *connection)
{
    _mcd_connection_setup (connection);
}