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

#include <TelepathyQt4/AccountManager>

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

#include "TelepathyQt4/debug-internal.h"

#include <TelepathyQt4/AccountSet>
#include <TelepathyQt4/PendingAccount>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/Constants>

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

namespace Tp
{

struct TELEPATHY_QT4_NO_EXPORT AccountManager::Private
{
    Private(AccountManager *parent, const ChannelFactoryConstPtr &chanFactory,
            const ConnectionFactoryConstPtr &connFactory, const AccountFactoryConstPtr &accFactory);
    ~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;

    ReadinessHelper *readinessHelper;

    ChannelFactoryConstPtr chanFactory;
    ConnectionFactoryConstPtr connFactory;
    AccountFactoryConstPtr accFactory;

    // Introspection
    QHash<QString, AccountPtr> incompleteAccounts;
    QHash<QString, AccountPtr> accounts;
    QStringList supportedAccountProperties;
};

AccountManager::Private::Private(AccountManager *parent, const ChannelFactoryConstPtr &chanFactory,
            const ConnectionFactoryConstPtr &connFactory, const AccountFactoryConstPtr &accFactory)
    : parent(parent),
      baseInterface(new Client::AccountManagerInterface(parent->dbusConnection(),
                    parent->busName(), parent->objectPath(), parent)),
      readinessHelper(parent->readinessHelper()),
      chanFactory(chanFactory),
      connFactory(connFactory),
      accFactory(accFactory)
{
    debug() << "Creating new AccountManager:" << parent->busName();

    if (chanFactory->dbusConnection().name() != parent->dbusConnection().name()) {
        warning() << "  The D-Bus connection in the channel 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 (accFactory->dbusConnection().name() != parent->dbusConnection().name()) {
        warning() << "  The D-Bus connection in the account 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(const QDBusObjectPath &, bool)),
            SLOT(onAccountValidityChanged(const QDBusObjectPath &, bool)));
    parent->connect(baseInterface,
            SIGNAL(AccountRemoved(const QDBusObjectPath &)),
            SLOT(onAccountRemoved(const QDBusObjectPath &)));
}

void AccountManager::Private::introspectMain(AccountManager::Private *self)
{
    Client::DBus::PropertiesInterface *properties = self->parent->propertiesInterface();
    Q_ASSERT(properties != 0);

    debug() << "Calling Properties::GetAll(AccountManager)";
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
            properties->GetAll(
                QLatin1String(TELEPATHY_INTERFACE_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)
{
    if (accounts.contains(path)) {
        return;
    }

    PendingReady *readyOp = accFactory->proxy(parent->busName(), path, connFactory,
            chanFactory);

    AccountPtr account(AccountPtr::dynamicCast(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 TelepathyQt4/account-manager.h <TelepathyQt4/AccountManager>
 *
 * \brief The AccountManager class provides an object representing a Telepathy
 * account manager.
 *
 * AccountManager adds the following features compared to using
 * Client::AccountManagerInterface directly:
 * <ul>
 *  <li>Account status tracking</li>
 *  <li>Getting the list of supported interfaces automatically</li>
 *  <li>Cache Account objects when they are requested the first time</li>
 * </ul>
 *
 * The remote object accessor functions on this object (allAccountPaths(),
 * allAccounts(), 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. Their return value is mostly undefined until the
 * introspection process is completed, i.e. isReady() returns true. See the
 * individual accessor descriptions for more details.
 *
 * Signals are emitted to indicate that accounts are added/removed and when
 * accounts validity changes. See accountCreated(), accountRemoved(),
 * accountValidityChanged().
 *
 * \section am_usage_sec Usage
 *
 * \subsection am_create_sec Creating an account manager 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 account manager 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 am;
 * };
 *
 * MyClass::MyClass(QObject *parent)
 *     : QObject(parent)
 *       am(AccountManager::create())
 * {
 *     connect(am->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() << "Valid accounts:";
 *     foreach (const QString &path, am->validAccountPaths()) {
 *         qDebug() << " path:" << path;
 *     }
 * }
 *
 * \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 any AccountManager
 * method.
 *
 * 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 QDBusConnection::sessionBus().
 *
 * \return An AccountManagerPtr object pointing to the newly created
 *         AccountManager object.
 */
AccountManagerPtr AccountManager::create()
{
    return AccountManagerPtr(new AccountManager());
}

/**
 * Create a new AccountManager object using the given \a bus.
 *
 * \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));
}

AccountManagerPtr AccountManager::create(const ChannelFactoryConstPtr &channelFactory,
        const ConnectionFactoryConstPtr &connectionFactory,
        const AccountFactoryConstPtr &accountFactory,
        const QDBusConnection &bus)
{
    return AccountManagerPtr(new AccountManager(
                channelFactory, connectionFactory, accountFactory, bus));
}

/**
 * Construct a new AccountManager object using QDBusConnection::sessionBus().
 */
AccountManager::AccountManager()
    : StatelessDBusProxy(QDBusConnection::sessionBus(),
            QLatin1String(TELEPATHY_ACCOUNT_MANAGER_BUS_NAME),
            QLatin1String(TELEPATHY_ACCOUNT_MANAGER_OBJECT_PATH)),
      OptionalInterfaceFactory<AccountManager>(this),
      ReadyObject(this, FeatureCore),
      mPriv(new Private(
                  this,
                  ChannelFactory::stockFreshFactory(QDBusConnection::sessionBus()),
                  ConnectionFactory::create(QDBusConnection::sessionBus()),
                  AccountFactory::create(QDBusConnection::sessionBus())))
{
}

/**
 * Construct a new AccountManager object using the given \a bus.
 *
 * \param bus QDBusConnection to use.
 */
AccountManager::AccountManager(const QDBusConnection& bus)
    : StatelessDBusProxy(bus,
            QLatin1String(TELEPATHY_ACCOUNT_MANAGER_BUS_NAME),
            QLatin1String(TELEPATHY_ACCOUNT_MANAGER_OBJECT_PATH)),
      OptionalInterfaceFactory<AccountManager>(this),
      ReadyObject(this, FeatureCore),
      mPriv(new Private(
                  this,
                  ChannelFactory::stockFreshFactory(bus),
                  ConnectionFactory::create(bus),
                  AccountFactory::create(bus)))
{
}

/**
 * Construct a new AccountManager object using the given \a bus.
 *
 * \param bus QDBusConnection to use.
 */
AccountManager::AccountManager(const ChannelFactoryConstPtr &channelFactory,
        const ConnectionFactoryConstPtr &connectionFactory,
        const AccountFactoryConstPtr &accountFactory,
        const QDBusConnection &bus)
    : StatelessDBusProxy(bus,
            QLatin1String(TELEPATHY_ACCOUNT_MANAGER_BUS_NAME),
            QLatin1String(TELEPATHY_ACCOUNT_MANAGER_OBJECT_PATH)),
      OptionalInterfaceFactory<AccountManager>(this),
      ReadyObject(this, FeatureCore),
      mPriv(new Private(this, channelFactory, connectionFactory, accountFactory))
{
}

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

ChannelFactoryConstPtr AccountManager::channelFactory() const
{
    return mPriv->chanFactory;
}

ConnectionFactoryConstPtr AccountManager::connectionFactory() const
{
    return mPriv->connFactory;
}

AccountFactoryConstPtr AccountManager::accountFactory() const
{
    return mPriv->accFactory;
}

/**
 * Return a list of object paths for all valid accounts.
 *
 * \return A list of object paths.
 */
QStringList AccountManager::validAccountPaths() const
{
    QStringList ret;
    foreach (const AccountPtr &account, mPriv->accounts) {
        if (account->isValid()) {
            ret << account->objectPath();
        }
    }
    return ret;
}

/**
 * Return a list of object paths for all invalid accounts.
 *
 * \return A list of object paths.
 */
QStringList AccountManager::invalidAccountPaths() const
{
    QStringList ret;
    foreach (const AccountPtr &account, mPriv->accounts) {
        if (!account->isValid()) {
            ret << account->objectPath();
        }
    }
    return ret;
}

/**
 * Return a list of object paths for all accounts.
 *
 * \return A list of object paths.
 */
QStringList AccountManager::allAccountPaths() const
{
    QStringList ret;
    foreach (const AccountPtr &account, mPriv->accounts) {
        ret << account->objectPath();
    }
    return ret;
}

/**
 * Return a list of AccountPtr objects for all valid accounts.
 *
 * Note that the returned account already has the Account::FeatureCore enabled.
 *
 * \return A list of AccountPtr objects.
 * \sa invalidAccounts(), allAccounts(), accountsForPaths()
 */
QList<AccountPtr> AccountManager::validAccounts()
{
    QList<AccountPtr> ret;
    foreach (const AccountPtr &account, mPriv->accounts) {
        if (account->isValid()) {
            ret << account;
        }
    }
    return ret;
}

/**
 * Return a list of AccountPtr objects for all invalid accounts.
 *
 * Note that the returned account already has the Account::FeatureCore enabled.
 *
 * \return A list of AccountPtr objects.
 * \sa validAccounts(), allAccounts(), accountsForPaths()
 */
QList<AccountPtr> AccountManager::invalidAccounts()
{
    QList<AccountPtr> ret;
    foreach (const AccountPtr &account, mPriv->accounts) {
        if (!account->isValid()) {
            ret << account;
        }
    }
    return ret;
}

/**
 * Return a list of AccountPtr objects for all accounts.
 *
 * Note that the returned account already has the Account::FeatureCore enabled.
 *
 * \return A list of AccountPtr objects.
 * \sa validAccounts(), invalidAccounts(), accountsForPaths()
 */
/* FIXME (API-BREAK) Add const qualifier */
QList<AccountPtr> AccountManager::allAccounts()
{
    QList<AccountPtr> ret;
    foreach (const AccountPtr &account, mPriv->accounts) {
        ret << account;
    }
    return ret;
}

/**
 * Return a set of accounts containing all valid accounts.
 *
 * Note that the returned account already has the Account::FeatureCore enabled.
 *
 * \return A set of accounts containing all valid accounts.
 */
AccountSetPtr AccountManager::validAccountsSet() const
{
    QVariantMap filter;
    filter.insert(QLatin1String("valid"), true);
    return AccountSetPtr(new AccountSet(AccountManagerPtr(
                    (AccountManager *) this), filter));
}

/**
 * Return a set of accounts containing all invalid accounts.
 *
 * Note that the returned account already has the Account::FeatureCore enabled.
 *
 * \return A set of accounts containing all invalid accounts.
 */
AccountSetPtr AccountManager::invalidAccountsSet() const
{
    QVariantMap filter;
    filter.insert(QLatin1String("valid"), false);
    return AccountSetPtr(new AccountSet(AccountManagerPtr(
                    (AccountManager *) this), filter));
}

/**
 * Return a set of accounts containing all enabled accounts.
 *
 * Note that the returned account already has the Account::FeatureCore enabled.
 *
 * \return A set of accounts containing all enabled accounts.
 */
AccountSetPtr AccountManager::enabledAccountsSet() const
{
    QVariantMap filter;
    filter.insert(QLatin1String("enabled"), true);
    return AccountSetPtr(new AccountSet(AccountManagerPtr(
                    (AccountManager *) this), filter));
}

/**
 * Return a set of accounts containing all disabled accounts.
 *
 * Note that the returned account already has the Account::FeatureCore enabled.
 *
 * \return A set of accounts containing all disabled accounts.
 */
AccountSetPtr AccountManager::disabledAccountsSet() const
{
    QVariantMap filter;
    filter.insert(QLatin1String("enabled"), false);
    return AccountSetPtr(new AccountSet(AccountManagerPtr(
                    (AccountManager *) this), filter));
}

/**
 * Return a set of accounts containing all online accounts.
 *
 * Note that the returned account already has the Account::FeatureCore enabled.
 *
 * \return A set of accounts containing all online accounts.
 */
AccountSetPtr AccountManager::onlineAccountsSet() const
{
    QVariantMap filter;
    filter.insert(QLatin1String("online"), true);
    return AccountSetPtr(new AccountSet(AccountManagerPtr(
                    (AccountManager *) this), filter));
}

/**
 * Return a set of accounts containing all offline accounts.
 *
 * Note that the returned account already has the Account::FeatureCore enabled.
 *
 * \return A set of accounts containing all offline accounts.
 */
AccountSetPtr AccountManager::offlineAccountsSet() const
{
    QVariantMap filter;
    filter.insert(QLatin1String("online"), false);
    return AccountSetPtr(new AccountSet(AccountManagerPtr(
                    (AccountManager *) this), filter));
}

/**
 * Return a set of accounts containing all accounts for the given \a
 * protocolName.
 *
 * Note that the returned account already has the Account::FeatureCore enabled.
 *
 * \param protocolName The name of the protocol used to filter accounts.
 * \return A set of accounts containing all accounts for the given \a
 *         protocolName.
 */
AccountSetPtr AccountManager::accountsByProtocol(
        const QString &protocolName) const
{
    QVariantMap filter;
    filter.insert(QLatin1String("protocolName"), protocolName);
    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()
 * {
 *     am = AccountManager::create();
 *     connect(am->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 = am->filterAccounts(filter);
 *     // connect to AccountSet::accountAdded/accountRemoved signals
 *     QList<AccountPtr> accounts = filteredAccountSet->accounts();
 *     // do something with accounts
 * }
 *
 * \endcode
 *
 * See AccountSet documentation for more details.
 *
 * \param filter The desired filter
 * \return A set of accounts containing all accounts that match the given \a
 *         filter criteria.
 */
AccountSetPtr AccountManager::filterAccounts(const QVariantMap &filter) const
{
    return AccountSetPtr(new AccountSet(AccountManagerPtr(
                    (AccountManager *) this), filter));
}

/**
 * Return an AccountPtr object for the given \a path.
 *
 * Note that the returned account already has the Account::FeatureCore enabled.
 *
 * \param path The account object path.
 * \return An AccountPtr object pointing to the Account object for the given
 *         \a path, or a null AccountPtr if \a path is invalid.
 * \sa validAccounts(), invalidAccounts(), accountsForPaths()
 */
AccountPtr AccountManager::accountForPath(const QString &path)
{
    if (!mPriv->accounts.contains(path)) {
        return AccountPtr();
    }

    return mPriv->accounts[path];
}

/**
 * Return a list of AccountPtr objects 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.
 *
 * Note that the returned accounts already have the Account::FeatureCore
 * enabled.
 *
 * \param paths List of accounts object paths.
 * \return A list of AccountPtr objects.
 * \sa validAccounts(), invalidAccounts(), allAccounts(), accountForPath()
 */
QList<AccountPtr> AccountManager::accountsForPaths(const QStringList &paths)
{
    QList<AccountPtr> result;
    foreach (const QString &path, paths) {
        result << accountForPath(path);
    }
    return result;
}

/**
 * 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 properties argument can be used to set any property listed in
 * supportedAccountProperties() at the time the account is created.
 *
 * \param connectionManager Name of the connection manager to create the account
 *                          for.
 * \param protocol 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);
}

/**
 * \fn void AccountManager::accountCreated(const QString &path)
 *
 * This signal is emitted when a new account is created.
 *
 * \param path The object path of the newly created account.
 * \sa accountForPath()
 */

/**
 * \fn void AccountManager::accountRemoved(const QString &path)
 *
 * This signal is emitted when an account gets removed.
 *
 * \param path The object path of the removed account.
 * \sa accountForPath()
 */

/**
 * \fn void AccountManager::accountValidityChanged(const QString &path, bool valid)
 *
 * This signal is emitted when an account validity changes.
 *
 * \param path The object path of the account in which the validity changed.
 * \param valid Whether the account is valid or not.
 * \sa accountForPath()
 */

/**
 * \fn Client::DBus::PropertiesInterface *AccountManager::propertiesInterface() const
 *
 * Convenience function for getting a PropertiesInterface interface proxy object
 * for this account manager. The AccountManager interface relies on properties,
 * so this interface is always assumed to be present.
 *
 * \return A pointer to the existing Client::DBus::PropertiesInterface object
 *         for this AccountManager object.
 */

/**
 * 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;
}

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

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

        if (props.contains(QLatin1String("Interfaces"))) {
            setInterfaces(qdbus_cast<QStringList>(props[QLatin1String("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);
        }
    } else {
        warning().nospace() <<
            "GetAll(AccountManager) failed: " <<
            reply.error().name() << ": " << reply.error().message();
    }

    watcher->deleteLater();

    mPriv->checkIntrospectionCompleted();
}

void AccountManager::onAccountReady(Tp::PendingOperation *op)
{
    PendingReady *pr = qobject_cast<PendingReady*>(op);
    AccountPtr account = AccountPtr::dynamicCast(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);
    mPriv->accounts.insert(path, account);

    if (isReady(FeatureCore)) {
        /* FIXME (API-BREAK) Remove accountCreated signal */
        emit accountCreated(path);
        emit newAccount(account);
    }

    mPriv->checkIntrospectionCompleted();
}

void AccountManager::onAccountValidityChanged(const QDBusObjectPath &objectPath,
        bool valid)
{
    QString path = objectPath.path();
    bool newAccount = false;

    if (!mPriv->incompleteAccounts.contains(path) &&
        !mPriv->accounts.contains(path)) {
        newAccount = true;
    }

    if (newAccount) {
        mPriv->addAccountForPath(path);
    } else {
        /* Only emit accountValidityChanged if both the AM and the account
         * are ready */
        if (isReady(FeatureCore) && mPriv->accounts.contains(path)) {
            /* FIXME (API-BREAK) Remove accountValidityChanged signal */
            emit accountValidityChanged(path, valid);
        }
    }
}

void AccountManager::onAccountRemoved(const QDBusObjectPath &objectPath)
{
    QString path = objectPath.path();

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

        /* Only emit accountRemoved if both the AM and the account are ready */
        if (isReady(FeatureCore)) {
            /* FIXME (API-BREAK) Remove accountRemoved signal */
            emit accountRemoved(path);
            debug() << "Account" << path << "removed";
        } else {
            debug() << "Account" << path << "removed while the AM "
                "or the account itself were not completely introspected, "
                "ignoring";
        }
    } else if (mPriv->incompleteAccounts.contains(path)) {
        mPriv->incompleteAccounts.remove(path);
        debug() << "Account" << path << "was removed, but it was "
            "not completely introspected, ignoring";
    }
}

} // Tp