summaryrefslogtreecommitdiff
path: root/TelepathyQt/account-manager.cpp
blob: 6ae628077f04d8ed4c08c996fb7bdd0dae66c0dc (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
/**
 * This file is part of TelepathyQt
 *
 * @copyright Copyright (C) 2008-2010 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2008-2010 Nokia Corporation
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt/AccountManager>

#include "TelepathyQt/_gen/account-manager.moc.hpp"
#include "TelepathyQt/_gen/cli-account-manager.moc.hpp"
#include "TelepathyQt/_gen/cli-account-manager-body.hpp"

#include "TelepathyQt/debug-internal.h"

#include <TelepathyQt/AccountCapabilityFilter>
#include <TelepathyQt/AccountFilter>
#include <TelepathyQt/AccountSet>
#include <TelepathyQt/Constants>
#include <TelepathyQt/PendingAccount>
#include <TelepathyQt/PendingComposite>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/ReadinessHelper>

#include <QQueue>
#include <QSet>
#include <QTimer>

namespace Tp
{

struct TP_QT_NO_EXPORT AccountManager::Private
{
    Private(AccountManager *parent, const AccountFactoryConstPtr &accFactory,
            const ConnectionFactoryConstPtr &connFactory,
            const ChannelFactoryConstPtr &chanFactory,
            const ContactFactoryConstPtr &contactFactory);
    ~Private();

    void init();

    static void introspectMain(Private *self);

    void checkIntrospectionCompleted();

    QSet<QString> getAccountPathsFromProp(const QVariant &prop);
    QSet<QString> getAccountPathsFromProps(const QVariantMap &props);
    void addAccountForPath(const QString &accountObjectPath);

    // Public object
    AccountManager *parent;

    // Instance of generated interface class
    Client::AccountManagerInterface *baseInterface;

    // Mandatory properties interface proxy
    Client::DBus::PropertiesInterface *properties;

    ReadinessHelper *readinessHelper;

    AccountFactoryConstPtr accFactory;
    ConnectionFactoryConstPtr connFactory;
    ChannelFactoryConstPtr chanFactory;
    ContactFactoryConstPtr contactFactory;

    // Introspection
    int reintrospectionRetries;
    bool gotInitialAccounts;
    QHash<QString, AccountPtr> incompleteAccounts;
    QHash<QString, AccountPtr> accounts;
    QStringList supportedAccountProperties;
};

static const int maxReintrospectionRetries = 5;
static const int reintrospectionRetryInterval = 3;

AccountManager::Private::Private(AccountManager *parent,
        const AccountFactoryConstPtr &accFactory, const ConnectionFactoryConstPtr &connFactory,
        const ChannelFactoryConstPtr &chanFactory, const ContactFactoryConstPtr &contactFactory)
    : parent(parent),
      baseInterface(new Client::AccountManagerInterface(parent)),
      properties(parent->interface<Client::DBus::PropertiesInterface>()),
      readinessHelper(parent->readinessHelper()),
      accFactory(accFactory),
      connFactory(connFactory),
      chanFactory(chanFactory),
      contactFactory(contactFactory),
      reintrospectionRetries(0),
      gotInitialAccounts(false)
{
    debug() << "Creating new AccountManager:" << parent->busName();

    if (accFactory->dbusConnection().name() != parent->dbusConnection().name()) {
        warning() << "  The D-Bus connection in the account factory is not the proxy connection";
    }

    if (connFactory->dbusConnection().name() != parent->dbusConnection().name()) {
        warning() << "  The D-Bus connection in the connection factory is not the proxy connection";
    }

    if (chanFactory->dbusConnection().name() != parent->dbusConnection().name()) {
        warning() << "  The D-Bus connection in the channel factory is not the proxy connection";
    }

    ReadinessHelper::Introspectables introspectables;

    // As AccountManager does not have predefined statuses let's simulate one (0)
    ReadinessHelper::Introspectable introspectableCore(
        QSet<uint>() << 0,                                           // makesSenseForStatuses
        Features(),                                                  // dependsOnFeatures
        QStringList(),                                               // dependsOnInterfaces
        (ReadinessHelper::IntrospectFunc) &Private::introspectMain,
        this);
    introspectables[FeatureCore] = introspectableCore;

    readinessHelper->addIntrospectables(introspectables);
    readinessHelper->becomeReady(Features() << FeatureCore);

    init();
}

AccountManager::Private::~Private()
{
    delete baseInterface;
}

void AccountManager::Private::init()
{
    if (!parent->isValid()) {
        return;
    }

    parent->connect(baseInterface,
            SIGNAL(AccountValidityChanged(QDBusObjectPath,bool)),
            SLOT(onAccountValidityChanged(QDBusObjectPath,bool)));
    parent->connect(baseInterface,
            SIGNAL(AccountRemoved(QDBusObjectPath)),
            SLOT(onAccountRemoved(QDBusObjectPath)));
}

void AccountManager::Private::introspectMain(AccountManager::Private *self)
{
    debug() << "Calling Properties::GetAll(AccountManager)";
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
            self->properties->GetAll(
                TP_QT_IFACE_ACCOUNT_MANAGER),
            self->parent);
    self->parent->connect(watcher,
            SIGNAL(finished(QDBusPendingCallWatcher*)),
            SLOT(gotMainProperties(QDBusPendingCallWatcher*)));
}

void AccountManager::Private::checkIntrospectionCompleted()
{
    if (!parent->isReady(FeatureCore) &&
        incompleteAccounts.size() == 0) {
        readinessHelper->setIntrospectCompleted(FeatureCore, true);
    }
}

QSet<QString> AccountManager::Private::getAccountPathsFromProp(
        const QVariant &prop)
{
    QSet<QString> set;

    ObjectPathList paths = qdbus_cast<ObjectPathList>(prop);
    if (paths.size() == 0) {
        /* maybe the AccountManager is buggy, like Mission Control
         * 5.0.beta45, and returns an array of strings rather than
         * an array of object paths? */
        QStringList wronglyTypedPaths = qdbus_cast<QStringList>(prop);
        if (wronglyTypedPaths.size() > 0) {
            warning() << "AccountManager returned wrong type for"
                "Valid/InvalidAccounts (expected 'ao', got 'as'); "
                "working around it";
            foreach (QString path, wronglyTypedPaths) {
                set << path;
            }
        }
    } else {
        foreach (const QDBusObjectPath &path, paths) {
            set << path.path();
        }
    }

    return set;
}

