/
notificationmanager.cpp
1212 lines (1042 loc) · 47.1 KB
/
notificationmanager.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
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
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
**
** Copyright (c) 2012 - 2019 Jolla Ltd.
** Copyright (c) 2019 Open Mobile Platform LLC.
**
** Contact: Robin Burchell <robin.burchell@jollamobile.com>
**
** This file is part of lipstick.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QCoreApplication>
#include <QDebug>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlTableModel>
#include <QStandardPaths>
#include <QFile>
#include <QFileInfo>
#include <aboutsettings.h>
#include <mremoteaction.h>
#include <mdesktopentry.h>
#include <sys/statfs.h>
#include <limits>
#include "androidprioritystore.h"
#include "categorydefinitionstore.h"
#include "notificationmanageradaptor.h"
#include "notificationmanager.h"
// Define this if you'd like to see debug messages from the notification manager
#ifdef DEBUG_NOTIFICATIONS
#define NOTIFICATIONS_DEBUG(things) qDebug() << Q_FUNC_INFO << things
#else
#define NOTIFICATIONS_DEBUG(things)
#endif
//! The android priority store path
static const char *ANDROID_PRIORITY_DEFINITION_PATH = "/usr/share/lipstick/androidnotificationpriorities";
//! The android bridge process name
static const char *ANDROID_BRIDGE_PROCESS = "alien_bridge_server";
//! The category definitions directory
static const char *CATEGORY_DEFINITION_FILE_DIRECTORY = "/usr/share/lipstick/notificationcategories";
//! The number configuration files to load into the event type store.
static const uint MAX_CATEGORY_DEFINITION_FILES = 100;
//! Path to probe for desktop entries
static const char *DESKTOP_ENTRY_PATH = "/usr/share/applications/";
//! Minimum amount of disk space needed for the notification database in kilobytes
static const uint MINIMUM_FREE_SPACE_NEEDED_IN_KB = 1024;
// Exported for unit test:
int MaxNotificationRestoreCount = 1000;
namespace {
const int DefaultNotificationPriority = 50;
const int CommitDelay = 10 * 1000;
const int PublicationDelay = 1000;
QString getProcessName(uint pid)
{
if (pid > 1) {
const QString procFilename(QString::fromLatin1("/proc/%1/cmdline").arg(QString::number(pid)));
QFile procFile(procFilename);
if (procFile.open(QIODevice::ReadOnly)) {
const QByteArray cmdLine = procFile.readAll();
QString processNameWithPath = QFile::decodeName(cmdLine.left(cmdLine.indexOf('\0')));
return QFileInfo(processNameWithPath).fileName();
}
}
return QString();
}
QPair<QString, QString> processProperties(uint pid)
{
// Cache resolution of process name to properties:
static QHash<QString, QPair<QString, QString> > nameProperties;
QPair<QString, QString> rv;
if (pid == QCoreApplication::applicationPid()) {
// This notification comes from our process
rv.first = QCoreApplication::applicationName();
} else {
const QString processName = getProcessName(pid);
if (!processName.isEmpty()) {
QHash<QString, QPair<QString, QString> >::iterator it = nameProperties.find(processName);
if (it == nameProperties.end()) {
// Look up the desktop entry for this process name
MDesktopEntry desktopEntry(DESKTOP_ENTRY_PATH + processName + ".desktop");
if (desktopEntry.isValid()) {
it = nameProperties.insert(processName, qMakePair(desktopEntry.name(), desktopEntry.icon()));
} else {
qWarning() << "No desktop entry for process name:" << processName;
// Fallback to the processName for application name
it = nameProperties.insert(processName, qMakePair(processName, QString()));
}
}
if (it != nameProperties.end()) {
rv.first = it->first;
rv.second = it->second;
}
} else {
qWarning() << "Unable to retrieve process name for pid:" << pid;
}
}
return rv;
}
bool notificationReverseOrder(const LipstickNotification *lhs, const LipstickNotification *rhs)
{
// Sort least significant notifications first
return *rhs < *lhs;
}
}
NotificationManager *NotificationManager::s_instance = 0;
NotificationManager *NotificationManager::instance(bool owner)
{
if (s_instance == 0) {
s_instance = new NotificationManager(qApp, owner);
}
return s_instance;
}
NotificationManager::NotificationManager(QObject *parent, bool owner) :
QObject(parent),
QDBusContext(),
m_previousNotificationID(0),
m_categoryDefinitionStore(new CategoryDefinitionStore(CATEGORY_DEFINITION_FILE_DIRECTORY, MAX_CATEGORY_DEFINITION_FILES, this)),
m_androidPriorityStore(new AndroidPriorityStore(ANDROID_PRIORITY_DEFINITION_PATH, this)),
m_database(new QSqlDatabase),
m_committed(true),
m_nextExpirationTime(0)
{
if (owner) {
qDBusRegisterMetaType<QVariantHash>();
qDBusRegisterMetaType<LipstickNotification>();
qDBusRegisterMetaType<NotificationList>();
new NotificationManagerAdaptor(this);
QDBusConnection::sessionBus().registerObject("/org/freedesktop/Notifications", this);
QDBusConnection::sessionBus().registerService("org.freedesktop.Notifications");
connect(m_categoryDefinitionStore, SIGNAL(categoryDefinitionUninstalled(QString)), this, SLOT(removeNotificationsWithCategory(QString)));
connect(m_categoryDefinitionStore, SIGNAL(categoryDefinitionModified(QString)), this, SLOT(updateNotificationsWithCategory(QString)));
// Commit the modifications to the database 10 seconds after the last modification so that writing to disk doesn't affect user experience
m_databaseCommitTimer.setInterval(CommitDelay);
m_databaseCommitTimer.setSingleShot(true);
connect(&m_databaseCommitTimer, SIGNAL(timeout()), this, SLOT(commit()));
m_expirationTimer.setSingleShot(true);
connect(&m_expirationTimer, SIGNAL(timeout()), this, SLOT(expire()));
m_modificationTimer.setInterval(PublicationDelay);
m_modificationTimer.setSingleShot(true);
connect(&m_modificationTimer, SIGNAL(timeout()), this, SLOT(reportModifications()));
}
restoreNotifications(owner);
}
NotificationManager::~NotificationManager()
{
m_database->commit();
delete m_database;
}
LipstickNotification *NotificationManager::notification(uint id) const
{
return m_notifications.value(id);
}
QList<uint> NotificationManager::notificationIds() const
{
return m_notifications.keys();
}
QStringList NotificationManager::GetCapabilities()
{
return QStringList() << "body"
<< "actions"
<< "persistence"
<< LipstickNotification::HINT_ICON
<< LipstickNotification::HINT_ITEM_COUNT
<< LipstickNotification::HINT_TIMESTAMP
<< LipstickNotification::HINT_PREVIEW_ICON
<< LipstickNotification::HINT_PREVIEW_BODY
<< LipstickNotification::HINT_PREVIEW_SUMMARY
<< "x-nemo-remote-actions"
<< LipstickNotification::HINT_USER_REMOVABLE
<< LipstickNotification::HINT_ORIGIN
<< LipstickNotification::HINT_MAX_CONTENT_LINES
<< "x-nemo-get-notifications";
}
uint NotificationManager::Notify(const QString &appName, uint replacesId, const QString &appIcon,
const QString &summary, const QString &body, const QStringList &actions,
const QVariantHash &hints, int expireTimeout)
{
NOTIFICATIONS_DEBUG("NOTIFY:" << appName << replacesId << appIcon << summary << body << actions << hints << expireTimeout);
if (replacesId != 0 && !m_notifications.contains(replacesId)) {
replacesId = 0;
}
uint id = replacesId != 0 ? replacesId : nextAvailableNotificationID();
QVariantHash hints_(hints);
// Ensure the hints contain a timestamp, and convert to UTC if required
QString timestamp(hints_.value(LipstickNotification::HINT_TIMESTAMP).toString());
if (!timestamp.isEmpty()) {
QDateTime tsValue(QDateTime::fromString(timestamp, Qt::ISODate));
if (tsValue.isValid()) {
if (tsValue.timeSpec() != Qt::UTC) {
tsValue = tsValue.toUTC();
}
timestamp = tsValue.toString(Qt::ISODate);
} else {
timestamp = QString();
}
}
if (timestamp.isEmpty()) {
timestamp = QDateTime::currentDateTimeUtc().toString(Qt::ISODate);
}
hints_.insert(LipstickNotification::HINT_TIMESTAMP, timestamp);
QPair<QString, QString> pidProperties;
bool androidOrigin(false);
if (calledFromDBus()) {
// Look up the properties of the originating process
const QString callerService(message().service());
const QDBusReply<uint> pidReply(connection().interface()->servicePid(callerService));
if (pidReply.isValid()) {
pidProperties = processProperties(pidReply.value());
androidOrigin = (pidProperties.first == QString::fromLatin1(ANDROID_BRIDGE_PROCESS));
}
}
// Allow notifications originating from android to be differentiated from native app notifications
QString disambiguatedAppName(appName);
if (androidOrigin) {
disambiguatedAppName.append("-android");
}
LipstickNotification notificationData(
appName, disambiguatedAppName, id, appIcon, summary, body, actions, hints_, expireTimeout);
applyCategoryDefinition(¬ificationData);
hints_ = notificationData.hints();
if (!notificationData.isUserRemovableByHint() && !isPrivileged()) {
qWarning() << "Persistent notification from"
<< qPrintable(pidProperties.first)
<< "dropped because of insufficent permissions";
return 0;
}
LipstickNotification *notification = replacesId != 0
? m_notifications.value(replacesId)
: nullptr;
if (notification) {
if (!notification->isUserRemovableByHint() && !isPrivileged()) {
qWarning() << "An alteration to a persistent notification by"
<< qPrintable(pidProperties.first)
<< "was ignored because of insufficent permissions";
return 0;
}
notification->setAppName(notificationData.appName());
notification->setDisambiguatedAppName(notificationData.disambiguatedAppName());
notification->setAppIcon(notificationData.appIcon());
notification->setSummary(notificationData.summary());
notification->setBody(notificationData.body());
notification->setActions(notificationData.actions());
notification->setHints(notificationData.hints());
notification->setExpireTimeout(notificationData.expireTimeout());
} else {
notification = new LipstickNotification(notificationData);
notification->setParent(this);
connect(notification, &LipstickNotification::actionInvoked,
this, &NotificationManager::invokeAction, Qt::QueuedConnection);
connect(notification, &LipstickNotification::removeRequested, // default prevents direction connection.
this, [this]() { removeNotificationIfUserRemovable(); }, Qt::QueuedConnection);
m_notifications.insert(id, notification);
}
notification->restartProgressTimer();
if (androidOrigin) {
// The app icon should also be the nemo icon
const QString icon(hints_.value(LipstickNotification::HINT_ICON).toString());
if (icon.isEmpty()) {
hints_.insert(LipstickNotification::HINT_ICON, appIcon);
}
// If this notification includes a preview, ensure it has a non-empty body and summary
const QString previewSummary(hints_.value(LipstickNotification::HINT_PREVIEW_SUMMARY).toString());
const QString previewBody(hints_.value(LipstickNotification::HINT_PREVIEW_BODY).toString());
if (!previewSummary.isEmpty()) {
if (previewBody.isEmpty()) {
hints_.insert(LipstickNotification::HINT_PREVIEW_BODY, QStringLiteral(" "));
}
}
if (!previewBody.isEmpty()) {
if (previewSummary.isEmpty()) {
hints_.insert(LipstickNotification::HINT_PREVIEW_SUMMARY, QStringLiteral(" "));
}
}
// See if this notification has elevated priority and feedback
AndroidPriorityStore::PriorityDetails priority;
const QString packageName(hints_.value(LipstickNotification::HINT_ORIGIN_PACKAGE).toString());
if (!packageName.isEmpty()) {
priority = m_androidPriorityStore->packageDetails(packageName);
} else {
priority = m_androidPriorityStore->appDetails(appName);
}
hints_.insert(LipstickNotification::HINT_PRIORITY, priority.first);
if (!priority.second.isEmpty()) {
hints_.insert(LipstickNotification::HINT_FEEDBACK, priority.second);
// Also turn the display on if required, but only if it's really playing vibra or sound feedback
if (hints_.value(LipstickNotification::HINT_VIBRA, false).toBool()
|| !hints_.value(LipstickNotification::HINT_SUPPRESS_SOUND, false).toBool()) {
hints_.insert(LipstickNotification::HINT_DISPLAY_ON, true);
}
}
} else {
if (notification->appName().isEmpty() && !pidProperties.first.isEmpty()) {
notification->setAppName(pidProperties.first);
}
if (notification->appIcon().isEmpty() && !pidProperties.second.isEmpty()) {
notification->setAppIcon(pidProperties.second);
}
// Unspecified priority should result in medium priority to permit low priorities
if (!hints_.contains(LipstickNotification::HINT_PRIORITY)) {
hints_.insert(LipstickNotification::HINT_PRIORITY, DefaultNotificationPriority);
}
}
notification->setHints(hints_);
publish(notification, replacesId);
return id;
}
void NotificationManager::deleteNotification(uint id)
{
// Remove the notification, its actions and its hints from database
const QVariantList params(QVariantList() << id);
execSQL(QString("DELETE FROM notifications WHERE id=?"), params);
execSQL(QString("DELETE FROM actions WHERE id=?"), params);
execSQL(QString("DELETE FROM hints WHERE id=?"), params);
execSQL(QString("DELETE FROM expiration WHERE id=?"), params);
}
void NotificationManager::CloseNotification(uint id, NotificationClosedReason closeReason)
{
if (LipstickNotification *notification = m_notifications.value(id)) {
if (!notification->isUserRemovableByHint() && !isPrivileged()) {
qWarning() << "An application was not allowed to close a notification due to insufficient permissions";
return;
}
emit NotificationClosed(id, closeReason);
deleteNotification(id);
NOTIFICATIONS_DEBUG("REMOVE:" << id);
emit notificationRemoved(id);
// Mark the notification to be destroyed
m_removedNotifications.insert(m_notifications.take(id));
}
}
void NotificationManager::closeNotifications(const QList<uint> &ids, NotificationClosedReason closeReason)
{
QSet<uint> uniqueIds = QSet<uint>::fromList(ids);
QList<uint> removedIds;
foreach (uint id, uniqueIds) {
if (m_notifications.contains(id)) {
removedIds.append(id);
emit NotificationClosed(id, closeReason);
deleteNotification(id);
}
}
if (!removedIds.isEmpty()) {
NOTIFICATIONS_DEBUG("REMOVE:" << removedIds);
emit notificationsRemoved(removedIds);
foreach (uint id, removedIds) {
emit notificationRemoved(id);
// Mark the notification to be destroyed
m_removedNotifications.insert(m_notifications.take(id));
}
}
}
void NotificationManager::markNotificationDisplayed(uint id)
{
if (m_notifications.contains(id)) {
const LipstickNotification *notification = m_notifications.value(id);
if (notification->hints().value(LipstickNotification::HINT_TRANSIENT).toBool()) {
// Remove this notification immediately
CloseNotification(id, NotificationExpired);
NOTIFICATIONS_DEBUG("REMOVED transient:" << id);
} else {
const int timeout(notification->expireTimeout());
if (timeout > 0) {
// Insert the timeout into the expiration table, or leave the existing value if already present
const qint64 currentTime(QDateTime::currentDateTimeUtc().toMSecsSinceEpoch());
const qint64 expireAt(currentTime + timeout);
execSQL(QString("INSERT OR IGNORE INTO expiration(id, expire_at) VALUES(?, ?)"), QVariantList() << id << expireAt);
if (m_nextExpirationTime == 0 || (expireAt < m_nextExpirationTime)) {
// This will be the next notification to expire - update the timer
m_nextExpirationTime = expireAt;
m_expirationTimer.start(timeout);
}
NOTIFICATIONS_DEBUG("DISPLAYED:" << id << "expiring in:" << timeout);
}
}
}
}
QString NotificationManager::GetServerInformation(QString &vendor, QString &version, QString &spec_version)
{
QString name = qApp->applicationName();
AboutSettings settings;
vendor = settings.operatingSystemName();
version = qApp->applicationVersion();
spec_version = "1.2";
return name;
}
NotificationList NotificationManager::GetNotifications(const QString &owner)
{
uint pid = callerProcessId();
QString callerProcessName = getProcessName(pid);
QList<LipstickNotification *> notificationList;
QHash<uint, LipstickNotification *>::const_iterator it = m_notifications.constBegin(), end = m_notifications.constEnd();
for ( ; it != end; ++it) {
LipstickNotification *notification = it.value();
if (notification->owner() == owner || (!callerProcessName.isEmpty() && (notification->owner() == callerProcessName))) {
notificationList.append(notification);
}
}
return NotificationList(notificationList);
}
NotificationList NotificationManager::GetNotificationsByCategory(const QString &category)
{
QList<LipstickNotification *> notificationList;
if (isPrivileged()) {
QHash<uint, LipstickNotification *>::const_iterator it = m_notifications.constBegin(), end = m_notifications.constEnd();
for ( ; it != end; ++it) {
LipstickNotification *notification = it.value();
if (notification->category() == category) {
notificationList.append(notification);
}
}
}
return NotificationList(notificationList);
}
QString NotificationManager::systemApplicationName() const
{
//% "System"
return qtTrId("qtn_ap_lipstick");
}
uint NotificationManager::nextAvailableNotificationID()
{
/* Find an unused ID. It is assumed that we will never end up
* in a situation where even close to significant portion of
* all possible ID numbers would be in use. If that ever happens
* this will turn into forever loop.
*/
for (;;) {
uint id = ++m_previousNotificationID;
// 0 is not a valid ID so skip it
if (!id)
continue;
if (!m_notifications.contains(id))
return id;
}
}
void NotificationManager::removeNotificationsWithCategory(const QString &category)
{
QList<uint> ids;
QHash<uint, LipstickNotification *>::const_iterator it = m_notifications.constBegin(), end = m_notifications.constEnd();
for ( ; it != end; ++it) {
LipstickNotification *notification(it.value());
if (notification->category() == category) {
ids.append(it.key());
}
}
closeNotifications(ids);
}
void NotificationManager::updateNotificationsWithCategory(const QString &category)
{
QList<LipstickNotification *> categoryNotifications;
QHash<uint, LipstickNotification *>::const_iterator it = m_notifications.constBegin(), end = m_notifications.constEnd();
for ( ; it != end; ++it) {
LipstickNotification *notification(it.value());
if (notification->category() == category) {
categoryNotifications.append(notification);
}
}
foreach (LipstickNotification *notification, categoryNotifications) {
// Mark the notification as restored to avoid showing the preview banner again
QVariantHash hints = notification->hints();
hints.insert(LipstickNotification::HINT_RESTORED, true);
notification->setHints(hints);
// Update the category properties and re-publish
applyCategoryDefinition(notification);
publish(notification, notification->id());
}
}
QHash<QString, QString> NotificationManager::categoryDefinitionParameters(const QVariantHash &hints) const
{
return m_categoryDefinitionStore->categoryParameters(hints.value(LipstickNotification::HINT_CATEGORY).toString());
}
void NotificationManager::applyCategoryDefinition(LipstickNotification *notification) const
{
QVariantHash hints = notification->hints();
// Apply a category definition, if any
const QHash<QString, QString> categoryParameters(categoryDefinitionParameters(hints));
QHash<QString, QString>::const_iterator it = categoryParameters.constBegin(), end = categoryParameters.constEnd();
for ( ; it != end; ++it) {
const QString &key(it.key());
const QString &value(it.value());
// TODO: this is wrong - in some cases we need to overwrite any existing value...
// What would get broken by doing this?
if (key == QString("appName")) {
if (notification->appName().isEmpty()) {
notification->setAppName(value);
}
} else if (key == QString("appIcon")) {
if (notification->appIcon().isEmpty()) {
notification->setAppIcon(value);
}
} else if (key == QString("summary")) {
if (notification->summary().isEmpty()) {
notification->setSummary(value);
}
} else if (key == QString("body")) {
if (notification->body().isEmpty()) {
notification->setBody(value);
}
} else if (key == QString("expireTimeout")) {
if (notification->expireTimeout() == -1) {
notification->setExpireTimeout(value.toInt());
}
} else if (!hints.contains(key)) {
hints.insert(key, value);
}
}
notification->setHints(hints);
}
void NotificationManager::publish(const LipstickNotification *notification, uint replacesId)
{
const uint id(notification->id());
if (id == 0) {
qWarning() << "Cannot publish notification without ID!";
return;
} else if (replacesId != 0 && replacesId != id) {
qWarning() << "Cannot publish notification replacing independent ID!";
return;
}
if (replacesId != 0) {
// Delete the existing notification from the database
deleteNotification(id);
}
// Add the notification, its actions and its hints to the database
execSQL("INSERT INTO notifications VALUES (?, ?, ?, ?, ?, ?, ?)",
QVariantList() << id << notification->appName() << notification->appIcon() << notification->summary()
<< notification->body() << notification->expireTimeout() << notification->disambiguatedAppName());
// every other is identifier and every other the localized name for it
bool everySecond = false;
QString action;
foreach (const QString &actionItem, notification->actions()) {
if (everySecond) {
if (!action.isEmpty()) {
execSQL("INSERT INTO actions VALUES (?, ?, ?)", QVariantList() << id << action << actionItem);
}
} else {
action = actionItem;
}
everySecond = !everySecond;
}
const QVariantHash hints(notification->hints());
QVariantHash::const_iterator hit = hints.constBegin(), hend = hints.constEnd();
for ( ; hit != hend; ++hit) {
execSQL("INSERT INTO hints VALUES (?, ?, ?)", QVariantList() << id << hit.key() << hit.value());
}
NOTIFICATIONS_DEBUG("PUBLISH:" << notification->appName() << notification->appIcon() << notification->summary()
<< notification->body() << notification->actions() << notification->hints()
<< notification->expireTimeout() << "->" << id);
m_modifiedIds.insert(id);
if (!m_modificationTimer.isActive()) {
m_modificationTimer.start();
}
if (replacesId == 0) {
emit notificationAdded(id);
} else {
emit notificationModified(id);
}
}
void NotificationManager::restoreNotifications(bool update)
{
if (connectToDatabase()) {
if (checkTableValidity()) {
fetchData(update);
} else {
m_database->close();
}
}
}
bool NotificationManager::connectToDatabase()
{
QString databasePath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/system/privileged/Notifications");
if (!QDir::root().exists(databasePath)) {
QDir::root().mkpath(databasePath);
}
QString databaseName = databasePath + "/notifications.db";
*m_database = QSqlDatabase::addDatabase("QSQLITE", metaObject()->className());
m_database->setDatabaseName(databaseName);
bool success = checkForDiskSpace(databasePath, MINIMUM_FREE_SPACE_NEEDED_IN_KB);
if (success) {
success = m_database->open();
if (!success) {
NOTIFICATIONS_DEBUG(m_database->lastError().driverText() << databaseName << m_database->lastError().databaseText());
// If opening the database fails, try to recreate the database
removeDatabaseFile(databaseName);
success = m_database->open();
NOTIFICATIONS_DEBUG("Unable to open database file. Recreating. Success: " << success);
}
} else {
NOTIFICATIONS_DEBUG("Not enough free disk space available. Unable to open database.");
}
if (success) {
// Set up the database mode to write-ahead locking to improve performance
QSqlQuery(*m_database).exec("PRAGMA journal_mode=WAL");
}
return success;
}
bool NotificationManager::checkForDiskSpace(const QString &path, unsigned long freeSpaceNeeded)
{
struct statfs st;
bool spaceAvailable = false;
if (statfs(path.toUtf8().data(), &st) != -1) {
unsigned long freeSpaceInKb = (st.f_bsize * st.f_bavail) / 1024;
if (freeSpaceInKb > freeSpaceNeeded) {
spaceAvailable = true;
}
}
return spaceAvailable;
}
void NotificationManager::removeDatabaseFile(const QString &path)
{
// Remove also -shm and -wal files created when journal-mode=WAL is being used
QDir::root().remove(path + "-shm");
QDir::root().remove(path + "-wal");
QDir::root().remove(path);
}
bool NotificationManager::checkTableValidity()
{
bool result = true;
bool recreateNotificationsTable = false;
bool recreateActionsTable = false;
bool recreateHintsTable = false;
bool recreateExpirationTable = false;
const int databaseVersion(schemaVersion());
if (databaseVersion == 0) {
// Unmodified database - remove any existing notifications, which might cause problems
qWarning() << "Removing obsolete notifications";
recreateNotificationsTable = true;
recreateActionsTable = true;
recreateHintsTable = true;
recreateExpirationTable = true;
} else if (databaseVersion == 1) {
// Check that the table schemas are as expected
recreateNotificationsTable = !verifyTableColumns("notifications",
QStringList() << "id" << "app_name" << "app_icon" << "summary"
<< "body" << "expire_timeout");
recreateActionsTable = !verifyTableColumns("actions", QStringList() << "id" << "action" << "display_name");
recreateHintsTable = !verifyTableColumns("hints", QStringList() << "id" << "hint" << "value");
recreateExpirationTable = !verifyTableColumns("expiration", QStringList() << "id" << "expire_at");
// Extend the notifications table with the disambiguated_app_name column
QSqlQuery query(*m_database);
if (query.exec("ALTER TABLE notifications ADD COLUMN disambiguated_app_name TEXT") &&
query.exec("UPDATE notifications SET disambiguated_app_name = app_name")) {
qWarning() << "Extended notifications table";
} else {
qWarning() << "Failed to extend notifications table!";
recreateNotificationsTable = true;
}
} else {
if (databaseVersion == 2) {
QSqlQuery query(*m_database);
if (query.exec("ALTER TABLE actions ADD COLUMN display_name TEXT")) {
qWarning() << "Extended actions table";
} else {
qWarning() << "Failed to extend actions table!";
recreateActionsTable = true;
}
} else {
recreateActionsTable = !verifyTableColumns("actions", QStringList() << "id" << "action" << "display_name");
}
recreateNotificationsTable = !verifyTableColumns("notifications",
QStringList() << "id" << "app_name" << "app_icon" << "summary"
<< "body" << "expire_timeout" << "disambiguated_app_name");
recreateHintsTable = !verifyTableColumns("hints", QStringList() << "id" << "hint" << "value");
recreateExpirationTable = !verifyTableColumns("expiration", QStringList() << "id" << "expire_at");
}
if (recreateNotificationsTable) {
qWarning() << "Recreating notifications table";
result &= recreateTable("notifications", "id INTEGER PRIMARY KEY, app_name TEXT, app_icon TEXT, summary TEXT, body TEXT, expire_timeout INTEGER, disambiguated_app_name TEXT");
}
if (recreateActionsTable) {
qWarning() << "Recreating actions table";
result &= recreateTable("actions", "id INTEGER, action TEXT, display_name TEXT, PRIMARY KEY(id, action)");
}
if (recreateHintsTable) {
qWarning() << "Recreating hints table";
result &= recreateTable("hints", "id INTEGER, hint TEXT, value TEXT, PRIMARY KEY(id, hint)");
}
if (recreateExpirationTable) {
qWarning() << "Recreating expiration table";
result &= recreateTable("expiration", "id INTEGER PRIMARY KEY, expire_at INTEGER");
}
if (result && databaseVersion != 3) {
if (!setSchemaVersion(3)) {
qWarning() << "Unable to set database schema version!";
}
}
return result;
}
int NotificationManager::schemaVersion()
{
int result = -1;
if (m_database->isOpen()) {
QSqlQuery query(*m_database);
if (query.exec("PRAGMA user_version") && query.next()) {
result = query.value(0).toInt();
}
}
return result;
}
bool NotificationManager::setSchemaVersion(int version)
{
bool result = false;
if (m_database->isOpen()) {
QSqlQuery query(*m_database);
if (query.exec(QString::fromLatin1("PRAGMA user_version=%1").arg(version))) {
result = true;
}
}
return result;
}
bool NotificationManager::verifyTableColumns(const QString &tableName, const QStringList &columnNames)
{
QSqlTableModel tableModel(0, *m_database);
tableModel.setTable(tableName);
// The order of the columns must be correct
int index = 0;
foreach (const QString &columnName, columnNames) {
if (tableModel.fieldIndex(columnName) != index)
return false;
++index;
}
return true;
}
bool NotificationManager::recreateTable(const QString &tableName, const QString &definition)
{
bool result = false;
if (m_database->isOpen()) {
QSqlQuery(*m_database).exec("DROP TABLE " + tableName);
result = QSqlQuery(*m_database).exec("CREATE TABLE " + tableName + " (" + definition + ")");
}
return result;
}
void NotificationManager::fetchData(bool update)
{
// Gather actions for each notification
QSqlQuery actionsQuery("SELECT * FROM actions", *m_database);
QSqlRecord actionsRecord = actionsQuery.record();
int actionsTableIdFieldIndex = actionsRecord.indexOf("id");
int actionsTableActionFieldIndex = actionsRecord.indexOf("action");
int actionsTableNameFieldIndex = actionsRecord.indexOf("display_name");
QHash<uint, QStringList> actions;
while (actionsQuery.next()) {
const uint id = actionsQuery.value(actionsTableIdFieldIndex).toUInt();
actions[id].append(actionsQuery.value(actionsTableActionFieldIndex).toString());
actions[id].append(actionsQuery.value(actionsTableNameFieldIndex).toString());
}
// Gather hints for each notification
QSqlQuery hintsQuery("SELECT * FROM hints", *m_database);
QSqlRecord hintsRecord = hintsQuery.record();
int hintsTableIdFieldIndex = hintsRecord.indexOf("id");
int hintsTableHintFieldIndex = hintsRecord.indexOf("hint");
int hintsTableValueFieldIndex = hintsRecord.indexOf("value");
QHash<uint, QVariantHash> hints;
while (hintsQuery.next()) {
const uint id = hintsQuery.value(hintsTableIdFieldIndex).toUInt();
const QString hintName(hintsQuery.value(hintsTableHintFieldIndex).toString());
const QVariant hintValue(hintsQuery.value(hintsTableValueFieldIndex));
QVariant value;
if (hintName == LipstickNotification::HINT_TIMESTAMP) {
// Timestamps in the DB are already UTC but not marked as such, so they will
// be converted again unless specified to be UTC
QDateTime timestamp(QDateTime::fromString(hintValue.toString(), Qt::ISODate));
timestamp.setTimeSpec(Qt::UTC);
value = timestamp.toString(Qt::ISODate);
} else {
value = hintValue;
}
hints[id].insert(hintName, value);
}
// Gather expiration times for displayed notifications
QSqlQuery expirationQuery("SELECT * FROM expiration", *m_database);
QSqlRecord expirationRecord = expirationQuery.record();
int expirationTableIdFieldIndex = expirationRecord.indexOf("id");
int expirationTableExpireAtFieldIndex = expirationRecord.indexOf("expire_at");
QHash<uint, qint64> expireAt;
while (expirationQuery.next()) {
const uint id = expirationQuery.value(expirationTableIdFieldIndex).toUInt();
expireAt.insert(id, expirationQuery.value(expirationTableExpireAtFieldIndex).value<qint64>());
}
const qint64 currentTime(QDateTime::currentDateTimeUtc().toMSecsSinceEpoch());
QList<LipstickNotification *> activeNotifications;
QList<uint> transientIds;
QList<uint> expiredIds;
qint64 nextTimeout = std::numeric_limits<qint64>::max();
bool unexpiredRemaining = false;
// Create the notifications
QSqlQuery notificationsQuery("SELECT * FROM notifications", *m_database);
QSqlRecord notificationsRecord = notificationsQuery.record();
int notificationsTableIdFieldIndex = notificationsRecord.indexOf("id");
int notificationsTableAppNameFieldIndex = notificationsRecord.indexOf("app_name");
int notificationsTableDisambiguatedAppNameFieldIndex = notificationsRecord.indexOf("disambiguated_app_name");
int notificationsTableAppIconFieldIndex = notificationsRecord.indexOf("app_icon");
int notificationsTableSummaryFieldIndex = notificationsRecord.indexOf("summary");
int notificationsTableBodyFieldIndex = notificationsRecord.indexOf("body");
int notificationsTableExpireTimeoutFieldIndex = notificationsRecord.indexOf("expire_timeout");
while (notificationsQuery.next()) {
const uint id = notificationsQuery.value(notificationsTableIdFieldIndex).toUInt();
QString appName = notificationsQuery.value(notificationsTableAppNameFieldIndex).toString();
QString disambiguatedAppName = notificationsQuery.value(notificationsTableDisambiguatedAppNameFieldIndex).toString();
QString appIcon = notificationsQuery.value(notificationsTableAppIconFieldIndex).toString();
QString summary = notificationsQuery.value(notificationsTableSummaryFieldIndex).toString();
QString body = notificationsQuery.value(notificationsTableBodyFieldIndex).toString();
int expireTimeout = notificationsQuery.value(notificationsTableExpireTimeoutFieldIndex).toInt();
const QStringList ¬ificationActions = actions[id];
QVariantHash ¬ificationHints = hints[id];
if (notificationHints.value(LipstickNotification::HINT_TRANSIENT).toBool()) {
// This notification was transient, it should not be restored
NOTIFICATIONS_DEBUG("TRANSIENT AT RESTORE:" << appName << appIcon << summary << body << notificationActions
<< notificationHints << expireTimeout << "->" << id);
transientIds.append(id);
continue;
} else {
// Mark this notification as restored
notificationHints.insert(LipstickNotification::HINT_RESTORED, true);
}
bool expired = false;
if (update && expireAt.contains(id)) {
const qint64 expiry(expireAt.value(id));
if (expiry <= currentTime) {
expired = true;
} else {
nextTimeout = qMin(expiry, nextTimeout);
unexpiredRemaining = true;
}
}
LipstickNotification *notification = new LipstickNotification(appName, disambiguatedAppName, id, appIcon,
summary, body, notificationActions, notificationHints,
expireTimeout, this);
m_notifications.insert(id, notification);
if (id > m_previousNotificationID) {
// Use the highest notification ID found as the previous notification ID
m_previousNotificationID = id;
}
if (!expired) {
activeNotifications.append(notification);
} else {
NOTIFICATIONS_DEBUG("EXPIRED AT RESTORE:" << appName << appIcon << summary << body << notificationActions
<< notificationHints << expireTimeout << "->" << id);
expiredIds.append(id);
}
}
if (update) {
// Remove notifications no longer required
foreach (uint id, transientIds) {
deleteNotification(id);
}
}
int cullCount(activeNotifications.count() - MaxNotificationRestoreCount);
if (update && cullCount > 0) {
// Cull the least relevant notifications from this set
std::sort(activeNotifications.begin(), activeNotifications.end(), notificationReverseOrder);
foreach (LipstickNotification *n, activeNotifications) {
const QVariant userRemovable = n->hints().value(LipstickNotification::HINT_USER_REMOVABLE);
if (!userRemovable.isValid() || userRemovable.toBool()) {
const uint id = n->id();
NOTIFICATIONS_DEBUG("CULLED AT RESTORE:" << n->appName() << n->appIcon() << n->summary() << n->body()
<< actions[id] << hints[id] << n->expireTimeout() << "->" << id);
expiredIds.append(id);
if (--cullCount == 0) {