contactinfoproxymodel.cpp 15 KB
Newer Older
Konrad Czapla's avatar
Konrad Czapla committed
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
/*
  This file is part of KAddressBook.

  SPDX-FileCopyrightText: 2020 Konrad Czapla <kondzio89dev@gmail.com>

  SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "contactinfoproxymodel.h"

#include "kaddressbook_debug.h"

#include <AkonadiCore/EntityTreeModel>
#include <AkonadiCore/Item>
#include <AkonadiCore/ItemFetchJob>
#include <AkonadiCore/ItemFetchScope>
#include <AkonadiCore/Monitor>
#include <KLocalizedString>
#include <kcontacts/addressee.h>
#include <kcontacts/contactgroup.h>

#include <KJob>
#include <QImage>
#include <QJsonObject>
#include <QRegularExpression>

ContactInfoProxyModel::ContactInfoProxyModel(QObject *parent)
    : QIdentityProxyModel(parent),
      mMonitor(new Akonadi::Monitor(this))
{
    mMonitor->setTypeMonitored(Akonadi::Monitor::Items);
    mMonitor->itemFetchScope().fetchFullPayload(true);
    connect(mMonitor, &Akonadi::Monitor::itemChanged, this, &ContactInfoProxyModel::slotItemChanged);
    connect(mMonitor, &Akonadi::Monitor::itemRemoved, this, &ContactInfoProxyModel::slotItemRemoved);
}

QVariant ContactInfoProxyModel::data(const QModelIndex &index, int role) const
{
    if (role >= Roles::PictureRole && role <= Roles::DescriptionRole) {
        const Akonadi::Item item = index.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();
        if (item.isValid()) {
            if (item.hasPayload<KContacts::Addressee>()) {
                const KContacts::Addressee contact = item.payload<KContacts::Addressee>();
                switch (role) {
                case Roles::PictureRole:
                    return contact.photo().data();
                case Roles::InitialsRole:
                    return getInitials(contact);
                case Roles::DescriptionRole:
                    return getDescription(contact);
                }
            } else if (item.hasPayload<KContacts::ContactGroup>()) {
                const KContacts::ContactGroup groupContacts = item.payload<KContacts::ContactGroup>();
                if (!mGroupsCache.contains(index)) {
                    mGroupsCache.insert(index, ContactCacheData::List());
                }
                updateCache(index, groupContacts);
                if (groupFetchDone(index, groupContacts)) {
                    switch (role) {
                    case Roles::PictureRole:
                        return QVariant();
                    case Roles::InitialsRole:
                        return getInitials(index, groupContacts);
                    case Roles::DescriptionRole:
                        return getDescription(index, groupContacts);
                    }
                } else if (role == Roles::DescriptionRole) {
                    return i18n("Loading contacts details ...");
                }
                if (!mPendingGroups.contains(groupContacts.id())) {

                    QMap<const char*, QVariant> properties{
                        {"groupPersistentModelIndex", QVariant::fromValue(index)},
                        {"groupId", QVariant::fromValue(groupContacts.id())},
                    };

                    Akonadi::Item::List groupItemsList;
                    QList<QJsonObject> groupRefIdsList;

                    for (int idx = 0; idx < groupContacts.contactReferenceCount(); ++idx) {
                        const KContacts::ContactGroup::ContactReference contactRef = groupContacts.contactReference(idx);

                        if (findCacheItem(index, contactRef) == mGroupsCache[index].cend()) {
                            Akonadi::Item newItem;

                            if (contactRef.gid().isEmpty()) {
                                newItem.setId(contactRef.uid().toLongLong());
                            } else {
                                newItem.setGid(contactRef.gid());
                            }
                            if (!mPendingGroups.contains(groupContacts.id())) {
                                mPendingGroups << groupContacts.id();
                            }

                            groupItemsList << newItem;
                            const QJsonObject refId {
                                {QStringLiteral("uid"), contactRef.uid()},
                                {QStringLiteral("gid"), contactRef.gid()}
                            };
                            if (!groupRefIdsList.contains(refId)) {
                                groupRefIdsList << refId;
                            }
                        }
                    }
Laurent Montel's avatar
Laurent Montel committed
105
                    if (!groupItemsList.isEmpty() && !groupRefIdsList.isEmpty()) {
Konrad Czapla's avatar
Konrad Czapla committed
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
                        properties.insert("groupRefIdsList", QVariant::fromValue(groupRefIdsList));
                        fetchItems(groupItemsList, properties);
                    }
                }
                return QVariant();
            }
        }
    }
    return QIdentityProxyModel::data(index, role);
}

QString ContactInfoProxyModel::getInitials(const KContacts::Addressee &contact) const
{
    QString initials;
    QString names = contact.realName();
    names.remove(contact.prefix());
    names.remove(contact.suffix());
    names.remove(contact.additionalName());

    const QStringList contactListNames = names.split(QRegularExpression(QStringLiteral("\\s+")));
    for (const QString &name : contactListNames) {
        if (!name.isEmpty()) {
            initials.append(name.front());
        }
    }
    return initials.toUpper();
}

QString ContactInfoProxyModel::getInitials(const QModelIndex &index, const KContacts::ContactGroup &groupContacts) const
{
    QString initials;

    for (int idx = 0; idx < groupContacts.dataCount(); idx++) {
        if (!groupContacts.data(idx).name().isEmpty()) {
            initials.append(groupContacts.data(idx).name().front());
        }
    }

    for (const ContactCacheData &cacheContact : mGroupsCache[index]) {
        if (!cacheContact.name.isEmpty()) {
            initials.append(cacheContact.name.front());
        }
    }

    return initials.toUpper();
}

QString ContactInfoProxyModel::getDescription(const KContacts::Addressee &contact) const
{
    QString dataSeparator;
    QString emailAddress;
    QString phone;

    if (!contact.preferredEmail().isEmpty()) {
        emailAddress = i18n("Email: %1", contact.preferredEmail());
    }
    const QList<KContacts::PhoneNumber> phoneList = contact.phoneNumbers().toList();
    QList<KContacts::PhoneNumber>::const_reverse_iterator itPhone = std::find_if(phoneList.rbegin(),
                                                                                 phoneList.rend(),
    [&phoneList](const KContacts::PhoneNumber &phone) {
        return phone.isPreferred() || phoneList.at(0) == phone;
    });
    if (itPhone != phoneList.rend()) {
        phone = i18n("Phone: %1", (*itPhone).number());
    }
    if (!emailAddress.isEmpty() && !phone.isEmpty()) {
        dataSeparator = QStringLiteral(",");
    }

    return i18n("%1%2 %3", emailAddress, dataSeparator, phone).trimmed();
}

QString ContactInfoProxyModel::getDescription(const QModelIndex &index, const KContacts::ContactGroup &groupContacts) const
{
    QStringList groupDescription;
    QString contactDescription;

    for (int idx = 0; idx < groupContacts.dataCount(); idx++) {
        QString dataSeparator;
        if (!groupContacts.data(idx).name().isEmpty() &&
            !groupContacts.data(idx).email().isEmpty()) {
            dataSeparator = QStringLiteral("-");
        }
        contactDescription = i18n("%1 %2 %3", groupContacts.data(idx).name(), dataSeparator, groupContacts.data(idx).email());
        groupDescription << contactDescription.trimmed();
        contactDescription.clear();

    }
    for (int idx = 0; idx < groupContacts.contactReferenceCount(); ++idx) {
        const KContacts::ContactGroup::ContactReference contactRef = groupContacts.contactReference(idx);

        ContactCacheData::ConstListIterator it = findCacheItem(index, contactRef);
        if (it != mGroupsCache[index].end()) {
            QString cacheSeparator, email;
            email = contactRef.preferredEmail().isEmpty() ? it->email : contactRef.preferredEmail();
            if (it->name.isEmpty() && email.isEmpty()) {
                continue;
            } else if (!it->name.isEmpty() && !email.isEmpty()) {
                cacheSeparator = QStringLiteral("-");
            }
            contactDescription = i18n("%1 %2 %3", it->name, cacheSeparator, email);
            groupDescription << contactDescription.trimmed();
            contactDescription.clear();
        }
    }
    return groupDescription.join(QStringLiteral(", "));
}

void ContactInfoProxyModel::updateCache(const QModelIndex &index, const KContacts::ContactGroup &groupContacts) const
{
    mGroupsCache[index].erase(std::remove_if(mGroupsCache[index].begin(), mGroupsCache[index].end(),
    [&groupContacts](const ContactCacheData &cacheContact) -> bool {
        for (int idx = 0; idx < groupContacts.contactReferenceCount(); ++idx)
        {
            const KContacts::ContactGroup::ContactReference &reference = groupContacts.contactReference(idx);

            if (cacheContact == reference) {
                return false;
            }
        }
        return true;
    }), mGroupsCache[index].end());
}

bool ContactInfoProxyModel::groupFetchDone(const QModelIndex &index, const KContacts::ContactGroup &groupContacts) const
{
    QStringList contactRefIds;
    QStringList contactCacheIds;

    auto sortFunc = [](const QString &lhs, const QString &rhs) -> bool {
        return lhs.toLongLong() < rhs.toLongLong();
    };

    for (int idx = 0; idx < groupContacts.contactReferenceCount(); ++idx) {
        const KContacts::ContactGroup::ContactReference &reference = groupContacts.contactReference(idx);

        contactRefIds += reference.gid().isEmpty() ? reference.uid() : reference.gid();
    }
    std::sort(contactRefIds.begin(), contactRefIds.end(), sortFunc);
    contactRefIds.erase(std::unique(contactRefIds.begin(), contactRefIds.end()), contactRefIds.end());

    for (const auto &cacheContact : mGroupsCache[index]) {
        contactCacheIds += cacheContact.gid.isEmpty() ? cacheContact.uid : cacheContact.gid;
    }
    std::sort(contactCacheIds.begin(), contactCacheIds.end(), sortFunc);

    return std::equal(contactRefIds.begin(), contactRefIds.end(), contactCacheIds.begin(), contactCacheIds.end());
}

ContactInfoProxyModel::ContactCacheData::ListIterator ContactInfoProxyModel::findCacheItem(const QModelIndex &index,
                                                                                           const ContactInfoProxyModel::ContactCacheData &cacheContact)
{
    ContactCacheData::ListIterator it = std::find_if(mGroupsCache[index].begin(), mGroupsCache[index].end(),
                                        [&cacheContact](const ContactCacheData &contact) -> bool
    { return contact == cacheContact; });
    return it;
}


ContactInfoProxyModel::ContactCacheData::ConstListIterator ContactInfoProxyModel::findCacheItem(const QModelIndex &index,
                                                                                                const ContactInfoProxyModel::ContactCacheData &cacheContact) const
{
    ContactCacheData::ConstListIterator it = std::find_if(mGroupsCache[index].cbegin(), mGroupsCache[index].cend(),
                                        [&cacheContact](const ContactCacheData &contact) -> bool
    { return contact == cacheContact; });
    return it;
}

void ContactInfoProxyModel::fetchItems(const Akonadi::Item::List &items, const QMap<const char*, QVariant> &properties) const
{
    Akonadi::ItemFetchJob *job = new Akonadi::ItemFetchJob(items);
    job->fetchScope().fetchFullPayload();
    job->fetchScope().setIgnoreRetrievalErrors(true);

    for (const auto &property : properties.toStdMap()) {
        job->setProperty(property.first, property.second);
    }

    connect(job, &Akonadi::ItemFetchJob::result, this, &ContactInfoProxyModel::slotFetchJobFinished);
}

void ContactInfoProxyModel::slotFetchJobFinished(KJob *job)
{
    if (job->error()) {
        qCWarning(KADDRESSBOOK_LOG) << " error during fetching items" << job->errorString();
        return;
    }
    Akonadi::ItemFetchJob *fetchJob = qobject_cast<Akonadi::ItemFetchJob *>(job);

    const QPersistentModelIndex index = job->property("groupPersistentModelIndex").value<QPersistentModelIndex>();
    const QString groupId = job->property("groupId").value<QString>();
    const QList<QJsonObject> groupRefIdsList = job->property("groupRefIdsList").value<QList<QJsonObject>>();

    for (const QJsonObject &refId : groupRefIdsList) {
        ContactCacheData cacheContact;
        cacheContact.gid = refId[QStringLiteral("gid")].toString();
        cacheContact.uid = refId[QStringLiteral("uid")].toString();

        for (const Akonadi::Item &item : fetchJob->items()) {
            if (item.isValid()) {
                if ((!item.gid().isEmpty() && refId[QStringLiteral("gid")].toString() == item.gid()) ||
                    QString::number(item.id()) == refId[QStringLiteral("uid")].toString()) {
                    if (item.hasPayload<KContacts::Addressee>()) {
                        mMonitor->setItemMonitored(item);
                        const KContacts::Addressee contact = item.payload<KContacts::Addressee>();
                        cacheContact.name = contact.realName();
                        cacheContact.email = contact.preferredEmail();
                    }
                }
            }
        }
        if (mGroupsCache.contains(index)) {
            mGroupsCache[index].append(cacheContact);
        }
    }

    Q_EMIT dataChanged(index, index, mKrole);
    if (mPendingGroups.contains(groupId)) {
        mPendingGroups.removeOne(groupId);
    }
}

void ContactInfoProxyModel::slotItemChanged(const Akonadi::Item &item, const QSet<QByteArray> &partIdentifiers)
{
    Q_UNUSED(partIdentifiers)
    for (const QPersistentModelIndex &index : mGroupsCache.keys()) {
        ContactCacheData::ListIterator it = findCacheItem(index, item);
        if (it != mGroupsCache[index].end()) {
            if (item.isValid()) {
                if (item.hasPayload<KContacts::Addressee>()) {
                    const KContacts::Addressee contact = item.payload<KContacts::Addressee>();
                    it->uid = QString::number(item.id());
                    it->gid = item.gid();
                    it->name = contact.realName();
                    it->email = contact.preferredEmail();
                    Q_EMIT dataChanged(index, index, mKrole);
                }
            }
        }
    }
}

void ContactInfoProxyModel::slotItemRemoved(const Akonadi::Item &item)
{
    if (item.isValid()) {
        for (const QPersistentModelIndex &index : mGroupsCache.keys()) {
            ContactCacheData::List::iterator it = findCacheItem(index, item);

            if (it != mGroupsCache[index].end()) {
                mGroupsCache[index].erase(it);
                Q_EMIT dataChanged(index, index, mKrole);
            }
        }
    }
}

bool operator==(const ContactInfoProxyModel::ContactCacheData &lhs, const ContactInfoProxyModel::ContactCacheData &rhs)
{
    return !lhs.gid.isEmpty() ? lhs.gid == rhs.gid : !lhs.uid.isEmpty() ? lhs.uid == rhs.uid : false;
}