QSet<QString> AccountManager::Private::getAccountPathsFromProps(
        const QVariantMap &props)
{
    return getAccountPathsFromProp(props[QLatin1String("ValidAccounts")]).unite(
            getAccountPathsFromProp(props[QLatin1String("InvalidAccounts")]));
}

void AccountManager::Private::addAccountForPath(const QString &path)
{
    // Also check incompleteAccounts, because otherwise we end up introspecting an account twice
    // when getting an AccountValidityChanged signal for a new account before we get the initial
    // introspection accounts list from the GetAll return (the GetAll return function
    // unconditionally calls addAccountForPath
    if (accounts.contains(path) || incompleteAccounts.contains(path)) {
        return;
    }

    PendingReady *readyOp = accFactory->proxy(parent->busName(), path, connFactory,
            chanFactory, contactFactory);
    AccountPtr account(AccountPtr::qObjectCast(readyOp->proxy()));
    Q_ASSERT(!account.isNull());

    parent->connect(readyOp,
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onAccountReady(Tp::PendingOperation*)));
    incompleteAccounts.insert(path, account);
}

/**
 * \class AccountManager
 * \ingroup clientam
 * \headerfile TelepathyQt/account-manager.h <TelepathyQt/AccountManager>
 *
 * \brief The AccountManager class represents a Telepathy account manager.
 *
 * The remote object accessor functions on this object (allAccounts(),
 * validAccounts(), and so on) don't make any D-Bus calls; instead, they return/use
 * values cached from a previous introspection run. The introspection process
 * populates their values in the most efficient way possible based on what the
 * service implements.
 *
 * To avoid unnecessary D-Bus traffic, some accessors only return valid
 * information after AccountManager::FeatureCore has been enabled.
 * See the individual methods descriptions for more details.
 *
 * AccountManager features can be enabled by calling becomeReady()
 * with the desired set of features as an argument (currently only AccountManager::FeatureCore is
 * supported), and waiting for the resulting PendingOperation to finish.
 *
 * All accounts returned by AccountManager are guaranteed to have the features set in the
 * AccountFactory used by it ready.
 *
 * A signal is emitted to indicate that accounts are added. See newCreated() for more details.
 *
 * \section am_usage_sec Usage
 *
 * \subsection am_create_sec Creating an AccountManager object
 *
 * One way to create an AccountManager object is to just call the create method.
 * For example:
 *
 * \code AccountManagerPtr am = AccountManager::create(); \endcode
 *
 * An AccountManagerPtr object is returned, which will automatically keep
 * track of object lifetime.
 *
 * You can also provide a D-Bus connection as a QDBusConnection:
 *
 * \code AccountManagerPtr am = AccountManager::create(QDBusConnection::sessionBus()); \endcode
 *
 * \subsection am_ready_sec Making AccountManager ready to use
 *
 * An AccountManager object needs to become ready before usage, meaning that the
 * introspection process finished and the object accessors can be used.
 *
 * To make the object ready, use becomeReady() and wait for the
 * PendingOperation::finished() signal to be emitted.
 *
 * \code
 *
 * class MyClass : public QObject
 * {
 *     QOBJECT
 *
 * public:
 *     MyClass(QObject *parent = 0);
 *     ~MyClass() { }
 *
 * private Q_SLOTS:
 *     void onAccountManagerReady(Tp::PendingOperation*);
 *
 * private:
 *     AccountManagerPtr mAM;
 * };
 *
 * MyClass::MyClass(QObject *parent)
 *     : QObject(parent)
 *       mAM(AccountManager::create())
 * {
 *     connect(mAM->becomeReady(),
 *             SIGNAL(finished(Tp::PendingOperation*)),
 *             SLOT(onAccountManagerReady(Tp::PendingOperation*)));
 * }
 *
 * void MyClass::onAccountManagerReady(Tp::PendingOperation *op)
 * {
 *     if (op->isError()) {
 *         qWarning() << "Account manager cannot become ready:" <<
 *             op->errorName() << "-" << op->errorMessage();
 *         return;
 *     }
 *
 *     // AccountManager is now ready
 *     qDebug() << "All accounts:";
 *     foreach (const Tp::AccountPtr &acc, mAM->allAccounts()) {
 *         qDebug() << " path:" << acc->objectPath();
 *     }
 * }
 *
 * \endcode
 *
 * See \ref async_model, \ref shared_ptr
 */

