~phablet-team/address-book-service/trunk

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
/*
 * Copyright 2013 Canonical Ltd.
 *
 * This file is part of contact-service-app.
 *
 * contact-service-app is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3.
 *
 * contact-service-app 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"
#include "addressbook.h"
#include "addressbook-adaptor.h"
#include "view.h"
#include "contacts-map.h"
#include "qindividual.h"
#include "dirtycontact-notify.h"
#include "e-source-ubuntu.h"

#include "common/vcard-parser.h"

#include <QtCore/QPair>
#include <QtCore/QUuid>

#include <QtContacts/QContactExtendedDetail>

#include <signal.h>
#include <sys/socket.h>

#include <folks/folks-eds.h>

// Ubuntu
#include <messaging-menu-app.h>
#include <messaging-menu-message.h>
#include <url-dispatcher.h>

namespace C {
#include <libintl.h>
}

#define MESSAGING_MENU_SOURCE_ID "address-book-service"

using namespace QtContacts;

namespace
{

class CreateContactData
{
public:
    QDBusMessage m_message;
    QContact m_contact;
    galera::AddressBook *m_addressbook;
};

class UpdateContactsData
{
public:
    QList<QContact> m_contacts;
    QStringList m_request;
    int m_currentIndex;
    QStringList m_result;
    galera::AddressBook *m_addressbook;
    QDBusMessage m_message;
};

class RemoveContactsData
{
public:
    QStringList m_request;
    galera::AddressBook *m_addressbook;
    QDBusMessage m_message;
    int m_sucessCount;
    bool m_softRemoval;
};

class CreateSourceData
{
public:
    QString m_sourceId;
    QString m_sourceName;
    QString m_applicationId;
    QString m_providerName;
    uint m_accountId;
    bool m_setAsPrimary;
    galera::AddressBook *m_addressbook;
    QDBusMessage m_message;
    ESource *m_source;
};

class UpdateSourceData
{
public:
    galera::SourceList m_toUpdate;
    galera::SourceList m_result;
    ESource *m_currentSource;
    ESourceRegistry *m_registry;
    galera::AddressBook *m_addressbook;
    QDBusMessage m_message;
};

class RemoveSourceData
{
public:
    galera::AddressBook *m_addressbook;
    QDBusMessage m_message;
};

ESource* create_esource_from_data(CreateSourceData &data, ESourceRegistry **registry)
{
    GError *error = NULL;
    ESource *source = e_source_new_with_uid(data.m_sourceId.toUtf8().data(), NULL, &error);
    if (error) {
        qWarning() << "Fail to create source" << error->message;
        g_error_free(error);
        return 0;
    }

    e_source_set_parent(source, "contacts-stub");
    e_source_set_display_name(source, data.m_sourceName.toUtf8().data());

    if (data.m_accountId > 0) {
        ESourceUbuntu *ubuntu_ex = E_SOURCE_UBUNTU(e_source_get_extension(source, E_SOURCE_EXTENSION_UBUNTU));
        e_source_ubuntu_set_account_id(ubuntu_ex, data.m_accountId);
        e_source_ubuntu_set_application_id(ubuntu_ex, data.m_applicationId.toUtf8());
        e_source_ubuntu_set_autoremove(ubuntu_ex, TRUE);
        data.m_providerName = QString::fromUtf8(e_source_ubuntu_get_account_provider(ubuntu_ex));
    }

    ESourceAddressBook *ext = E_SOURCE_ADDRESS_BOOK(e_source_get_extension(source, E_SOURCE_EXTENSION_ADDRESS_BOOK));
    e_source_backend_set_backend_name(E_SOURCE_BACKEND(ext), "local");

    *registry = e_source_registry_new_sync(NULL, &error);
    if (error) {
        qWarning() << "Fail to change default contact address book" << error->message;
        g_error_free(error);
        g_object_unref(source);
        return 0;
    }

    return source;
}

}

namespace galera
{
int AddressBook::m_sigQuitFd[2] = {0, 0};
QSettings AddressBook::m_settings(SETTINGS_ORG, SETTINGS_APPLICATION);

AddressBook::AddressBook(QObject *parent)
    : QObject(parent),
      m_individualAggregator(0),
      m_contacts(0),
      m_adaptor(0),
      m_notifyContactUpdate(0),
      m_edsIsLive(false),
      m_ready(false),
      m_isAboutToQuit(false),
      m_isAboutToReload(false),
      m_individualsChangedDetailedId(0),
      m_notifyIsQuiescentHandlerId(0),
      m_connection(QDBusConnection::sessionBus()),
      m_messagingMenu(0),
      m_messagingMenuMessage(0),
      m_sourceRegistryListener(0)
{
    if (qEnvironmentVariableIsSet(ALTERNATIVE_CPIM_SERVICE_NAME)) {
        m_serviceName = qgetenv(ALTERNATIVE_CPIM_SERVICE_NAME);
        qDebug() << "Using alternative service name:" << m_serviceName;
    } else {
        m_serviceName = CPIM_SERVICE_NAME;
    }
    prepareUnixSignals();
    connectWithEDS();
    connect(this, SIGNAL(readyChanged()), SLOT(checkCompatibility()));
    connect(this, SIGNAL(safeModeChanged()), SLOT(onSafeModeChanged()));
}

AddressBook::~AddressBook()
{
    if (m_sourceRegistryListener) {
        g_object_unref(m_sourceRegistryListener);
        m_sourceRegistryListener = 0;
    }

    if (m_messagingMenuMessage) {
        g_object_unref(m_messagingMenuMessage);
        m_messagingMenuMessage = 0;
    }

    if (m_messagingMenu) {
        g_object_unref(m_messagingMenu);
        m_messagingMenu = 0;
    }

    if (m_individualAggregator) {
        qWarning() << "Addressbook destructor called while running, you should call shutdown first";
        shutdown();
        while (m_adaptor) {
            QCoreApplication::processEvents();
        }
    }

    if (m_notifyContactUpdate) {
        delete m_notifyContactUpdate;
        m_notifyContactUpdate = 0;
    }
}

QString AddressBook::objectPath()
{
    return CPIM_ADDRESSBOOK_OBJECT_PATH;
}

bool AddressBook::registerObject(QDBusConnection &connection)
{
    if (connection.interface()->isServiceRegistered(m_serviceName)) {
        qWarning() << "Galera pin service already registered";
        return false;
    } else if (!connection.registerService(m_serviceName)) {
        qWarning() << "Could not register service!" << m_serviceName;
        return false;
    }

    if (!m_adaptor) {
        m_adaptor = new AddressBookAdaptor(connection, this);
        if (!connection.registerObject(galera::AddressBook::objectPath(), this))
        {
            qWarning() << "Could not register object!" << objectPath();
            delete m_adaptor;
            m_adaptor = 0;
            if (m_notifyContactUpdate) {
                delete m_notifyContactUpdate;
                m_notifyContactUpdate = 0;
            }
        }
    }
    if (m_adaptor) {
        m_notifyContactUpdate = new DirtyContactsNotify(m_adaptor);
    }
    return (m_adaptor != 0);
}

bool AddressBook::start(QDBusConnection connection)
{
    if (registerObject(connection)) {
        m_connection = connection;
        prepareFolks();
        return true;
    }

    return false;
}

bool AddressBook::start()
{
    g_type_ensure (E_TYPE_SOURCE_UBUNTU);

    return start(QDBusConnection::sessionBus());
}

void AddressBook::unprepareFolks()
{
    // remove all contacts
    // flusing any pending notification
    m_notifyContactUpdate->flush();

    setIsReady(false);

    Q_FOREACH(View* view, m_views) {
        view->close();
    }
    m_views.clear();

    if (m_contacts) {
        delete m_contacts;
        m_contacts = 0;
    }

    qDebug() << "Will destroy aggregator" << (void*) m_individualAggregator;
    if (m_individualAggregator) {
        g_signal_handler_disconnect(m_individualAggregator,
                                    m_individualsChangedDetailedId);
        g_signal_handler_disconnect(m_individualAggregator,
                                    m_notifyIsQuiescentHandlerId);
        m_individualsChangedDetailedId = m_notifyIsQuiescentHandlerId = 0;

        // make it sync
        qDebug() << "call unprepare";
        folks_individual_aggregator_unprepare(m_individualAggregator,
                                              AddressBook::folksUnprepared,
                                              this);
    }
}

void AddressBook::checkCompatibility()
{
    QByteArray envSafeMode = qgetenv(ADDRESS_BOOK_SAFE_MODE);
    if (!envSafeMode.isEmpty()) {
        return;
    }

    bool enableSafeMode = m_settings.value(SETTINGS_SAFE_MODE_KEY, true).toBool();
    if (!enableSafeMode) {
        qDebug() << "Server marked as updated";
        return;
    }

    GError *gError = NULL;
    ESourceRegistry *r = e_source_registry_new_sync(NULL, &gError);
    if (gError) {
        qWarning() << "Fail to check compatibility" << gError->message;
        g_error_free(gError);
        return;
    }

    enableSafeMode = false;
    GList *sources = e_source_registry_list_sources(r, E_SOURCE_EXTENSION_ADDRESS_BOOK);
    for(GList *l = sources; l != NULL; l = l->next) {
        ESource *s = E_SOURCE(l->data);
        if ((strcmp(e_source_get_uid(s), "system-address-book") != 0)  &&
            !e_source_has_extension(s, E_SOURCE_EXTENSION_UBUNTU)) {
            qDebug() << "Source does not contains UBUNTU extension" << QString::fromUtf8(e_source_get_display_name(s));
            enableSafeMode = true;
            break;
        }
    }

    g_list_free_full(sources, g_object_unref);
    g_object_unref(r);

    if (enableSafeMode) {
        qWarning() << "Enabling safe mode";
        setSafeMode(true);
        Q_EMIT safeModeChanged();
    } else {
        qDebug() << "Safe mode not necessary";
    }
}

void AddressBook::shutdown()
{
    m_isAboutToQuit = true;
    unprepareFolks();
}

void AddressBook::continueShutdown()
{
    qDebug() << "Folks is not running anymore";
    if (m_adaptor) {
        if (m_connection.interface() &&
            m_connection.interface()->isValid()) {

            m_connection.unregisterObject(objectPath());
            if (m_connection.interface()->isServiceRegistered(m_serviceName)) {
                m_connection.unregisterService(m_serviceName);
            }
        }

        delete m_adaptor;
        m_adaptor = 0;
        Q_EMIT stopped();
    }
}

void AddressBook::setIsReady(bool isReady)
{
    if (isReady != m_ready) {
        m_ready = isReady;
        if (m_adaptor) {
            Q_EMIT readyChanged();
        }
    }
}

void AddressBook::prepareFolks()
{
    qDebug() << "Initialize folks";
    m_contacts = new ContactsMap;
    m_individualAggregator = folks_individual_aggregator_dup();
    gboolean ready;
    g_object_get(G_OBJECT(m_individualAggregator), "is-quiescent", &ready, NULL);
    m_notifyIsQuiescentHandlerId = g_signal_connect(m_individualAggregator,
                                          "notify::is-quiescent",
                                          (GCallback) AddressBook::isQuiescentChanged,
                                          this);

    m_individualsChangedDetailedId = g_signal_connect(m_individualAggregator,
                                          "individuals-changed-detailed",
                                          (GCallback) AddressBook::individualsChangedCb,
                                          this);

    folks_individual_aggregator_prepare(m_individualAggregator,
                                        (GAsyncReadyCallback) AddressBook::prepareFolksDone,
                                        this);
    if (ready) {
        qDebug() << "Folks is already in quiescent mode";
        setIsReady(ready);
    }
}

void AddressBook::unprepareEds()
{
    FolksBackendStore *store = folks_backend_store_dup();
    FolksBackend *edsBackend = folks_backend_store_dup_backend_by_name(store, "eds");
    if (edsBackend && folks_backend_get_is_prepared(edsBackend)) {
        qDebug() << "WILL unprepare EDS";
        folks_backend_unprepare(edsBackend,
                                AddressBook::edsUnprepared,
                                this);
    } else {
        qDebug() << "Eds not prepared will restart folks";
        prepareFolks();
    }
}

void AddressBook::connectWithEDS()
{
    // we need to keep it update with the EDS dbus service name
    static const QString evolutionServiceName(EVOLUTION_ADDRESSBOOK_SERVICE_NAME);

    // Check if eds was disabled manually
    // If eds was disabled we should skip the check
    if (qEnvironmentVariableIsSet("FOLKS_BACKENDS_ALLOWED")) {
        QString allowedBackends = qgetenv("FOLKS_BACKENDS_ALLOWED");
        if (!allowedBackends.contains("eds")) {
            m_edsIsLive = true;
            return;
        }
    }

    // connect with source registry to get notifications about source change
    GError *gError = NULL;
    if (m_sourceRegistryListener) {
        g_object_unref(m_sourceRegistryListener);
        m_sourceRegistryListener = 0;
    }
    m_sourceRegistryListener = e_source_registry_new_sync(NULL, &gError);
    if (gError) {
        qWarning() << "Fail to connect with source registry" << gError->message;
        g_error_free(gError);
        m_sourceRegistryListener = 0;
    } else {
        g_signal_connect(m_sourceRegistryListener,
                         "source-added",
                         G_CALLBACK(AddressBook::sourceEDSChanged),
                         this);
        g_signal_connect(m_sourceRegistryListener,
                         "source-changed",
                         G_CALLBACK(AddressBook::sourceEDSChanged),
                         this);
        g_signal_connect(m_sourceRegistryListener,
                         "source-removed",
                         G_CALLBACK(AddressBook::sourceEDSChanged),
                         this);
        g_signal_connect(m_sourceRegistryListener,
                         "source-enabled",
                         G_CALLBACK(AddressBook::sourceEDSChanged),
                         this);
        g_signal_connect(m_sourceRegistryListener,
                         "source-disabled",
                         G_CALLBACK(AddressBook::sourceEDSChanged),
                         this);
    }

    // check if service is already registered
    // We will try register a EDS service if its fails this mean that the service is already registered
    m_edsIsLive = !QDBusConnection::sessionBus().registerService(evolutionServiceName);
    if (!m_edsIsLive) {
        // if we succeed we need to unregister it
        QDBusConnection::sessionBus().unregisterService(evolutionServiceName);
    }

    m_edsWatcher = new QDBusServiceWatcher(evolutionServiceName,
                                           QDBusConnection::sessionBus(),
                                           QDBusServiceWatcher::WatchForOwnerChange,
                                           this);
    connect(m_edsWatcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)),
            this, SLOT(onEdsServiceOwnerChanged(QString,QString,QString)));


    // WORKAROUND: Will ceck for EDS after the service get ready
    connect(this, SIGNAL(readyChanged()), SLOT(checkForEds()));
}

SourceList AddressBook::availableSources(const QDBusMessage &message)
{
    getSource(message, false);
    return SourceList();
}

Source AddressBook::source(const QDBusMessage &message)
{
    getSource(message, true);
    return Source();
}

Source AddressBook::createSource(const QString &sourceName,
                                 uint accountId,
                                 bool setAsPrimary,
                                 const QDBusMessage &message)
{
    CreateSourceData *data = new CreateSourceData;
    data->m_addressbook = this;
    data->m_message = message;
    data->m_sourceName = sourceName;
    data->m_setAsPrimary = setAsPrimary;
    data->m_accountId = accountId;

    FolksPersonaStore *store = folks_individual_aggregator_get_primary_store(m_individualAggregator);
    QString personaStoreTypeId("dummy");
    if (store) {
        personaStoreTypeId = QString::fromUtf8(folks_persona_store_get_type_id(store));
    }
    if (personaStoreTypeId == "dummy") {
        FolksBackendStore *backendStore = folks_backend_store_dup();
        FolksBackend *dummy = folks_backend_store_dup_backend_by_name(backendStore, "dummy");

        GeeMap *stores = folks_backend_get_persona_stores(dummy);
        GeeSet *storesKeys = gee_map_get_keys(stores);
        GeeSet *storesIds = (GeeSet*) gee_hash_set_new(G_TYPE_STRING,
                                                       (GBoxedCopyFunc) g_strdup, g_free,
                                                       NULL, NULL, NULL, NULL, NULL, NULL);

        gee_collection_add_all(GEE_COLLECTION(storesIds), GEE_COLLECTION(storesKeys));
        gee_collection_add(GEE_COLLECTION(storesIds), sourceName.toUtf8().constData());
        folks_backend_set_persona_stores(dummy, storesIds);

        g_object_unref(storesIds);
        g_object_unref(backendStore);
        g_object_unref(dummy);

        Source src(sourceName, sourceName, QString(), QString(), data->m_accountId, false, false);
        QDBusMessage reply = message.createReply(QVariant::fromValue<Source>(src));
        QDBusConnection::sessionBus().send(reply);
    } else if (personaStoreTypeId == "eds") {
        data->m_sourceId = QUuid::createUuid().toString().remove("{").remove("}");
        ESourceRegistry *registry = NULL;
        ESource *source = create_esource_from_data(*data, &registry);
        if (source) {
            data->m_source = source;
            e_source_registry_commit_source(registry,
                                            source,
                                            NULL,
                                            (GAsyncReadyCallback) AddressBook::createSourceDone,
                                            data);
        } else {
            delete data;
            QDBusMessage reply = message.createReply(QVariant::fromValue<Source>(Source()));
            QDBusConnection::sessionBus().send(reply);
        }
    } else {
        qWarning() << "Not supported, create sources on persona store with type id:" << personaStoreTypeId;
        delete data;
        QDBusMessage reply = message.createReply(QVariant::fromValue<Source>(Source()));
        QDBusConnection::sessionBus().send(reply);
    }
    return Source();
}

SourceList AddressBook::updateSources(const SourceList &sources, const QDBusMessage &message)
{
    FolksPersonaStore *store = folks_individual_aggregator_get_primary_store(m_individualAggregator);
    QString personaStoreTypeId("dummy");

    if (store) {
        personaStoreTypeId = QString::fromUtf8(folks_persona_store_get_type_id(store));
    }

    if (personaStoreTypeId == "eds") {
        UpdateSourceData *data = new UpdateSourceData;
        data->m_toUpdate = sources;
        data->m_registry = 0;
        data->m_message = message;
        data->m_addressbook = this;
        data->m_result = SourceList();
        updateSourcesEDS(data);
    } else {
        qWarning() << "Not supported, update sources on persona store with type id:" << personaStoreTypeId;
        QDBusMessage reply = message.createReply(QVariant::fromValue<SourceList>(SourceList()));
        QDBusConnection::sessionBus().send(reply);
    }
    return SourceList();
}

void AddressBook::updateSourcesEDS(void *data)
{
    Source source;
    ESource *eSource = NULL;
    UpdateSourceData *uData = static_cast<UpdateSourceData*>(data);

    if (uData->m_toUpdate.isEmpty()) {
         goto operation_done;
    }

    if (uData->m_registry == 0) {
        GError *gError = 0;
        uData->m_registry = e_source_registry_new_sync(NULL, &gError);
        if (gError) {
            qWarning() << "Fail to create source registry" << gError->message;
            g_error_free(gError);
            goto operation_done;
        }
    }

    source = uData->m_toUpdate.takeFirst();
    eSource = e_source_registry_ref_source(uData->m_registry, source.id().toUtf8().data());
    if (eSource) {
        // set as primary if necessary
        if (source.isPrimary()) {
            e_source_registry_set_default_address_book(uData->m_registry, eSource);
        }

        e_source_set_display_name(eSource, source.displayLabel().toUtf8().data());
        if (source.accountId() > 0) {
            ESourceUbuntu *ubuntu_ex = E_SOURCE_UBUNTU(e_source_get_extension(eSource, E_SOURCE_EXTENSION_UBUNTU));
            e_source_ubuntu_set_account_id(ubuntu_ex, source.accountId());
            e_source_ubuntu_set_application_id(ubuntu_ex, source.applicationId().toUtf8().data());
        }

        uData->m_currentSource = eSource;
        e_source_registry_commit_source(uData->m_registry,
                                        eSource,
                                        NULL,
                                        (GAsyncReadyCallback) AddressBook::updateSourceEDSDone,
                                        data);
    } else {
        // next source
        updateSourcesEDS(data);
    }
    return;

operation_done:
    SourceList result(uData->m_result);
    QDBusMessage reply = uData->m_message.createReply(QVariant::fromValue<SourceList>(result));
    QDBusConnection::sessionBus().send(reply);

    if (uData->m_registry) {
        g_object_unref (uData->m_registry);
    }
    delete uData;
}

void AddressBook::updateSourceEDSDone(GObject *registry,
                                      GAsyncResult *res,
                                      void *data)
{
    UpdateSourceData *uData = static_cast<UpdateSourceData*>(data);
    GError *error = 0;

    e_source_registry_commit_source_finish(E_SOURCE_REGISTRY(registry), res, &error);
    if (error) {
        qWarning() << "Failed to update source" << error->message;
        g_error_free(error);
    } else {
        uData->m_result.append(parseEDSSource(uData->m_registry, uData->m_currentSource));
    }

    g_object_unref(uData->m_currentSource);
    uData->m_addressbook->updateSourcesEDS(data);
}

void AddressBook::sourceEDSChanged(ESourceRegistry *registry, ESource *source, AddressBook *self)
{
    Q_EMIT self->sourcesChanged();
}

void AddressBook::removeSource(const QString &sourceId, const QDBusMessage &message)
{
    FolksBackendStore *bs = folks_backend_store_dup();
    FolksBackend *backend = folks_backend_store_dup_backend_by_name(bs, "eds");
    bool error = false;
    if (backend) {
        GeeMap *storesMap = folks_backend_get_persona_stores(backend);
        GeeCollection *stores = gee_map_get_values(storesMap);
        GeeIterator *i = gee_iterable_iterator(GEE_ITERABLE(stores));
        RemoveSourceData *rData = 0;
        while (gee_iterator_next(i)) {
            FolksPersonaStore *ps = FOLKS_PERSONA_STORE(gee_iterator_get(i));
            if (g_strcmp0(folks_persona_store_get_id(ps), sourceId.toUtf8().constData()) == 0) {
                ESource *src = edsf_persona_store_get_source(EDSF_PERSONA_STORE(ps));
                if (src) {
                    e_source_set_enabled(src, FALSE);
                    rData = new RemoveSourceData;
                    rData->m_addressbook = this;
                    rData->m_message = message;
                    e_source_write(src, NULL, AddressBook::removeSourceDone, rData);
                }
                g_object_unref(ps);
                break;
            }
            g_object_unref(ps);
        }

        g_object_unref(backend);
        g_object_unref(stores);

        if (!rData) {
            qWarning() << "Source not found to remove:" << sourceId;
            error = true;
        }
    } else {
        qWarning() << "Fail to create eds backend during the source removal:" << sourceId;
        error = true;
    }

    g_object_unref(bs);

    if (error) {
        QDBusMessage reply = message.createReply(false);
        QDBusConnection::sessionBus().send(reply);
    }
}

void AddressBook::removeSourceDone(GObject *source,
                                   GAsyncResult *res,
                                   void *data)
{
    GError *error = 0;
    bool result = true;
    e_source_write_finish(E_SOURCE(source), res, &error);
    if (error) {
        qWarning() << "Fail to remove source" << error->message;
        g_error_free(error);
        result = false;
    }

    RemoveSourceData *rData = static_cast<RemoveSourceData*>(data);
    QDBusMessage reply = rData->m_message.createReply(result);
    QDBusConnection::sessionBus().send(reply);
    delete rData;
}

void AddressBook::folksUnprepared(GObject *source, GAsyncResult *res, void *data)
{
    AddressBook *self = static_cast<AddressBook*>(data);
    GError *error = NULL;
    folks_individual_aggregator_unprepare_finish(FOLKS_INDIVIDUAL_AGGREGATOR(source), res, &error);
    if (error) {
        qWarning() << "Fail to unprepare folks:" << error->message;
        g_error_free(error);
    }
    g_clear_object(&self->m_individualAggregator);

    qDebug() << "Folks unprepared" << (void*) self->m_individualAggregator;
    if (self->m_isAboutToQuit) {
        self->continueShutdown();
    } else {
        self->unprepareEds();
    }
}

void AddressBook::edsUnprepared(GObject *source, GAsyncResult *res, void *data)
{
    GError *error = NULL;
    folks_backend_unprepare_finish(FOLKS_BACKEND(source), res, &error);
    if (error) {
        qWarning() << "Fail to unprepare eds:" << error->message;
        g_error_free(error);
    }
    qDebug() << "EDS unprepared";
    folks_backend_prepare(FOLKS_BACKEND(source),
                          AddressBook::edsPrepared,
                          data);
}

void AddressBook::edsPrepared(GObject *source, GAsyncResult *res, void *data)
{
    AddressBook *self = static_cast<AddressBook*>(data);
    GError *error = NULL;
    folks_backend_prepare_finish(FOLKS_BACKEND(source), res, &error);
    if (error) {
        qWarning() << "Fail to prepare eds:" << error->message;
        g_error_free(error);
    }
    // remove reference created by parent function
    g_object_unref(source);
    // will start folks again
    self->prepareFolks();
}

void AddressBook::onSafeModeMessageActivated(MessagingMenuMessage *message,
                                             const char *actionId,
                                             GVariant *param,
                                             AddressBook *self)
{
    if (self->m_messagingMenu) {
        if (self->m_messagingMenuMessage) {
             messaging_menu_app_remove_message(self->m_messagingMenu, self->m_messagingMenuMessage);
             g_object_unref(self->m_messagingMenuMessage);
             self->m_messagingMenuMessage = 0;
        }

        messaging_menu_app_unregister(self->m_messagingMenu);
        g_object_unref(self->m_messagingMenu);
        self->m_messagingMenu = 0;
    }

    url_dispatch_send("application:///address-book-app.desktop", NULL, NULL);
}

Source AddressBook::parseEDSSource(ESourceRegistry *registry, ESource *eSource)
{
    if (eSource) {
        guint accountId;
        QString applicationId;
        QString providerName;

        // ubuntu extension info
        if (e_source_has_extension(eSource, E_SOURCE_EXTENSION_UBUNTU)) {
            ESourceUbuntu *ubuntu_ex = E_SOURCE_UBUNTU(e_source_get_extension(eSource, E_SOURCE_EXTENSION_UBUNTU));
            accountId = e_source_ubuntu_get_account_id(ubuntu_ex);
            applicationId = QString::fromUtf8(e_source_ubuntu_get_application_id(ubuntu_ex));
            providerName = QString::fromUtf8(e_source_ubuntu_get_account_provider(ubuntu_ex));
        }

        // check primary
        ESource *defaultAddressBook = e_source_registry_ref_default_address_book(registry);
        bool isPrimary = e_source_equal(defaultAddressBook, eSource);
        g_object_unref (defaultAddressBook);

        return Source(QString::fromUtf8(e_source_get_uid(eSource)),
                      QString::fromUtf8(e_source_get_display_name(eSource)),
                      applicationId,
                      providerName,
                      accountId,
                      !e_source_get_writable(eSource),
                      isPrimary);
    }

    return Source();
}


bool AddressBook::isSafeMode()
{
    QByteArray envSafeMode = qgetenv(ADDRESS_BOOK_SAFE_MODE);
    if (!envSafeMode.isEmpty()) {
        return (envSafeMode.toLower() == "on" ? true : false);
    } else {
        return m_settings.value(SETTINGS_SAFE_MODE_KEY, false).toBool();
    }
}

void AddressBook::setSafeMode(bool flag)
{
    QByteArray envSafeMode = qgetenv(ADDRESS_BOOK_SAFE_MODE);
    if (!envSafeMode.isEmpty()) {
        return;
    }

    if (m_settings.value(SETTINGS_SAFE_MODE_KEY, false).toBool() != flag) {
        m_settings.setValue(SETTINGS_SAFE_MODE_KEY, flag);
        if (!flag) {
            // make all contacts visible
            Q_FOREACH(ContactEntry *entry, m_contacts->values()) {
                QIndividual *i = entry->individual();
                if (!i->isVisible()) {
                    i->setVisible(true);
                }
            }
            // clear invisible sources list
            m_settings.setValue(SETTINGS_INVISIBLE_SOURCES, QStringList());
        }
        m_settings.sync();
        // avoid send a ton of signals since the service will be reseted after the
        // 'safeModeChanged' signal
        m_notifyContactUpdate->clear();
        Q_EMIT safeModeChanged();
    }
}

void AddressBook::createSourceDone(GObject *source,
                                   GAsyncResult *res,
                                   void *data)
{
    CreateSourceData *cData = static_cast<CreateSourceData*>(data);
    GError *error = 0;
    Source src;
    e_source_registry_commit_source_finish(E_SOURCE_REGISTRY(source), res, &error);
    if (error) {
        qWarning() << "Failed to create source" << error->message;
        g_error_free(error);
    } else {
        // set as primary if necessary
        if (cData->m_setAsPrimary) {
            e_source_registry_set_default_address_book(E_SOURCE_REGISTRY(source), cData->m_source);
        }
        src = Source(cData->m_sourceId,
                     cData->m_sourceName,
                     cData->m_applicationId,
                     cData->m_providerName,
                     cData->m_accountId,
                     false,
                     cData->m_setAsPrimary);
        // if in safe mode source will be invisible, we use that to avoid invalid states
        if (isSafeMode()) {
            qDebug() << "Source will be invisible until safe mode is gone" << cData->m_sourceId << e_source_get_uid(cData->m_source);
            QStringList iSources = cData->m_addressbook->m_settings.value(SETTINGS_INVISIBLE_SOURCES).toStringList();
            iSources << e_source_get_uid(cData->m_source);
            cData->m_addressbook->m_settings.setValue(SETTINGS_INVISIBLE_SOURCES, iSources);
            cData->m_addressbook->m_settings.sync();
        }
    }
    g_object_unref(source);
    QDBusMessage reply = cData->m_message.createReply(QVariant::fromValue<Source>(src));
    QDBusConnection::sessionBus().send(reply);
    delete cData;
}

void AddressBook::getSource(const QDBusMessage &message, bool onlyTheDefault)
{
    FolksBackendStore *backendStore = folks_backend_store_dup();
    QDBusMessage *msg = new QDBusMessage(message);

    if (folks_backend_store_get_is_prepared(backendStore)) {
        if (onlyTheDefault) {
            availableSourcesDoneListDefaultSource(backendStore, 0, msg);
        } else {
            availableSourcesDoneListAllSources(backendStore, 0, msg);
        }
    } else {
        if (onlyTheDefault) {
            folks_backend_store_prepare(backendStore,
                                        (GAsyncReadyCallback) availableSourcesDoneListDefaultSource,
                                        msg);
        } else {
            folks_backend_store_prepare(backendStore,
                                        (GAsyncReadyCallback) availableSourcesDoneListAllSources,
                                        msg);
        }
    }

    g_object_unref(backendStore);
}

void AddressBook::availableSourcesDoneListAllSources(FolksBackendStore *backendStore,
                                                     GAsyncResult *res,
                                                     QDBusMessage *msg)
{
    SourceList list = availableSourcesDoneImpl(backendStore, res);
    QDBusMessage reply = msg->createReply(QVariant::fromValue<SourceList>(list));
    QDBusConnection::sessionBus().send(reply);
    delete msg;
}

void AddressBook::availableSourcesDoneListDefaultSource(FolksBackendStore *backendStore,
                                                        GAsyncResult *res,
                                                        QDBusMessage *msg)
{
    Source defaultSource;
    SourceList list = availableSourcesDoneImpl(backendStore, res);
    if (list.count() > 0) {
        defaultSource = list.first();
    }
    QDBusMessage reply = msg->createReply(QVariant::fromValue<Source>(defaultSource));
    QDBusConnection::sessionBus().send(reply);
    delete msg;
}

SourceList AddressBook::availableSourcesDoneImpl(FolksBackendStore *backendStore, GAsyncResult *res)
{
    if (res) {
        folks_backend_store_prepare_finish(backendStore, res);
    }
    static QStringList backendBlackList;

    // these backends are not fully supported yet
    if (backendBlackList.isEmpty()) {
        backendBlackList << "telepathy"
                         << "bluez"
                         << "ofono"
                         << "key-file";
    }

    GeeCollection *backends = folks_backend_store_list_backends(backendStore);

    SourceList result;

    GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(backends));
    while(gee_iterator_next(iter)) {
        FolksBackend *backend = FOLKS_BACKEND(gee_iterator_get(iter));
        QString backendName = QString::fromUtf8(folks_backend_get_name(backend));
        if (backendBlackList.contains(backendName)) {
            continue;
        }

        GeeMap *stores = folks_backend_get_persona_stores(backend);
        GeeCollection *values =  gee_map_get_values(stores);
        GeeIterator *backendIter = gee_iterable_iterator(GEE_ITERABLE(values));

        while(gee_iterator_next(backendIter)) {
            FolksPersonaStore *store = FOLKS_PERSONA_STORE(gee_iterator_get(backendIter));

            QString id = QString::fromUtf8(folks_persona_store_get_id(store));
            QString displayName = folks_persona_store_get_display_name(store);
            bool canWrite = folks_persona_store_get_can_add_personas(store) &&
                            folks_persona_store_get_can_remove_personas(store);
            bool isPrimary = folks_persona_store_get_is_primary_store(store);

            uint accountId = 0;
            QString applicationId;
            QString providerName;


            // FIXME: Due a bug on Folks we can not rely on folks_persona_store_get_is_primary_store
            // see main.cpp:68
            if (strcmp(folks_backend_get_name(backend), "eds") == 0) {
                GError *error = 0;
                ESourceRegistry *r = e_source_registry_new_sync(NULL, &error);
                if (error) {
                    qWarning() << "Failt to check default source:" << error->message;
                    g_error_free(error);
                } else {
                    ESource *defaultSource = e_source_registry_ref_default_address_book(r);
                    ESource *source = edsf_persona_store_get_source(EDSF_PERSONA_STORE(store));
                    displayName = QString::fromUtf8(e_source_get_display_name(source));
                    isPrimary = e_source_equal(defaultSource, source);
                    g_object_unref(defaultSource);
                    g_object_unref(r);

                    if (e_source_has_extension(source, E_SOURCE_EXTENSION_UBUNTU)) {
                        ESourceUbuntu *ubuntu_ex = E_SOURCE_UBUNTU(e_source_get_extension(source, E_SOURCE_EXTENSION_UBUNTU));
                        if (ubuntu_ex) {
                            applicationId = QString::fromUtf8(e_source_ubuntu_get_application_id(ubuntu_ex));
                            providerName = QString::fromUtf8(e_source_ubuntu_get_account_provider(ubuntu_ex));
                            accountId = e_source_ubuntu_get_account_id(ubuntu_ex);
                        }
                    } else {
                        qDebug() << "SOURCE DOES NOT HAVE UBUNTU EXTENSION:"
                                 << displayName;
                    }
                }
            }

            // If running on safe mode only the system-address-book is writable
            if (isSafeMode() && (id != "system-address-book")) {
                qDebug() << "Running safe mode for source" << id << displayName;
                canWrite = false;
            }

            result.append(Source(id, displayName, applicationId, providerName, accountId, !canWrite, isPrimary));
            g_object_unref(store);
        }

        g_object_unref(backendIter);
        g_object_unref(backend);
        g_object_unref(values);
    }
    g_object_unref(iter);
    return result;
}

QString AddressBook::createContact(const QString &contact, const QString &source, const QDBusMessage &message)
{
    ContactEntry *entry = m_contacts->valueFromVCard(contact);
    if (entry) {
        qWarning() << "Contact exists";
    } else {
        QContact qcontact = VCardParser::vcardToContact(contact);
        if (!qcontact.isEmpty()) {
            GHashTable *details = QIndividual::parseDetails(qcontact);
            Q_ASSERT(details);
            CreateContactData *data = new CreateContactData;
            data->m_message = message;
            data->m_addressbook = this;
            data->m_contact = qcontact;
            FolksPersonaStore *store = getFolksStore(source);
            folks_individual_aggregator_add_persona_from_details(m_individualAggregator,
                                                                 NULL, //parent
                                                                 store,
                                                                 details,
                                                                 (GAsyncReadyCallback) createContactDone,
                                                                 (void*) data);
            g_hash_table_destroy(details);
            g_object_unref(store);
            return "";
        }
    }

    if (message.type() != QDBusMessage::InvalidMessage) {
        QDBusMessage reply = message.createReply(QString());
        QDBusConnection::sessionBus().send(reply);
    }
    return "";
}

FolksPersonaStore * AddressBook::getFolksStore(const QString &source)
{
    QString sourceId(source);
    FolksPersonaStore *result = 0;

    // if source is empty we try use EDS default source
    if (source.isEmpty()) {
        GError *gError = NULL;
        ESourceRegistry *registry = e_source_registry_new_sync (NULL, &gError);
        if (gError) {
            qWarning() << "Fail to find EDS default source";
        } else {
            ESource *defaultAB = e_source_registry_ref_default_address_book(registry);
            if (defaultAB) {
                sourceId = QString::fromUtf8(e_source_get_uid(defaultAB));
            }
            g_object_unref(registry);
        }
    }

    if (!sourceId.isEmpty()) {
        FolksBackendStore *backendStore = folks_backend_store_dup();
        GeeCollection *backends = folks_backend_store_list_backends(backendStore);

        GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(backends));
        while((result == 0) && gee_iterator_next(iter)) {
            FolksBackend *backend = FOLKS_BACKEND(gee_iterator_get(iter));
            GeeMap *stores = folks_backend_get_persona_stores(backend);
            GeeCollection *values =  gee_map_get_values(stores);
            GeeIterator *storeIter = gee_iterable_iterator(GEE_ITERABLE(values));

            while(gee_iterator_next(storeIter)) {
                FolksPersonaStore *store = FOLKS_PERSONA_STORE(gee_iterator_get(storeIter));

                QString id = QString::fromUtf8(folks_persona_store_get_id(store));
                if (id == sourceId) {
                    result = store;
                    break;
                }
                g_object_unref(store);
            }

            g_object_unref(storeIter);
            g_object_unref(backend);
            g_object_unref(values);
        }
        g_object_unref(iter);
        g_object_unref(backendStore);
    }

    if (!result) {
        result = folks_individual_aggregator_get_primary_store(m_individualAggregator);
        Q_ASSERT(result);
        g_object_ref(result);
    }

    return result;
}

QString AddressBook::linkContacts(const QStringList &contacts)
{
    //TODO
    return "";
}

View *AddressBook::query(const QString &clause, const QString &sort, int maxCount, bool showInvisible, const QStringList &sources)
{
    View *view = new View(clause, sort, maxCount, showInvisible, sources, m_ready ? m_contacts : 0, this);
    m_views << view;
    connect(view, SIGNAL(closed()), this, SLOT(viewClosed()));
    return view;
}

void AddressBook::viewClosed()
{
    m_views.remove(qobject_cast<View*>(QObject::sender()));
}

void AddressBook::individualChanged(QIndividual *individual)
{
    if (individual->isVisible()) {
        m_notifyContactUpdate->insertChangedContacts(QSet<QString>() << individual->id());
    }
}

void AddressBook::onEdsServiceOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner)
{
    if (newOwner.isEmpty()) {
        m_edsIsLive = false;
        m_isAboutToReload = true;
        qWarning() << "EDS died: restarting service" << m_individualsChangedDetailedId;
        unprepareFolks();
    } else {
        m_edsIsLive = true;
    }
}

void AddressBook::onSafeModeChanged()
{
    GIcon *icon = g_themed_icon_new("address-book-app");

    if (m_messagingMenu == 0) {
        m_messagingMenu = messaging_menu_app_new("address-book-app.desktop");
        messaging_menu_app_register(m_messagingMenu);
        messaging_menu_app_append_source(m_messagingMenu, MESSAGING_MENU_SOURCE_ID, icon, C::gettext("Address book service"));
    }

    if (m_messagingMenuMessage) {
        messaging_menu_app_remove_message(m_messagingMenu, m_messagingMenuMessage);
        g_object_unref (m_messagingMenuMessage);
        m_messagingMenuMessage = 0;
    }

    if (isSafeMode()) {
        m_messagingMenuMessage = messaging_menu_message_new("address-book-service-safe-mode",
                                                            icon,
                                                            C::gettext("Update required"),
                                                            NULL,
                                                            C::gettext("Only local contacts will be editable until the contact sync upgrade is complete."),
                                                            QDateTime::currentMSecsSinceEpoch() * 1000); // the value is expected to be in microseconds
    } else {
        m_messagingMenuMessage = messaging_menu_message_new("address-book-service-safe-mode",
                                                            icon,
                                                            C::gettext("Update complete"),
                                                            NULL,
                                                            C::gettext("Your Contact sync upgrade is complete."),
                                                            QDateTime::currentMSecsSinceEpoch() * 1000); // the value is expected to be in microseconds
    }

    g_signal_connect(m_messagingMenuMessage, "activate", G_CALLBACK(&AddressBook::onSafeModeMessageActivated), this);
    messaging_menu_app_append_message(m_messagingMenu, m_messagingMenuMessage, MESSAGING_MENU_SOURCE_ID, true);
    g_object_unref(icon);
}

int AddressBook::removeContacts(const QStringList &contactIds, const QDBusMessage &message)
{
    RemoveContactsData *data = new RemoveContactsData;
    data->m_addressbook = this;
    data->m_message = message;
    data->m_request = contactIds;
    data->m_sucessCount = 0;
    data->m_softRemoval = true;
    removeContactDone(0, 0, data);
    return 0;
}

void AddressBook::removeContactDone(FolksIndividualAggregator *individualAggregator,
                                    GAsyncResult *result,
                                    void *data)
{
    GError *error = 0;
    RemoveContactsData *removeData = static_cast<RemoveContactsData*>(data);

    if (result) {
        folks_individual_aggregator_remove_individual_finish(individualAggregator, result, &error);
        if (error) {
            qWarning() << "Fail to remove contact:" << error->message;
            g_error_free(error);
        } else {
            removeData->m_sucessCount++;
        }
    }


    if (!removeData->m_request.isEmpty()) {
        QString contactId = removeData->m_request.takeFirst();
        ContactEntry *entry = removeData->m_addressbook->m_contacts->value(contactId);
        if (entry) {
            if (removeData->m_softRemoval && entry->individual()->markAsDeleted()) {
                removeContactDone(individualAggregator, 0, data);
                // since this will not be removed we need to send a removal singal
                removeData->m_addressbook->m_notifyContactUpdate->insertRemovedContacts(QSet<QString>() << entry->individual()->id());
            } else {
                folks_individual_aggregator_remove_individual(individualAggregator,
                                                              entry->individual()->individual(),
                                                              (GAsyncReadyCallback) removeContactDone,
                                                              data);
            }
        } else {
            removeContactDone(individualAggregator, 0, data);
        }
    } else {
        QDBusMessage reply = removeData->m_message.createReply(removeData->m_sucessCount);
        QDBusConnection::sessionBus().send(reply);
        delete removeData;
    }
}

QStringList AddressBook::sortFields()
{
    return SortClause::supportedFields();
}

bool AddressBook::unlinkContacts(const QString &parent, const QStringList &contacts)
{
    //TODO
    return false;
}

bool AddressBook::isReady() const
{
    return m_ready && m_edsIsLive;
}

QStringList AddressBook::updateContacts(const QStringList &contacts, const QDBusMessage &message)
{
    //TODO: support multiple update contacts calls
    Q_ASSERT(m_updateCommandPendingContacts.isEmpty());
    if (!processUpdates()) {
        qWarning() << "Fail to process pending updates";
        QDBusMessage reply = m_updateCommandReplyMessage.createReply(QStringList());
        QDBusConnection::sessionBus().send(reply);
        return QStringList();
    }

    m_updatedIds.clear();
    m_updateCommandReplyMessage = message;
    m_updateCommandResult = contacts;
    m_updateCommandPendingContacts = contacts;

    updateContactsDone("", "");
    return QStringList();
}

void AddressBook::purgeContacts(const QDateTime &since, const QString &sourceId, const QDBusMessage &message)
{
    RemoveContactsData *data = new RemoveContactsData;
    data->m_addressbook = this;
    data->m_message = message;
    data->m_sucessCount = 0;
    data->m_softRemoval = false;

    Q_FOREACH(const ContactEntry *entry, m_contacts->values()) {
        if (entry->individual()->deletedAt() > since) {
            QContactSyncTarget syncTarget = entry->individual()->contact().detail<QContactSyncTarget>();
            if (syncTarget.value(QContactSyncTarget::FieldSyncTarget + 1).toString() == sourceId) {
                data->m_request << entry->individual()->id();
            }
        }
    }

    removeContactDone(0, 0, data);
}

void AddressBook::updateContactsDone(const QString &contactId,
                                     const QString &error)
{
    int currentContactIndex = m_updateCommandResult.size() - m_updateCommandPendingContacts.size() - 1;

    if (!error.isEmpty()) {
        // update the result with the error
        if (currentContactIndex >= 0 &&
            currentContactIndex < m_updateCommandResult.size()) {
            m_updateCommandResult[currentContactIndex] = error;
        } else {
            qWarning() << "Invalid contact changed index" << currentContactIndex <<
                          "Contact list size" << m_updateCommandResult.size();
        }
    } else if (!contactId.isEmpty()){
        // update the result with the new contact info
        ContactEntry *entry = m_contacts->value(contactId);
        Q_ASSERT(entry);
        m_updatedIds << contactId;
        QContact contact = entry->individual()->contact();
        QString vcard = VCardParser::contactToVcard(contact);
        if (!vcard.isEmpty()) {
            m_updateCommandResult[currentContactIndex] = vcard;
        } else {
            m_updateCommandResult[currentContactIndex] = "";
        }
        // update contact position on map
        m_contacts->updatePosition(entry);
    }

    if (!m_updateCommandPendingContacts.isEmpty()) {
        QString vCard = m_updateCommandPendingContacts.takeFirst();
        QContact newContact = VCardParser::vcardToContact(vCard);
        ContactEntry *entry = m_contacts->value(newContact.detail<QContactGuid>().guid());
        if (entry) {
            entry->individual()->update(newContact, this,
                                        SLOT(updateContactsDone(QString,QString)));
        } else {
            qWarning() << "Contact not found for update:" << vCard;
            updateContactsDone("", "Contact not found!");
        }
    } else {
        QDBusMessage reply = m_updateCommandReplyMessage.createReply(m_updateCommandResult);
        QDBusConnection::sessionBus().send(reply);

        // notify about the changes
        m_notifyContactUpdate->insertChangedContacts(m_updatedIds.toSet());

        // clear command data
        m_updatedIds.clear();
        m_updateCommandResult.clear();
        m_updateCommandReplyMessage = QDBusMessage();
        m_updateLock.unlock();
    }
}

QString AddressBook::removeContact(FolksIndividual *individual, bool *visible)
{
    QString contactId = QString::fromUtf8(folks_individual_get_id(individual));
    ContactEntry *ci = m_contacts->take(contactId);
    if (ci) {
        *visible = ci->individual()->isVisible();
        delete ci;
        return contactId;
    }
    return QString();
}

QString AddressBook::addContact(FolksIndividual *individual, bool visible)
{
    QString id = QString::fromUtf8(folks_individual_get_id(individual));
    ContactEntry *entry = m_contacts->value(id);
    if (entry) {
        entry->individual()->setIndividual(individual);
        entry->individual()->setVisible(visible);

        // update contact position on map
        m_contacts->updatePosition(entry);
    } else {
        QIndividual *i = new QIndividual(individual, m_individualAggregator);
        i->addListener(this, SLOT(individualChanged(QIndividual*)));
        i->setVisible(visible);
        m_contacts->insert(new ContactEntry(i));
        //TODO: Notify view
    }

    return id;
}

void AddressBook::individualsChangedCb(FolksIndividualAggregator *individualAggregator,
                                       GeeMultiMap *changes,
                                       AddressBook *self)
{
    Q_UNUSED(individualAggregator);

    QSet<QString> removedIds;
    QSet<QString> addedIds;
    QSet<QString> updatedIds;
    QStringList invisibleSources;

    if (isSafeMode()) {
        invisibleSources = self->m_settings.value(SETTINGS_INVISIBLE_SOURCES).toStringList();
    }

    GeeSet *removed = gee_multi_map_get_keys(changes);
    GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(removed));
    while(gee_iterator_next(iter)) {
        FolksIndividual *individual = FOLKS_INDIVIDUAL(gee_iterator_get(iter));
        if (!individual) {
            continue;
        }

        bool visible = true;
        QString cId = self->removeContact(individual, &visible);
        if (visible && !cId.isEmpty()) {
            removedIds << cId;
        }
        g_object_unref(individual);
    }
    g_object_unref(iter);

    GeeCollection *added = gee_multi_map_get_values(changes);
    iter = gee_iterable_iterator(GEE_ITERABLE(added));
    while(gee_iterator_next(iter)) {
        FolksIndividual *individual = FOLKS_INDIVIDUAL(gee_iterator_get(iter));

        if (!individual) {
            continue;
        }

        QString id = QString::fromUtf8(folks_individual_get_id(individual));
        if (addedIds.contains(id)) {
            g_object_unref(individual);
            continue;
        }

        bool visible = true;
        if (!invisibleSources.isEmpty()) {
            GeeSet *personas = folks_individual_get_personas(individual);
            GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(personas));
            if (gee_iterator_next(iter)) {
                FolksPersona *persona = FOLKS_PERSONA(gee_iterator_get(iter));
                FolksPersonaStore *ps = folks_persona_get_store(persona);
                g_object_unref(persona);
                visible = !invisibleSources.contains(folks_persona_store_get_id(ps));
            }
            g_object_unref(iter);
        }

        bool exists = self->m_contacts->contains(id);
        QString cId = self->addContact(individual, visible);
        if (visible && exists) {
            updatedIds <<  cId;
        } else if (visible) {
            addedIds << cId;
        }

        g_object_unref(individual);
    }
    g_object_unref(iter);

    g_object_unref(removed);
    g_object_unref(added);

    if (!removedIds.isEmpty()) {
        self->m_notifyContactUpdate->insertRemovedContacts(removedIds);
    }

    if (!addedIds.isEmpty()) {
        self->m_notifyContactUpdate->insertAddedContacts(addedIds);
    }

    if (!updatedIds.isEmpty()) {
        self->m_notifyContactUpdate->insertChangedContacts(updatedIds);
    }
}

void AddressBook::prepareFolksDone(GObject *source,
                                      GAsyncResult *res,
                                      AddressBook *self)
{
    Q_UNUSED(source);
    Q_UNUSED(res);
    Q_UNUSED(self);
}

void AddressBook::createContactDone(FolksIndividualAggregator *individualAggregator,
                                    GAsyncResult *res,
                                    void *data)
{
    CreateContactData *createData = static_cast<CreateContactData*>(data);

    FolksPersona *persona;
    GError *error = NULL;
    QDBusMessage reply;
    persona = folks_individual_aggregator_add_persona_from_details_finish(individualAggregator, res, &error);
    if (error != NULL) {
        qWarning() << "Failed to create individual from contact:" << error->message;
        reply = createData->m_message.createErrorReply("Failed to create individual from contact", error->message);
        g_clear_error(&error);
    } else if (persona == NULL) {
        qWarning() << "Failed to create individual from contact: Persona already exists";
        reply = createData->m_message.createErrorReply("Failed to create individual from contact", "Contact already exists");
    } else {
        QIndividual::setExtendedDetails(persona,
                                        createData->m_contact.details(QContactExtendedDetail::Type),
                                        QDateTime::currentDateTime());
        FolksIndividual *individual = folks_persona_get_individual(persona);
        ContactEntry *entry = createData->m_addressbook->m_contacts->value(QString::fromUtf8(folks_individual_get_id(individual)));
        if (entry) {
            // We will need to reload contact due the extended details
            entry->individual()->flush();
            QString vcard = VCardParser::contactToVcard(entry->individual()->contact());
            if (createData->m_message.type() != QDBusMessage::InvalidMessage) {
                reply = createData->m_message.createReply(vcard);
            }
        } else if (createData->m_message.type() != QDBusMessage::InvalidMessage) {
            reply = createData->m_message.createErrorReply("", "Failed to retrieve the new contact");
        }
    }
    //TODO: use dbus connection
    if (createData->m_message.type() != QDBusMessage::InvalidMessage) {
        QDBusConnection::sessionBus().send(reply);
    }
    delete createData;
}

void AddressBook::isQuiescentChanged(GObject *source, GParamSpec *param, AddressBook *self)
{
    Q_UNUSED(param);
    gboolean ready = false;
    g_object_get(source, "is-quiescent", &ready, NULL);
    if (self) {
        self->setIsReady(ready);
    }
}

void AddressBook::quitSignalHandler(int)
 {
     char a = 1;
     ::write(m_sigQuitFd[0], &a, sizeof(a));
}

bool AddressBook::processUpdates()
{
    int timeout = 10;
    while(!m_updateLock.tryLock(1000)) {
        if (timeout <= 0) {
            return false;
        }
        QCoreApplication::processEvents();
        timeout--;
    }
    return true;
}

int AddressBook::init()
{
    struct sigaction quit = { { 0 } };
    Source::registerMetaType();

    quit.sa_handler = AddressBook::quitSignalHandler;
    sigemptyset(&quit.sa_mask);
    quit.sa_flags |= SA_RESTART;

    if (sigaction(SIGQUIT, &quit, 0) > 0)
        return 1;

    return 0;
}

void AddressBook::prepareUnixSignals()
{
    if (::socketpair(AF_UNIX, SOCK_STREAM, 0, m_sigQuitFd)) {
       qFatal("Couldn't create HUP socketpair");
    }

    m_snQuit = new QSocketNotifier(m_sigQuitFd[1], QSocketNotifier::Read, this);
    connect(m_snQuit, SIGNAL(activated(int)), this, SLOT(handleSigQuit()));
}

void AddressBook::handleSigQuit()
{
    m_snQuit->setEnabled(false);
    char tmp;
    ::read(m_sigQuitFd[1], &tmp, sizeof(tmp));

    shutdown();

    m_snQuit->setEnabled(true);
}

// WORKAROUND: For some strange reason sometimes EDS does not start with the service request
// we will try to reload folks if this happen
void AddressBook::checkForEds()
{
    if (!m_ready) {
        return;
    }

    // Use maxRetry value to avoid infinite loop
    static const int maxRetry = 10;
    static int retryCount = 0;

    qDebug() << "Check for EDS attempt number " << retryCount;
    if (retryCount >= maxRetry) {
        // abort when reach the maxRetry
        qWarning() << QDateTime::currentDateTime().toString() << "Fail to start EDS the service will abort";
        QTimer::singleShot(500, this, SLOT(shutdown()));
        return;
    }
    retryCount++;

    if (!m_edsIsLive) {
        // wait some ms to restart folks, this increase 1s for each retryCount
        m_isAboutToReload = true;
        QTimer::singleShot(1000 * retryCount, this, SLOT(unprepareFolks()));
        qWarning() << QDateTime::currentDateTime().toString() << "EDS did not start, trying to reload folks";
    } else {
        retryCount = 0;
    }
}

} //namespace