File indexing completed on 2024-11-24 04:50:42

0001 // SPDX-FileCopyrightText: 2022 Carl Schwan <carl@carlschwan.eu>
0002 // SPDX-License-Identifier: LGPL-2.1-or-later
0003 
0004 #include "contactgroupwrapper.h"
0005 
0006 #include "contactgroupmodel.h"
0007 #include <Akonadi/ItemFetchJob>
0008 #include <Akonadi/ItemFetchScope>
0009 #include <Akonadi/Session>
0010 #include <QAbstractListModel>
0011 #include <akonadi/itemmonitor.h>
0012 
0013 using namespace Akonadi;
0014 
0015 ContactGroupWrapper::ContactGroupWrapper(QObject *parent)
0016     : QObject(parent)
0017     , Akonadi::ItemMonitor()
0018     , m_model(new ContactGroupModel(false, this))
0019 {
0020     Akonadi::ItemFetchScope scope;
0021     scope.fetchFullPayload();
0022     scope.fetchAllAttributes();
0023     scope.setFetchRelations(true);
0024     scope.setAncestorRetrieval(Akonadi::ItemFetchScope::Parent);
0025     setFetchScope(scope);
0026 
0027     KContacts::ContactGroup dummyGroup;
0028     m_model->loadContactGroup(dummyGroup);
0029 }
0030 
0031 void ContactGroupWrapper::itemChanged(const Akonadi::Item &item)
0032 {
0033     const auto group = item.payload<KContacts::ContactGroup>();
0034     loadContactGroup(group);
0035 }
0036 
0037 QString ContactGroupWrapper::name() const
0038 {
0039     return m_name;
0040 }
0041 
0042 QAbstractListModel *ContactGroupWrapper::model() const
0043 {
0044     return (QAbstractListModel *)m_model;
0045 }
0046 
0047 Akonadi::Item ContactGroupWrapper::item() const
0048 {
0049     return m_item;
0050 }
0051 
0052 void ContactGroupWrapper::setItem(const Akonadi::Item &item)
0053 {
0054     ItemMonitor::setItem(item);
0055     m_item = item;
0056     auto job = new ItemFetchJob(item);
0057     job->fetchScope().fetchFullPayload();
0058     job->fetchScope().setAncestorRetrieval(Akonadi::ItemFetchScope::Parent);
0059 
0060     connect(job, &Akonadi::ItemFetchJob::result, this, [this](KJob *job) {
0061         itemFetchDone(job);
0062     });
0063 }
0064 
0065 void ContactGroupWrapper::itemFetchDone(KJob *job)
0066 {
0067     if (job->error()) {
0068         return;
0069     }
0070 
0071     auto fetchJob = qobject_cast<ItemFetchJob *>(job);
0072     if (!fetchJob) {
0073         return;
0074     }
0075 
0076     if (fetchJob->items().isEmpty()) {
0077         return;
0078     }
0079 
0080     m_item = fetchJob->items().at(0);
0081 
0082     const auto group = m_item.payload<KContacts::ContactGroup>();
0083     loadContactGroup(group);
0084 }
0085 
0086 void ContactGroupWrapper::loadContactGroup(const KContacts::ContactGroup &group)
0087 {
0088     setName(group.name());
0089     m_model->loadContactGroup(group);
0090 }
0091 
0092 void ContactGroupWrapper::setName(const QString &name)
0093 {
0094     if (m_name == name) {
0095         return;
0096     }
0097     m_name = name;
0098     Q_EMIT nameChanged();
0099 }
0100 
0101 #include "moc_contactgroupwrapper.cpp"