/**
 * Feature representing the core that needs to become ready to make the
 * AccountManager object usable.
 *
 * Note that this feature must be enabled in order to use most AccountManager
 * methods.
 *
 * When calling isReady(), becomeReady(), this feature is implicitly added
 * to the requested features.
 */
const Feature AccountManager::FeatureCore = Feature(QLatin1String(AccountManager::staticMetaObject.className()), 0, true);

/**
 * Create a new AccountManager object using the given \a bus.
 *
 * The instance will use an account factory creating Tp::Account objects with Account::FeatureCore
 * ready, a connection factory creating Tp::Connection objects with no features ready, a channel
 * factory creating stock Tp::Channel subclasses, as appropriate, with no features ready, and a
 * contact factory creating Tp::Contact objects with no features ready.
 *
 * \param bus QDBusConnection to use.
 * \return An AccountManagerPtr object pointing to the newly created
 *         AccountManager object.
 */
AccountManagerPtr AccountManager::create(const QDBusConnection &bus)
{
    return AccountManagerPtr(new AccountManager(bus,
                AccountFactory::create(bus, Account::FeatureCore), ConnectionFactory::create(bus),
                ChannelFactory::create(bus), ContactFactory::create(),
                AccountManager::FeatureCore));
}

/**
 * Create a new AccountManager using QDBusConnection::sessionBus() and the given factories.
 *
 * The connection, channel and contact factories are passed to any Account objects created by this
 * account manager object. In fact, they're not used directly by AccountManager at all.
 *
 * A warning is printed if the factories are for a bus different from QDBusConnection::sessionBus().
 *
 * \param accountFactory The account factory to use.
 * \param connectionFactory The connection factory to use.
 * \param channelFactory The channel factory to use.
 * \param contactFactory The contact factory to use.
 * \return An AccountManagerPtr object pointing to the newly created
 *         AccountManager object.
 */
AccountManagerPtr AccountManager::create(const AccountFactoryConstPtr &accountFactory,
        const ConnectionFactoryConstPtr &connectionFactory,
        const ChannelFactoryConstPtr &channelFactory,
        const ContactFactoryConstPtr &contactFactory)
{
    return AccountManagerPtr(new AccountManager(QDBusConnection::sessionBus(),
                accountFactory, connectionFactory, channelFactory, contactFactory,
                AccountManager::FeatureCore));
}

