File: facebooknotificationsdatabase.cpp

package info (click to toggle)
libsocialcache 0.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,160 kB
  • sloc: cpp: 16,261; makefile: 21
file content (546 lines) | stat: -rw-r--r-- 20,513 bytes parent folder | download
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
/*
 * Copyright (C) 2014-2015 Jolla Ltd.
 * Contact: Antti Seppälä <antti.seppala@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 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 Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "facebooknotificationsdatabase.h"
#include "abstractsocialcachedatabase_p.h"
#include "socialsyncinterface.h"

#include <QtSql/QSqlError>
#include <QtCore/QtDebug>

static const char *DB_NAME = "facebookNotifications.db";
static const int VERSION = 1;

struct FacebookNotificationPrivate
{
    explicit FacebookNotificationPrivate(const QString &facebookId, const QString &from, const QString &to,
                                         const QDateTime &createdTime, const QDateTime &updatedTime,
                                         const QString &title, const QString &link,
                                         const QString &application, const QString &object,
                                         bool unread, int accountId, const QString &clientId);

    QString m_facebookId;
    QString m_from;
    QString m_to;
    QDateTime m_createdTime;
    QDateTime m_updatedTime;
    QString m_title;
    QString m_link;
    QString m_application;
    QString m_object;
    bool m_unread;
    int m_accountId;
    QString m_clientId;
};

FacebookNotificationPrivate::FacebookNotificationPrivate(const QString &facebookId, const QString &from, const QString &to,
                                                         const QDateTime &createdTime, const QDateTime &updatedTime,
                                                         const QString &title, const QString &link,
                                                         const QString &application, const QString &object,
                                                         bool unread, int accountId, const QString &clientId)
    : m_facebookId(facebookId)
    , m_from(from)
    , m_to(to)
    , m_createdTime(createdTime)
    , m_updatedTime(updatedTime)
    , m_title(title)
    , m_link(link)
    , m_application(application)
    , m_object(object)
    , m_unread(unread)
    , m_accountId(accountId)
    , m_clientId(clientId)
{
}

FacebookNotification::FacebookNotification(const QString &facebookId, const QString &from, const QString &to,
                                           const QDateTime &createdTime, const QDateTime &updatedTime,
                                           const QString &title, const QString &link,
                                           const QString &application, const QString &object,
                                           bool unread, int accountId, const QString &clientId)
    : d_ptr(new FacebookNotificationPrivate(facebookId, from, to, createdTime, updatedTime, title, link,
                                            application, object, unread, accountId, clientId))
{
}

FacebookNotification::Ptr FacebookNotification::create(const QString &facebookId, const QString &from, const QString &to,
                                                       const QDateTime &createdTime, const QDateTime &updatedTime,
                                                       const QString &title, const QString &link,
                                                       const QString &application, const QString &object,
                                                       bool unread, int accountId, const QString &clientId)
{
    return FacebookNotification::Ptr(new FacebookNotification(facebookId, from, to, createdTime, updatedTime, title, link,
                                                              application, object, unread, accountId, clientId));
}

FacebookNotification::~FacebookNotification()
{
}

QString FacebookNotification::facebookId() const
{
    Q_D(const FacebookNotification);
    return d->m_facebookId;
}

QString FacebookNotification::from() const
{
    Q_D(const FacebookNotification);
    return d->m_from;
}

QString FacebookNotification::to() const
{
    Q_D(const FacebookNotification);
    return d->m_to;
}

QDateTime FacebookNotification::createdTime() const
{
    Q_D(const FacebookNotification);
    return d->m_createdTime;
}

QDateTime FacebookNotification::updatedTime() const
{
    Q_D(const FacebookNotification);
    return d->m_updatedTime;
}

QString FacebookNotification::title() const
{
    Q_D(const FacebookNotification);
    return d->m_title;
}

QString FacebookNotification::link() const
{
    Q_D(const FacebookNotification);
    return d->m_link;
}

QString FacebookNotification::application() const
{
    Q_D(const FacebookNotification);
    return d->m_application;
}

QString FacebookNotification::object() const
{
    Q_D(const FacebookNotification);
    return d->m_object;
}

bool FacebookNotification::unread() const
{
    Q_D(const FacebookNotification);
    return d->m_unread;
}

int FacebookNotification::accountId() const
{
    Q_D(const FacebookNotification);
    return d->m_accountId;
}

QString FacebookNotification::clientId() const
{
    Q_D(const FacebookNotification);
    return d->m_clientId;
}

class FacebookNotificationsDatabasePrivate: public AbstractSocialCacheDatabasePrivate
{
public:
    explicit FacebookNotificationsDatabasePrivate(FacebookNotificationsDatabase *q);

    QMap<int, QList<FacebookNotification::ConstPtr> > insertNotifications;
    QList<int> removeNotificationsFromAccounts;
    QVariantList accountIdFilter;
    QStringList removeNotifications;
    int purgeTimeLimit;

    struct {
        QMap<int, QList<FacebookNotification::ConstPtr> > insertNotifications;
        QList<int> removeNotificationsFromAccounts;
        QStringList removeNotifications;
        bool removeAll;
    } queue;
};

FacebookNotificationsDatabasePrivate::FacebookNotificationsDatabasePrivate(FacebookNotificationsDatabase *q)
    : AbstractSocialCacheDatabasePrivate(
            q,
            SocialSyncInterface::socialNetwork(SocialSyncInterface::Facebook),
            SocialSyncInterface::dataType(SocialSyncInterface::Notifications),
            QLatin1String(DB_NAME),
            VERSION)
    , purgeTimeLimit(0)
{
    queue.removeAll = false;
}

FacebookNotificationsDatabase::FacebookNotificationsDatabase()
    : AbstractSocialCacheDatabase(*(new FacebookNotificationsDatabasePrivate(this)))
{
}

FacebookNotificationsDatabase::~FacebookNotificationsDatabase()
{
    wait();
}

QVariantList FacebookNotificationsDatabase::accountIdFilter() const
{
    Q_D(const FacebookNotificationsDatabase);

    return d->accountIdFilter;
}

void FacebookNotificationsDatabase::setAccountIdFilter(const QVariantList &accountIds)
{
    Q_D(FacebookNotificationsDatabase);

    if (d->accountIdFilter != accountIds) {
        d->accountIdFilter = accountIds;
        emit accountIdFilterChanged();
    }
}

void FacebookNotificationsDatabase::addFacebookNotification(const QString &facebookId, const QString &from, const QString &to,
                                                            const QDateTime &createdTime, const QDateTime &updatedTime,
                                                            const QString &title, const QString &link,
                                                            const QString &application, const QString &object,
                                                            bool unread, int accountId, const QString &clientId)
{
    Q_D(FacebookNotificationsDatabase);
    d->insertNotifications[accountId].append(FacebookNotification::create(facebookId, from, to, createdTime, updatedTime, title, link,
                                                                          application, object, unread, accountId, clientId));
}

void FacebookNotificationsDatabase::removeAllNotifications()
{
    Q_D(FacebookNotificationsDatabase);

    {
        QMutexLocker locker(&d->mutex);
        d->queue.insertNotifications.clear();
        d->queue.removeNotificationsFromAccounts.clear();
        d->queue.removeNotifications.clear();
        d->queue.removeAll = true;
    }

    executeWrite();
}

void FacebookNotificationsDatabase::removeNotifications(int accountId)
{
    Q_D(FacebookNotificationsDatabase);

    QMutexLocker locker(&d->mutex);
    if (!d->queue.removeNotificationsFromAccounts.contains(accountId)) {
        d->queue.removeNotificationsFromAccounts.append(accountId);
    }
    d->queue.insertNotifications.remove(accountId);
}

void FacebookNotificationsDatabase::removeNotification(const QString &notificationId)
{
    Q_D(FacebookNotificationsDatabase);

    QMutexLocker locker(&d->mutex);
    removeNotificationFromQueues(notificationId);
}

void FacebookNotificationsDatabase::removeNotifications(QStringList notificationIds)
{
    Q_D(FacebookNotificationsDatabase);

    QMutexLocker locker(&d->mutex);
    Q_FOREACH(const QString notifId, notificationIds) {
        removeNotificationFromQueues(notifId);
    }
}

void FacebookNotificationsDatabase::purgeOldNotifications(int limitInDays)
{
    Q_D(FacebookNotificationsDatabase);
    d->purgeTimeLimit = limitInDays;
}

void FacebookNotificationsDatabase::removeNotificationFromQueues(const QString &notificationId)
{
    Q_D(FacebookNotificationsDatabase);

    if (!d->queue.removeNotifications.contains(notificationId)) {
        d->queue.removeNotifications.append(notificationId);
        Q_FOREACH(int accountId, d->insertNotifications.keys()) {
            for (int i = 0; i < d->insertNotifications[accountId].count(); ++i) {
                if (d->insertNotifications[accountId][i]->facebookId() == notificationId) {
                    d->insertNotifications[accountId].removeAt(i);
                    i--;
                }
            }
        }
    }
}

void FacebookNotificationsDatabase::sync()
{
    Q_D(FacebookNotificationsDatabase);

    {
        QMutexLocker locker(&d->mutex);
        Q_FOREACH(int accountId, d->insertNotifications.keys()) {
            d->queue.insertNotifications.insert(accountId, d->insertNotifications.take(accountId));
        }
        while (d->removeNotificationsFromAccounts.count()) {
            d->queue.removeNotificationsFromAccounts.append(d->removeNotificationsFromAccounts.takeFirst());
        }
        while (d->removeNotifications.count()) {
            d->queue.removeNotifications.append(d->removeNotifications.takeFirst());
        }
    }

    executeWrite();
}

QList<FacebookNotification::ConstPtr> FacebookNotificationsDatabase::notifications()
{
    Q_D(FacebookNotificationsDatabase);

    QList<FacebookNotification::ConstPtr> data;

    QString queryString = QStringLiteral(
                "SELECT facebookId, accountId, fromStr, toStr, createdTime, updatedTime, title, link, application," \
                "objectStr, unread, clientId FROM notifications");
    if (!d->accountIdFilter.isEmpty()) {
        QStringList accountIds;
        for (int i=0; i<d->accountIdFilter.count(); i++) {
            if (d->accountIdFilter[i].type() == QVariant::Int) {
                accountIds << d->accountIdFilter[i].toString();
            }
        }
        if (accountIds.count()) {
            queryString += " WHERE accountId IN (" + accountIds.join(',') + ')';
        }
    }
    queryString += QStringLiteral(" ORDER BY updatedTime DESC");
    QSqlQuery query = prepare(queryString);

    if (!query.exec()) {
        qWarning() << Q_FUNC_INFO << "Failed to query events" << query.lastError().text();
        return data;
    }

    while (query.next()) {
        data.append(FacebookNotification::create(query.value(0).toString(),                      // facebookId
                                                 query.value(2).toString(),                      // from
                                                 query.value(3).toString(),                      // to
#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)
                                                 QDateTime::fromSecsSinceEpoch(query.value(4).toInt()),  // createdTime
                                                 QDateTime::fromSecsSinceEpoch(query.value(5).toInt()),  // updatedTime
#else
                                                 QDateTime::fromTime_t(query.value(4).toInt()),  // createdTime
                                                 QDateTime::fromTime_t(query.value(5).toInt()),  // updatedTime
#endif
                                                 query.value(6).toString(),                      // title
                                                 query.value(7).toString(),                      // link
                                                 query.value(8).toString(),                      // application
                                                 query.value(9).toString(),                      // object
                                                 query.value(10).toBool(),                       // unread
                                                 query.value(1).toInt(),                         // accountId
                                                 query.value(11).toString()));                   // clientId
    }

    return data;
}

void FacebookNotificationsDatabase::readFinished()
{
    emit notificationsChanged();
}

bool FacebookNotificationsDatabase::write()
{
    Q_D(FacebookNotificationsDatabase);

    QMutexLocker locker(&d->mutex);

    const QMap<int, QList<FacebookNotification::ConstPtr> > insertNotifications = d->queue.insertNotifications;
    const QList<int> removeNotificationsFromAccounts = d->queue.removeNotificationsFromAccounts;
    QStringList removeNotifications = d->queue.removeNotifications;
    bool removeAll = d->queue.removeAll;

    d->queue.insertNotifications.clear();
    d->queue.removeNotificationsFromAccounts.clear();
    d->queue.removeNotifications.clear();
    d->queue.removeAll = false;

    locker.unlock();

    bool success = true;
    QSqlQuery query;

    if (removeAll) {
        QVariantList accountIds;
        accountIds.append(-1);

        query = prepare(QStringLiteral("DELETE FROM notifications WHERE accountId > :accountId"));
        query.bindValue(QStringLiteral(":accountId"), accountIds);
        executeBatchSocialCacheQuery(query);
    }

    if (!removeNotificationsFromAccounts.isEmpty()) {
        QVariantList accountIds;

        Q_FOREACH (const int accountId, removeNotificationsFromAccounts) {
            accountIds.append(accountId);
        }

        query = prepare(QStringLiteral("DELETE FROM notifications WHERE accountId = :accountId"));
        query.bindValue(QStringLiteral(":accountId"), accountIds);
        executeBatchSocialCacheQuery(query);
    }

    if (!removeNotifications.isEmpty()) {
        QVariantList notifIds;

        Q_FOREACH (const QString notifId, removeNotifications) {
            notifIds.append(notifId);
        }

        query = prepare(QStringLiteral("DELETE FROM notifications WHERE facebookId = :facebookId"));
        query.bindValue(QStringLiteral(":facebookId"), notifIds);
        executeBatchSocialCacheQuery(query);
    }

    if (!insertNotifications.isEmpty()) {
        QVariantList facebookIds;
        QVariantList accountIds;
        QVariantList fromStrings;
        QVariantList toStrings;
        QVariantList createdTimes;
        QVariantList updatedTimes;
        QVariantList titles;
        QVariantList links;
        QVariantList applications;
        QVariantList unreads;
        QVariantList objects;
        QVariantList clientIds;

        Q_FOREACH (const QList<FacebookNotification::ConstPtr> &notifications, insertNotifications) {
            Q_FOREACH (const FacebookNotification::ConstPtr &notification, notifications) {
                facebookIds.append(notification->facebookId());
                accountIds.append(notification->accountId());
                fromStrings.append(notification->from());
                toStrings.append(notification->to());
#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)
                createdTimes.append(notification->createdTime().toSecsSinceEpoch());
                updatedTimes.append(notification->updatedTime().toSecsSinceEpoch());
#else
                createdTimes.append(notification->createdTime().toTime_t());
                updatedTimes.append(notification->updatedTime().toTime_t());
#endif
                titles.append(notification->title());
                links.append(notification->link());
                applications.append(notification->application());
                objects.append(notification->object());
                unreads.append((notification->unread()));
                clientIds.append(notification->clientId());
            }
        }

        query = prepare(QStringLiteral(
                    "INSERT OR REPLACE INTO notifications ("
                    " facebookId, accountId, fromStr, toStr, createdTime, updatedTime, title, link, application, objectStr, unread, clientId) "
                    "VALUES("
                    " :facebookId, :accountId, :fromStr, :toStr, :createdTime, :updatedTime, :title, :link, :application, :objectStr, :unread, :clientId)"));
        query.bindValue(QStringLiteral(":facebookId"), facebookIds);
        query.bindValue(QStringLiteral(":accountId"), accountIds);
        query.bindValue(QStringLiteral(":fromStr"), fromStrings);
        query.bindValue(QStringLiteral(":toStr"), toStrings);
        query.bindValue(QStringLiteral(":createdTime"), createdTimes);
        query.bindValue(QStringLiteral(":updatedTime"), updatedTimes);
        query.bindValue(QStringLiteral(":title"), titles);
        query.bindValue(QStringLiteral(":link"), links);
        query.bindValue(QStringLiteral(":application"), applications);
        query.bindValue(QStringLiteral(":objectStr"), objects);
        query.bindValue(QStringLiteral(":unread"), unreads);
        query.bindValue(QStringLiteral(":clientId"), clientIds);

        executeBatchSocialCacheQuery(query);
    }

    if (d->purgeTimeLimit > 0) {
        QVariantList limits;
        // purge notifications older than expirationTime in days
#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)
        const quint32 limit = QDateTime::currentDateTime().toSecsSinceEpoch() - d->purgeTimeLimit * 24 * 60 * 60;
#else
        const quint32 limit = QDateTime::currentDateTime().toTime_t() - d->purgeTimeLimit * 24 * 60 * 60;
#endif
        limits.append(limit);
        query = prepare(QStringLiteral("DELETE FROM notifications WHERE updatedTime < :timeLimit"));
        query.bindValue(QStringLiteral(":timeLimit"), limits);
        executeBatchSocialCacheQuery(query);
        d->purgeTimeLimit = 0;
    }

    return success;
}

bool FacebookNotificationsDatabase::createTables(QSqlDatabase database) const
{
    QSqlQuery query(database);

    // create the Facebook notification db tables
    // notifications = facebookId, accountId, from, to, createdTime, updatedTime, title, link, application, objectStr, unread, clientId
    query.prepare("CREATE TABLE IF NOT EXISTS notifications ("
                  "facebookId TEXT UNIQUE PRIMARY KEY,"
                  "accountId INTEGER,"
                  "fromStr TEXT,"
                  "toStr TEXT,"
                  "createdTime INTEGER,"
                  "updatedTime INTEGER,"
                  "title TEXT,"
                  "link TEXT,"
                  "application TEXT,"
                  "objectStr TEXT,"
                  "unread INTEGER,"
                  "clientId TEXT)");
    if (!query.exec()) {
        qWarning() << Q_FUNC_INFO << "Unable to create notifications table: " << query.lastError().text();
        return false;
    }

    return true;
}

bool FacebookNotificationsDatabase::dropTables(QSqlDatabase database) const
{
    QSqlQuery query(database);

    if (!query.exec(QStringLiteral("DROP TABLE IF EXISTS notifications"))) {
        qWarning() << Q_FUNC_INFO << "Unable to delete notifications table: " << query.lastError().text();
        return false;
    }

    return true;
}