/
recentcontactsmodel.cpp
418 lines (357 loc) · 13.6 KB
/
recentcontactsmodel.cpp
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
/******************************************************************************
**
** This file is part of libcommhistory.
**
** Copyright (C) 2013 Jolla Ltd. <matthew.vogt@jollamobile.com>
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of the GNU Lesser General Public License version 2.1 as
** published by the Free Software Foundation.
**
** 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 "recentcontactsmodel.h"
#include "databaseio_p.h"
#include "commhistorydatabase.h"
#include "eventmodel_p.h"
#include "contactlistener.h"
#include "debug.h"
#include <seasidecache.h>
#include <QContactFavorite>
#include <QSqlQuery>
#include <QSqlError>
namespace CommHistory {
using namespace CommHistory;
static int eventContact(const Event &event)
{
return event.recipients().contactIds().value(0);
}
static bool contactIsFavorite(int contactId)
{
if (SeasideCache::CacheItem *item = SeasideCache::instance()->existingItem(static_cast<quint32>(contactId))) {
QContactFavorite favoriteDetail = item->contact.detail<QContactFavorite>();
return favoriteDetail.isFavorite();
}
return false;
}
class RecentContactsModelPrivate : public EventModelPrivate
{
public:
Q_DECLARE_PUBLIC(RecentContactsModel)
RecentContactsModelPrivate(EventModel *model)
: EventModelPrivate(model),
requiredProperty(RecentContactsModel::NoPropertyRequired),
excludeFavorites(false),
addressFlags(0)
{
setResolveContacts(EventModel::ResolveOnDemand);
}
virtual bool acceptsEvent(const Event &event) const;
virtual bool fillModel(int start, int end, QList<Event> events, bool resolved);
virtual void prependEvents(QList<Event> events, bool resolved);
virtual void slotContactInfoChanged(const RecipientList &recipients);
virtual void slotContactChanged(const RecipientList &recipients);
virtual void slotContactDetailsChanged(const RecipientList &recipients);
private:
void removeFavorites(const RecipientList &recipients);
int requiredProperty;
bool excludeFavorites;
quint64 addressFlags;
QList<Event> unresolvedEvents;
QList<Event> resolvedEvents;
QSet<int> resolvedContactIds;
};
bool RecentContactsModelPrivate::acceptsEvent(const Event &event) const
{
// Contact must be resolved before we can do anything, so just accept
Q_UNUSED(event);
return true;
}
bool RecentContactsModelPrivate::fillModel(int start, int end, QList<Event> events, bool resolved)
{
Q_UNUSED(start);
Q_UNUSED(end);
// This model doesn't fetchMore, so fill is only called once. We can use the prepend logic to get
// the right contact behaviors.
prependEvents(events, resolved);
return true;
}
void RecentContactsModelPrivate::slotContactInfoChanged(const RecipientList &recipients)
{
if (addressFlags != 0) {
// Find if any of these recipients no longer matches our address requirements
QSet<int> nonmatchingIds;
foreach (const Recipient &recipient, recipients) {
if (!recipient.matchesAddressFlags(addressFlags)) {
nonmatchingIds.insert(recipient.contactId());
}
}
if (!nonmatchingIds.isEmpty()) {
// If any of our events no longer resolve to a contact, remove them
int rowCount = eventRootItem->childCount();
for (int row = 0; row < rowCount; ) {
const Event &existing(eventRootItem->eventAt(row));
const int contactId(eventContact(existing));
if (nonmatchingIds.contains(contactId)) {
deleteFromModel(existing.id());
--rowCount;
nonmatchingIds.remove(contactId);
if (nonmatchingIds.isEmpty())
break;
} else {
++row;
}
}
}
}
if (excludeFavorites) {
// We may also need to update for favorite status changes
removeFavorites(recipients);
}
EventModelPrivate::slotContactInfoChanged(recipients);
}
void RecentContactsModelPrivate::slotContactChanged(const RecipientList &recipients)
{
// If any of our events no longer resolve to a contact, remove them
int rowCount = eventRootItem->childCount();
for (int row = 0; row < rowCount; ) {
const Event &existing(eventRootItem->eventAt(row));
if (existing.contactRecipients().isEmpty()) {
deleteFromModel(existing.id());
--rowCount;
} else {
++row;
}
}
EventModelPrivate::slotContactChanged(recipients);
}
void RecentContactsModelPrivate::slotContactDetailsChanged(const RecipientList &recipients)
{
if (excludeFavorites) {
// If any of these contacts have become favorites, they should be removed from our model
removeFavorites(recipients);
}
EventModelPrivate::slotContactDetailsChanged(recipients);
}
void RecentContactsModelPrivate::removeFavorites(const RecipientList &recipients)
{
QList<int> favoriteIds;
foreach (const Recipient &recipient, recipients) {
const int contactId(recipient.contactId());
if (contactIsFavorite(contactId)) {
favoriteIds.append(contactId);
}
}
if (!favoriteIds.isEmpty()) {
int rowCount = eventRootItem->childCount();
for (int row = 0; row < rowCount; ) {
const Event &existing(eventRootItem->eventAt(row));
const int contactId(eventContact(existing));
if (favoriteIds.contains(contactId)) {
deleteFromModel(existing.id());
--rowCount;
} else {
++row;
}
}
}
}
void RecentContactsModelPrivate::prependEvents(QList<Event> events, bool resolved)
{
Q_Q(RecentContactsModel);
QList<Event>::iterator it = events.begin(), end = events.end();
for ( ; it != end; ++it) {
Event &event(*it);
if (eventCategoryMask == Event::AnyCategory || (event.category() & eventCategoryMask) != 0) {
if (!resolved) {
// Queue these events for resolution if required
unresolvedEvents.append(event);
} else {
// Ensure the new events represent different contacts
const Recipient &recipient = event.recipients().first();
const int contactId = recipient.contactId();
if (contactId != 0 && !resolvedContactIds.contains(contactId)) {
// If this contact is a favorite, then don't include the event in our results
if (excludeFavorites && contactIsFavorite(contactId)) {
continue;
}
// Is this contact relevant to our required types?
if (!addressFlags || recipient.matchesAddressFlags(addressFlags)) {
resolvedContactIds.insert(contactId);
resolvedEvents.append(event);
// Don't add any more events than we can present
if (resolvedEvents.count() == queryLimit) {
break;
}
}
}
}
}
}
if (!unresolvedEvents.isEmpty()) {
// Do we have enough items to reach the limit?
if (queryLimit == 0 || resolvedEvents.count() < queryLimit) {
resolveAddedEvents(QList<Event>() << unresolvedEvents.takeFirst());
return;
}
// We won't ever show these events; just drop them
unresolvedEvents.clear();
}
if (!resolvedEvents.isEmpty()) {
// Does the new event replace an existing event?
QSet<int> removeSet;
const int rowCount = eventRootItem->childCount();
for (int row = 0; row < rowCount; ++row) {
const Event &existing(eventRootItem->eventAt(row));
if (resolvedContactIds.contains(eventContact(existing))) {
removeSet.insert(row);
}
}
// Do we need to remove the final event(s) to maintain the limit?
if (queryLimit) {
int trimCount = rowCount + resolvedEvents.count() - removeSet.count() - queryLimit;
int removeIndex = rowCount - 1;
while (trimCount > 0) {
while (removeSet.contains(removeIndex)) {
--removeIndex;
}
if (removeIndex < 0) {
break;
} else {
removeSet.insert(removeIndex);
--removeIndex;
--trimCount;
}
}
}
// Remove the rows that have been made obsolete
QList<int> removeIndices = removeSet.values();
std::sort(removeIndices.begin(), removeIndices.end());
int count;
while ((count = removeIndices.count()) != 0) {
int end = removeIndices.last();
int consecutiveCount = 1;
for ( ; (count - consecutiveCount) > 0; ++consecutiveCount) {
if (removeIndices.at(count - 1 - consecutiveCount) != (end - consecutiveCount)) {
break;
}
}
removeIndices = removeIndices.mid(0, count - consecutiveCount);
int start = (end - consecutiveCount + 1);
q->beginRemoveRows(QModelIndex(), start, end);
while (end >= start) {
eventRootItem->removeAt(end);
--end;
}
q->endRemoveRows();
}
// Insert the new events at the start
int start = 0;
q->beginInsertRows(QModelIndex(), start, resolvedEvents.count() - 1);
QList<Event>::const_iterator it = resolvedEvents.constBegin(), end = resolvedEvents.constEnd();
for ( ; it != end; ++it) {
eventRootItem->insertChildAt(start++, new EventTreeItem(*it, eventRootItem));
}
q->endInsertRows();
resolvedEvents.clear();
resolvedContactIds.clear();
}
if (resolved) {
modelUpdatedSlot(true);
emit q->resolvingChanged();
}
}
RecentContactsModel::RecentContactsModel(QObject *parent)
: EventModel(*new RecentContactsModelPrivate(this), parent)
{
}
RecentContactsModel::~RecentContactsModel()
{
}
int RecentContactsModel::requiredProperty() const
{
Q_D(const RecentContactsModel);
return d->requiredProperty;
}
void RecentContactsModel::setRequiredProperty(int requiredProperty)
{
Q_D(RecentContactsModel);
quint64 addressFlags = 0;
if (requiredProperty & RecentContactsModel::PhoneNumberRequired)
addressFlags |= QContactStatusFlags::HasPhoneNumber;
if (requiredProperty & RecentContactsModel::EmailAddressRequired)
addressFlags |= QContactStatusFlags::HasEmailAddress;
if (requiredProperty & RecentContactsModel::AccountUriRequired)
addressFlags |= QContactStatusFlags::HasOnlineAccount;
d->addressFlags = addressFlags;
if (d->requiredProperty != requiredProperty) {
d->requiredProperty = requiredProperty;
emit requiredPropertyChanged();
}
}
bool RecentContactsModel::excludeFavorites() const
{
Q_D(const RecentContactsModel);
return d->excludeFavorites;
}
void RecentContactsModel::setExcludeFavorites(bool exclude)
{
Q_D(RecentContactsModel);
if (d->excludeFavorites != exclude) {
d->excludeFavorites = exclude;
emit excludeFavoritesChanged();
}
}
bool RecentContactsModel::resolving() const
{
Q_D(const RecentContactsModel);
return !d->isReady || (d->addResolver && d->addResolver->isResolving()) ||
(d->receiveResolver && d->receiveResolver->isResolving());
}
bool RecentContactsModel::getEvents()
{
Q_D(RecentContactsModel);
beginResetModel();
d->clearEvents();
endResetModel();
QString categoryClause, limitClause;
if (d->eventCategoryMask != Event::AnyCategory) {
categoryClause = QStringLiteral("WHERE ") + DatabaseIOPrivate::categoryClause(d->eventCategoryMask);
}
if (d->queryLimit) {
// Default to 4x the configured limit, because some of the addresses may
// resolve to the same final contact, and others will match favorites
limitClause = QStringLiteral("LIMIT ") + QString::number(4 * d->queryLimit);
}
QString q = DatabaseIOPrivate::eventQueryBase() + QString::fromLatin1(
" WHERE Events.id IN ("
" SELECT lastId FROM ("
" SELECT max(id) AS lastId, max(endTime) FROM Events"
" JOIN ("
" SELECT remoteUid, localUid, max(endTime) AS lastEventTime FROM Events"
" %1"
" GROUP BY remoteUid, localUid"
" ORDER BY lastEventTime DESC"
" %2"
" ) AS LastEvent ON Events.endTime = LastEvent.lastEventTime"
" AND Events.remoteUid = LastEvent.remoteUid"
" AND Events.localUid = LastEvent.localUid"
" GROUP BY Events.remoteUid, Events.localUid"
" )"
" )"
" ORDER BY Events.endTime DESC").arg(categoryClause).arg(limitClause);
QSqlQuery query = d->prepareQuery(q, 0, 0);
bool re = d->executeQuery(query);
if (re)
emit resolvingChanged();
return re;
}
} // namespace CommHistory