/**
 * Create a new AccountManager using the given \a bus and the given factories.
 *
 * The connection, channel and contact factories are passed to any Account objects created by this
 * account manager object. In fact, they're not used directly by AccountManager at all.
 *
 * A warning is printed if the factories are not for \a bus.
 *
 * \param bus QDBusConnection to use.
 * \param accountFactory The account factory to use.
 * \param connectionFactory The connection factory to use.
 * \param channelFactory The channel factory to use.
 * \param contactFactory The contact factory to use.
 * \return An AccountManagerPtr object pointing to the newly created
 *         AccountManager object.
 */
AccountManagerPtr AccountManager::create(const QDBusConnection &bus,
        const AccountFactoryConstPtr &accountFactory,
        const ConnectionFactoryConstPtr &connectionFactory,
        const ChannelFactoryConstPtr &channelFactory,
        const ContactFactoryConstPtr &contactFactory)
{
    return AccountManagerPtr(new AccountManager(bus,
                accountFactory, connectionFactory, channelFactory, contactFactory,
                AccountManager::FeatureCore));
}

/**
 * Construct a new AccountManager object using the given \a bus and the given factories.
 *
 * The connection, channel and contact factories are passed to any Account objects created by this
 * account manager object. In fact, they're not used directly by AccountManager at all.
 *
 * A warning is printed if the factories are not for \a bus.
 *
 * \param bus QDBusConnection to use.
 * \param accountFactory The account factory to use.
 * \param connectionFactory The connection factory to use.
 * \param channelFactory The channel factory to use.
 * \param contactFactory The contact factory to use.
 * \param coreFeature The core feature of the Account subclass. The corresponding introspectable
 * should depend on AccountManager::FeatureCore.
 */
AccountManager::AccountManager(const QDBusConnection &bus,
        const AccountFactoryConstPtr &accountFactory,
        const ConnectionFactoryConstPtr &connectionFactory,
        const ChannelFactoryConstPtr &channelFactory,
        const ContactFactoryConstPtr &contactFactory,
        const Feature &coreFeature)
    : StatelessDBusProxy(bus,
            TP_QT_ACCOUNT_MANAGER_BUS_NAME,
            TP_QT_ACCOUNT_MANAGER_OBJECT_PATH, coreFeature),
      OptionalInterfaceFactory<AccountManager>(this),
      mPriv(new Private(this, accountFactory, connectionFactory, channelFactory, contactFactory))
{
}

/**
 * Class destructor.
 */
AccountManager::~AccountManager()
{
    delete mPriv;
}

/**
 * Return the account factory used by this account manager.
 *
 * Only read access is provided. This allows constructing object instances and examining the object
 * construction settings, but not changing settings. Allowing changes would lead to tricky
 * situations where objects constructed at different times by the manager would have unpredictably
 * different construction settings (eg. subclass).
 *
 * \return A read-only pointer to the AccountFactory object.
 */
AccountFactoryConstPtr AccountManager::accountFactory() const
{
    return mPriv->accFactory;
}

/**
 * Return the connection factory used by this account manager.
 *
 * Only read access is provided. This allows constructing object instances and examining the object
 * construction settings, but not changing settings. Allowing changes would lead to tricky
 * situations where objects constructed at different times by the manager would have unpredictably
 * different construction settings (eg. subclass).
 *
 * \return A read-only pointer to the ConnectionFactory object.
 */
ConnectionFactoryConstPtr AccountManager::connectionFactory() const
{
    return mPriv->connFactory;
}

/**
 * Return the channel factory used by this account manager.
 *
 * Only read access is provided. This allows constructing object instances and examining the object
 * construction settings, but not changing settings. Allowing changes would lead to tricky
 * situations where objects constructed at different times by the manager would have unpredictably
 * different construction settings (eg. subclass).
 *
 * \return A read-only pointer to the ChannelFactory object.
 */
ChannelFactoryConstPtr AccountManager::channelFactory() const
{
    return mPriv->chanFactory;
}

/**
 * Return the contact factory used by this account manager.
 *
 * Only read access is provided. This allows constructing object instances and examining the object
 * construction settings, but not changing settings. Allowing changes would lead to tricky
 * situations where objects constructed at different times by the manager would have unpredictably
 * different construction settings (eg. subclass).
 *
 * \return A read-only pointer to the ContactFactory object.
 */
ContactFactoryConstPtr AccountManager::contactFactory() const
{
    return mPriv->contactFactory;
}

/**
 * Return a list containing all accounts.
 *
 * Newly accounts added and/or discovered are signaled via newAccount().
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A list of pointers to Account objects.
 */
QList<AccountPtr> AccountManager::allAccounts() const
{
    QList<AccountPtr> ret;
    foreach (const AccountPtr &account, mPriv->accounts) {
        ret << account;
    }
    return ret;
}

/**
 * Return a set of accounts containing all valid accounts.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::validAccounts() const
{
    QVariantMap filter;
    filter.insert(QLatin1String("valid"), true);
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all invalid accounts.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::invalidAccounts() const
{
    QVariantMap filter;
    filter.insert(QLatin1String("valid"), false);
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all enabled accounts.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::enabledAccounts() const
{
    QVariantMap filter;
    filter.insert(QLatin1String("enabled"), true);
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all disabled accounts.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::disabledAccounts() const
{
    QVariantMap filter;
    filter.insert(QLatin1String("enabled"), false);
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all online accounts.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::onlineAccounts() const
{
    QVariantMap filter;
    filter.insert(QLatin1String("online"), true);
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all offline accounts.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::offlineAccounts() const
{
    QVariantMap filter;
    filter.insert(QLatin1String("online"), false);
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all accounts that support text chats by
 * providing a contact identifier.
 *
 * For this method to work, you must use an AccountFactory which makes Account::FeatureCapabilities
 * ready.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::textChatAccounts() const
{
    if (!accountFactory()->features().contains(Account::FeatureCapabilities)) {
        warning() << "Account filtering by capabilities can only be used with an AccountFactory"
            << "which makes Account::FeatureCapabilities ready";
        return filterAccounts(AccountFilterConstPtr());
    }

    AccountCapabilityFilterPtr filter = AccountCapabilityFilter::create();
    filter->addRequestableChannelClassSubset(RequestableChannelClassSpec::textChat());
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all accounts that support text chat
 * rooms.
 *
 * For this method to work, you must use an AccountFactory which makes Account::FeatureCapabilities
 * ready.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::textChatroomAccounts() const
{
    if (!accountFactory()->features().contains(Account::FeatureCapabilities)) {
        warning() << "Account filtering by capabilities can only be used with an AccountFactory"
            << "which makes Account::FeatureCapabilities ready";
        return filterAccounts(AccountFilterConstPtr());
    }

    AccountCapabilityFilterPtr filter = AccountCapabilityFilter::create();
    filter->addRequestableChannelClassSubset(RequestableChannelClassSpec::textChatroom());
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all accounts that support audio calls (using the
 * Call interface) by providing a contact identifier.
 *
 * For this method to work, you must use an AccountFactory which makes Account::FeatureCapabilities
 * ready.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::audioCallAccounts() const
{
    if (!accountFactory()->features().contains(Account::FeatureCapabilities)) {
        warning() << "Account filtering by capabilities can only be used with an AccountFactory"
            << "which makes Account::FeatureCapabilities ready";
        return filterAccounts(AccountFilterConstPtr());
    }

    AccountCapabilityFilterPtr filter = AccountCapabilityFilter::create();
    filter->addRequestableChannelClassSubset(RequestableChannelClassSpec::audioCall());
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all accounts that support video calls (using the
 * Call interface) by providing a contact identifier.
 *
 * For this method to work, you must use an AccountFactory which makes Account::FeatureCapabilities
 * ready.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::videoCallAccounts() const
{
    if (!accountFactory()->features().contains(Account::FeatureCapabilities)) {
        warning() << "Account filtering by capabilities can only be used with an AccountFactory"
            << "which makes Account::FeatureCapabilities ready";
        return filterAccounts(AccountFilterConstPtr());
    }

    AccountCapabilityFilterPtr filter = AccountCapabilityFilter::create();
    filter->addRequestableChannelClassSubset(RequestableChannelClassSpec::videoCall());
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all accounts that support media calls (using the
 * StreamedMedia interface) by providing a contact identifier.
 *
 * For this method to work, you must use an AccountFactory which makes Account::FeatureCapabilities
 * ready.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::streamedMediaCallAccounts() const
{
    if (!accountFactory()->features().contains(Account::FeatureCapabilities)) {
        warning() << "Account filtering by capabilities can only be used with an AccountFactory"
            << "which makes Account::FeatureCapabilities ready";
        return filterAccounts(AccountFilterConstPtr());
    }

    AccountCapabilityFilterPtr filter = AccountCapabilityFilter::create();
    filter->addRequestableChannelClassSubset(RequestableChannelClassSpec::streamedMediaCall());
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all accounts that support audio calls (using the
 * StreamedMedia interface) by providing a contact identifier.
 *
 * For this method to work, you must use an AccountFactory which makes Account::FeatureCapabilities
 * ready.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::streamedMediaAudioCallAccounts() const
{
    if (!accountFactory()->features().contains(Account::FeatureCapabilities)) {
        warning() << "Account filtering by capabilities can only be used with an AccountFactory"
            << "which makes Account::FeatureCapabilities ready";
        return filterAccounts(AccountFilterConstPtr());
    }

    AccountCapabilityFilterPtr filter = AccountCapabilityFilter::create();
    filter->addRequestableChannelClassSubset(RequestableChannelClassSpec::streamedMediaAudioCall());
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all accounts that support video calls (using the
 * StreamedMedia interface) by providing a contact identifier.
 *
 * For this method to work, you must use an AccountFactory which makes Account::FeatureCapabilities
 * ready.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::streamedMediaVideoCallAccounts() const
{
    if (!accountFactory()->features().contains(Account::FeatureCapabilities)) {
        warning() << "Account filtering by capabilities can only be used with an AccountFactory"
            << "which makes Account::FeatureCapabilities ready";
        return filterAccounts(AccountFilterConstPtr());
    }

    AccountCapabilityFilterPtr filter = AccountCapabilityFilter::create();
    filter->addRequestableChannelClassSubset(RequestableChannelClassSpec::streamedMediaVideoCall());
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all accounts that support video calls with audio (using the
 * StreamedMedia interface) by providing a contact identifier.
 *
 * For this method to work, you must use an AccountFactory which makes Account::FeatureCapabilities
 * ready.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::streamedMediaVideoCallWithAudioAccounts() const
{
    if (!accountFactory()->features().contains(Account::FeatureCapabilities)) {
        warning() << "Account filtering by capabilities can only be used with an AccountFactory"
            << "which makes Account::FeatureCapabilities ready";
        return filterAccounts(AccountFilterConstPtr());
    }

    AccountCapabilityFilterPtr filter = AccountCapabilityFilter::create();
    filter->addRequestableChannelClassSubset(
            RequestableChannelClassSpec::streamedMediaVideoCallWithAudio());
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all accounts that support file transfers by
 * providing a contact identifier.
 *
 * For this method to work, you must use an AccountFactory which makes Account::FeatureCapabilities
 * ready.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::fileTransferAccounts() const
{
    if (!accountFactory()->features().contains(Account::FeatureCapabilities)) {
        warning() << "Account filtering by capabilities can only be used with an AccountFactory"
            << "which makes Account::FeatureCapabilities ready";
        return filterAccounts(AccountFilterConstPtr());
    }

    AccountCapabilityFilterPtr filter = AccountCapabilityFilter::create();
    filter->addRequestableChannelClassSubset(RequestableChannelClassSpec::fileTransfer());
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all accounts for the given \a
 * protocolName.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \param protocolName The name of the protocol used to filter accounts.
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::accountsByProtocol(
        const QString &protocolName) const
{
    if (!isReady(FeatureCore)) {
        warning() << "Account filtering requires AccountManager to be ready";
        return filterAccounts(AccountFilterConstPtr());
    }

    QVariantMap filter;
    filter.insert(QLatin1String("protocolName"), protocolName);
    return filterAccounts(filter);
}

/**
 * Return a set of accounts containing all accounts that match the given \a
 * filter criteria.
 *
 * For AccountCapabilityFilter filtering, an AccountFactory which makes
 * Account::FeatureCapabilities ready must be used.
 *
 * See AccountSet documentation for more details.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \param filter The desired filter.
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::filterAccounts(const AccountFilterConstPtr &filter) const
{
    if (!isReady(FeatureCore)) {
        warning() << "Account filtering requires AccountManager to be ready";
        return AccountSetPtr(new AccountSet(AccountManagerPtr(
                        (AccountManager *) this), AccountFilterConstPtr()));
    }

    return AccountSetPtr(new AccountSet(AccountManagerPtr(
                    (AccountManager *) this), filter));
}

/**
 * Return a set of accounts containing all accounts that match the given \a
 * filter criteria.
 *
 * The \a filter is composed by Account property names and values as map items.
 *
 * The following example will return all jabber accounts that are enabled:
 *
 * \code
 *
 * void MyClass::init()
 * {
 *     mAM = AccountManager::create();
 *     connect(mAM->becomeReady(),
 *             SIGNAL(finished(Tp::PendingOperation*)),
 *             SLOT(onAccountManagerReady(Tp::PendingOperation*)));
 * }
 *
 * void MyClass::onAccountManagerReady(Tp::PendingOperation *op)
 * {
 *     if (op->isError()) {
 *         qWarning() << "Account manager cannot become ready:" <<
 *             op->errorName() << "-" << op->errorMessage();
 *         return;
 *     }
 *
 *     QVariantMap filter;
 *     filter.insert(QLatin1String("protocolName"), QLatin1String("jabber"));
 *     filter.insert(QLatin1String("enabled"), true);
 *     filteredAccountSet = mAM->filterAccounts(filter);
 *     // connect to AccountSet::accountAdded/accountRemoved signals
 *     QList<AccountPtr> accounts = filteredAccountSet->accounts();
 *     // do something with accounts
 * }
 *
 * \endcode
 *
 * See AccountSet documentation for more details.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \param filter The desired filter.
 * \return A pointer to an AccountSet object containing the matching accounts.
 */
AccountSetPtr AccountManager::filterAccounts(const QVariantMap &filter) const
{
    if (!isReady(FeatureCore)) {
        warning() << "Account filtering requires AccountManager to be ready";
        return AccountSetPtr(new AccountSet(AccountManagerPtr(
                        (AccountManager *) this), QVariantMap()));
    }

    return AccountSetPtr(new AccountSet(AccountManagerPtr(
                    (AccountManager *) this), filter));
}

/**
 * Return the account for the given \a path.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \param path The account object path.
 * \return A pointer to an AccountSet object containing the matching accounts.
 * \sa allAccounts(), accountsForObjectPaths()
 */
AccountPtr AccountManager::accountForObjectPath(const QString &path) const
{
    if (!isReady(FeatureCore)) {
        return AccountPtr();
    }

    return mPriv->accounts.value(path);
}

/**
 * \deprecated See accountForObjectPath()
 */
AccountPtr AccountManager::accountForPath(const QString &path) const
{
    return accountForObjectPath(path);
}

/**
 * Return a list of accounts for the given \a paths.
 *
 * The returned list will have one AccountPtr object for each given path. If
 * a given path is invalid the returned AccountPtr object will point to 0.
 * AccountPtr::isNull() will return true.
 *
 * This method requires AccountManager::FeatureCore to be ready.
 *
 * \param paths List of accounts object paths.
 * \return A list of pointers to Account objects for the given
 *         \a paths. Null AccountPtr objects will be used as list elements for each invalid path.
 * \sa allAccounts(), accountForObjectPath()
 */
QList<AccountPtr> AccountManager::accountsForObjectPaths(const QStringList &paths) const
{
    if (!isReady(FeatureCore)) {
        return QList<AccountPtr>();
    }

    QList<AccountPtr> result;
    foreach (const QString &path, paths) {
        result << accountForObjectPath(path);
    }
    return result;
}

/**
 * \deprecated See accountsForObjectPaths()
 */
QList<AccountPtr> AccountManager::accountsForPaths(const QStringList &paths) const
{
    return accountsForObjectPaths(paths);
}

/**
 * Return a list of the fully qualified names of properties that can be set
 * when calling createAccount().
 *
 * \return A list of fully qualified D-Bus property names,
 *         such as "org.freedesktop.Telepathy.Account.Enabled".
 * \sa createAccount()
 */
QStringList AccountManager::supportedAccountProperties() const
{
    return mPriv->supportedAccountProperties;
}

/**
 * Create an account with the given parameters.
 *
 * The optional \a properties argument can be used to set any property listed in
 * supportedAccountProperties() at the time the account is created.
 *
 * \param connectionManager The name of the connection manager to create the account
 *                          for.
 * \param protocol The name of the protocol to create the account for.
 * \param displayName The account display name.
 * \param parameters The account parameters.
 * \param properties An optional map from fully qualified D-Bus property
 *                   names such as "org.freedesktop.Telepathy.Account.Enabled"
 *                   to their values.
 * \return A PendingAccount object which will emit PendingAccount::finished
 *         when the account has been created of failed its creation process.
 * \sa supportedAccountProperties()
 */
PendingAccount *AccountManager::createAccount(const QString &connectionManager,
        const QString &protocol, const QString &displayName,
        const QVariantMap &parameters, const QVariantMap &properties)
{
    return new PendingAccount(AccountManagerPtr(this), connectionManager,
            protocol, displayName, parameters, properties);
}

/**
 * Return the Client::AccountManagerInterface interface proxy object for this
 * account manager. This method is protected since the convenience methods
 * provided by this class should generally be used instead of calling D-Bus
 * methods directly.
 *
 * \return A pointer to the existing Client::AccountManagerInterface object for
 *         this AccountManager object.
 */
Client::AccountManagerInterface *AccountManager::baseInterface() const
{
    return mPriv->baseInterface;
}

void AccountManager::introspectMain()
{
    mPriv->introspectMain(mPriv);
}

void AccountManager::gotMainProperties(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QVariantMap> reply = *watcher;
    QVariantMap props;

    if (!reply.isError()) {
        mPriv->gotInitialAccounts = true;

        debug() << "Got reply to Properties.GetAll(AccountManager)";
        props = reply.value();

        if (props.contains(QLatin1String("Interfaces"))) {
            setInterfaces(qdbus_cast<QStringList>(props[QLatin1String("Interfaces")]));
            mPriv->readinessHelper->setInterfaces(interfaces());
        }

        if (props.contains(QLatin1String("SupportedAccountProperties"))) {
            mPriv->supportedAccountProperties =
                qdbus_cast<QStringList>(props[QLatin1String("SupportedAccountProperties")]);
        }

        QSet<QString> paths = mPriv->getAccountPathsFromProps(props);
        foreach (const QString &path, paths) {
            mPriv->addAccountForPath(path);
        }

        mPriv->checkIntrospectionCompleted();
    } else {
        if (mPriv->reintrospectionRetries++ < maxReintrospectionRetries) {
            int retryInterval = reintrospectionRetryInterval;
            if (reply.error().type() == QDBusError::TimedOut) {
                retryInterval = 0;
            }
            QTimer::singleShot(retryInterval, this, SLOT(introspectMain()));
        } else {
            warning() << "GetAll(AccountManager) failed with" <<
                reply.error().name() << ":" << reply.error().message();
            mPriv->readinessHelper->setIntrospectCompleted(FeatureCore,
                    false, reply.error());
        }
    }

    watcher->deleteLater();
}

void AccountManager::onAccountReady(Tp::PendingOperation *op)
{
    PendingReady *pr = qobject_cast<PendingReady*>(op);
    AccountPtr account(AccountPtr::qObjectCast(pr->proxy()));
    QString path = account->objectPath();

    /* Some error occurred or the account was removed before become ready */
    if (op->isError() || !mPriv->incompleteAccounts.contains(path)) {
        mPriv->incompleteAccounts.remove(path);
        mPriv->checkIntrospectionCompleted();
        return;
    }

    mPriv->incompleteAccounts.remove(path);

    // We shouldn't end up here twice for the same account - that would also mean newAccount being
    // emitted twice for an account, and AccountSets getting confused as a result
    Q_ASSERT(!mPriv->accounts.contains(path));
    mPriv->accounts.insert(path, account);

    if (isReady(FeatureCore)) {
        emit newAccount(account);
    }

    mPriv->checkIntrospectionCompleted();
}

void AccountManager::onAccountValidityChanged(const QDBusObjectPath &objectPath,
        bool valid)
{
    if (!mPriv->gotInitialAccounts) {
        return;
    }

    QString path = objectPath.path();

    if (!mPriv->incompleteAccounts.contains(path) &&
        !mPriv->accounts.contains(path)) {
        debug() << "New account" << path;
        mPriv->addAccountForPath(path);
    }
}

void AccountManager::onAccountRemoved(const QDBusObjectPath &objectPath)
{
    if (!mPriv->gotInitialAccounts) {
        return;
    }

    QString path = objectPath.path();

    /* the account is either in mPriv->incompleteAccounts or mPriv->accounts */
    if (mPriv->accounts.contains(path)) {
        mPriv->accounts.remove(path);

        if (isReady(FeatureCore)) {
            debug() << "Account" << path << "removed";
        } else {
            debug() << "Account" << path << "removed while the AM "
                "was not completely introspected";
        }
    } else if (mPriv->incompleteAccounts.contains(path)) {
        mPriv->incompleteAccounts.remove(path);
        debug() << "Account" << path << "was removed, but it was "
            "not completely introspected, ignoring";
    } else {
        debug() << "Got AccountRemoved for unknown account" << path << ", ignoring";
    }
}

/**
 * \fn void AccountManager::newAccount(const Tp::AccountPtr &account)
 *
 * Emitted when a new account is created.
 *
 * The new \a account will have the features set in the AccountFactory used by this
 * account manager ready and the same connection, channel and contact factories as used by this
 * account manager.
 *
 * \param account The newly created account.
 */

} // Tp