| 1 | // SPDX-FileCopyrightText: Nheko Contributors |
| 2 | // |
| 3 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 4 | |
| 5 | #include "notifications/Manager.h" |
| 6 | |
| 7 | #include <QDBusConnection> |
| 8 | #include <QDBusMessage> |
| 9 | #include <QDBusMetaType> |
| 10 | #include <QDBusPendingCallWatcher> |
| 11 | #include <QDBusPendingReply> |
| 12 | #include <QDebug> |
| 13 | #include <QImage> |
| 14 | #include <QRegularExpression> |
| 15 | #include <QStringBuilder> |
| 16 | #include <QTextDocumentFragment> |
| 17 | |
| 18 | #include <functional> |
| 19 | #include <variant> |
| 20 | |
| 21 | #include <mtx/responses/notifications.hpp> |
| 22 | |
| 23 | #include "Cache.h" |
| 24 | #include "EventAccessors.h" |
| 25 | #include "Logging.h" |
| 26 | #include "MxcImageProvider.h" |
| 27 | #include "UserSettingsPage.h" |
| 28 | #include "Utils.h" |
| 29 | #include "dbus/NhekoDBusApi.h" |
| 30 | |
| 31 | NotificationsManager::NotificationsManager(QObject *parent) |
| 32 | : QObject(parent) |
| 33 | , dbus(QStringLiteral("org.freedesktop.Notifications"), |
| 34 | QStringLiteral("/org/freedesktop/Notifications"), |
| 35 | QStringLiteral("org.freedesktop.Notifications"), |
| 36 | QDBusConnection::sessionBus(), |
| 37 | this) |
| 38 | , hasMarkup_{std::invoke([this]() -> bool { |
| 39 | auto caps = dbus.call("GetCapabilities").arguments(); |
| 40 | for (const auto &x : std::as_const(caps)) |
| 41 | if (x.toStringList().contains("body-markup")) |
| 42 | return true; |
| 43 | return false; |
| 44 | })} |
| 45 | , hasImages_{std::invoke([this]() -> bool { |
| 46 | auto caps = dbus.call("GetCapabilities").arguments(); |
| 47 | for (const auto &x : std::as_const(caps)) |
| 48 | if (x.toStringList().contains("body-images")) |
| 49 | return true; |
| 50 | return false; |
| 51 | })} |
| 52 | { |
| 53 | qDBusRegisterMetaType<QImage>(); |
| 54 | |
| 55 | // clang-format off |
| 56 | QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.Notifications"), |
| 57 | QStringLiteral("/org/freedesktop/Notifications"), |
| 58 | QStringLiteral("org.freedesktop.Notifications"), |
| 59 | QStringLiteral("ActionInvoked"), |
| 60 | this, |
| 61 | SLOT(actionInvoked(uint,QString))); |
| 62 | QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.Notifications"), |
| 63 | QStringLiteral("/org/freedesktop/Notifications"), |
| 64 | QStringLiteral("org.freedesktop.Notifications"), |
| 65 | QStringLiteral("ActivationToken"), |
| 66 | this, |
| 67 | SLOT(activationToken(uint,QString))); |
| 68 | QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.Notifications"), |
| 69 | QStringLiteral("/org/freedesktop/Notifications"), |
| 70 | QStringLiteral("org.freedesktop.Notifications"), |
| 71 | QStringLiteral("NotificationClosed"), |
| 72 | this, |
| 73 | SLOT(notificationClosed(uint,uint))); |
| 74 | QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.Notifications"), |
| 75 | QStringLiteral("/org/freedesktop/Notifications"), |
| 76 | QStringLiteral("org.freedesktop.Notifications"), |
| 77 | QStringLiteral("NotificationReplied"), |
| 78 | this, |
| 79 | SLOT(notificationReplied(uint,QString))); |
| 80 | // clang-format on |
| 81 | |
| 82 | connect(this, |
| 83 | &NotificationsManager::systemPostNotificationCb, |
| 84 | this, |
| 85 | &NotificationsManager::systemPostNotification, |
| 86 | Qt::QueuedConnection); |
| 87 | } |
| 88 | |
| 89 | void |
| 90 | NotificationsManager::postNotification(const mtx::responses::Notification ¬ification, |
| 91 | const QImage &icon) |
| 92 | { |
| 93 | const auto room_id = QString::fromStdString(notification.room_id); |
| 94 | const auto event_id = QString::fromStdString(mtx::accessors::event_id(notification.event)); |
| 95 | const auto room_name = QString::fromStdString(cache::singleRoomInfo(notification.room_id).name); |
| 96 | |
| 97 | const auto replaces_event_id = |
| 98 | QString::fromStdString(mtx::accessors::relations(notification.event).replaces().value_or("")); |
| 99 | |
| 100 | auto postNotif = [this, room_id, event_id, room_name, icon, replaces_event_id](QString text) { |
| 101 | if (replaces_event_id.isEmpty()) |
| 102 | emit systemPostNotificationCb(room_id, event_id, room_name, text, icon); |
| 103 | else |
| 104 | emit systemPostNotificationCb(room_id, replaces_event_id, room_name, text, icon); |
| 105 | }; |
| 106 | |
| 107 | QString template_ = getMessageTemplate(notification); |
| 108 | // TODO: decrypt this message if the decryption setting is on in the UserSettings |
| 109 | if (std::holds_alternative<mtx::events::EncryptedEvent<mtx::events::msg::Encrypted>>( |
| 110 | notification.event) || |
| 111 | !template_.contains("%2")) { |
| 112 | postNotif(template_); |
| 113 | return; |
| 114 | } |
| 115 | |
| 116 | if (hasMarkup_) { |
| 117 | if (hasImages_ && allowShowingImages(notification) && |
| 118 | (mtx::accessors::msg_type(notification.event) == mtx::events::MessageType::Image || |
| 119 | mtx::accessors::event_type(notification.event) == mtx::events::EventType::Sticker)) { |
| 120 | MxcImageProvider::download( |
| 121 | QString::fromStdString(mtx::accessors::url(notification.event)) |
| 122 | .remove(QStringLiteral("mxc://")), |
| 123 | QSize(200, 80), |
| 124 | [postNotif, notification, template_](QString, QSize, QImage, QString imgPath) { |
| 125 | if (imgPath.isEmpty()) |
| 126 | postNotif(template_ |
| 127 | .arg(utils::stripReplyFallbacks(notification.event, {}, {}) |
| 128 | .quoted_formatted_body) |
| 129 | .replace(QLatin1String("<em>"), QLatin1String("<i>")) |
| 130 | .replace(QLatin1String("</em>"), QLatin1String("</i>")) |
| 131 | .replace(QLatin1String("<strong>"), QLatin1String("<b>")) |
| 132 | .replace(QLatin1String("</strong>"), QLatin1String("</b>"))); |
| 133 | else |
| 134 | postNotif(template_.arg( |
| 135 | QStringLiteral("<br><img src=\"file:///") % imgPath % "\" alt=\"" % |
| 136 | mtx::accessors::formattedBodyWithFallback(notification.event) % "\">")); |
| 137 | }); |
| 138 | return; |
| 139 | } |
| 140 | |
| 141 | postNotif( |
| 142 | template_ |
| 143 | .arg(utils::stripReplyFallbacks(notification.event, {}, {}).quoted_formatted_body) |
| 144 | .replace(QLatin1String("<em>"), QLatin1String("<i>")) |
| 145 | .replace(QLatin1String("</em>"), QLatin1String("</i>")) |
| 146 | .replace(QLatin1String("<strong>"), QLatin1String("<b>")) |
| 147 | .replace(QLatin1String("</strong>"), QLatin1String("</b>"))); |
| 148 | return; |
| 149 | } |
| 150 | |
| 151 | postNotif(template_.arg(utils::stripReplyFallbacks(notification.event, {}, {}).quoted_body)); |
| 152 | } |
| 153 | |
| 154 | /** |
| 155 | * This function is based on code from |
| 156 | * https://github.com/rohieb/StratumsphereTrayIcon |
| 157 | * Copyright (C) 2012 Roland Hieber <[email protected]> |
| 158 | * Licensed under the GNU General Public License, version 3 |
| 159 | */ |
| 160 | void |
| 161 | NotificationsManager::systemPostNotification(const QString &room_id, |
| 162 | const QString &event_id, |
| 163 | const QString &roomName, |
| 164 | const QString &text, |
| 165 | const QImage &icon) |
| 166 | { |
| 167 | QVariantMap hints; |
| 168 | hints[QStringLiteral("image-data")] = icon; |
| 169 | hints[QStringLiteral("sound-name")] = "message-new-instant"; |
| 170 | hints[QStringLiteral("desktop-entry")] = "nheko"; |
| 171 | hints[QStringLiteral("category")] = "im.received"; |
| 172 | |
| 173 | if (auto profile = UserSettings::instance()->profile(); !profile.isEmpty()) |
| 174 | hints[QStringLiteral("x-kde-origin-name")] = profile; |
| 175 | |
| 176 | uint replace_id = 0; |
| 177 | if (!event_id.isEmpty()) { |
| 178 | for (auto elem = notificationIds.begin(); elem != notificationIds.end(); ++elem) { |
| 179 | if (elem.value().roomId != room_id) |
| 180 | continue; |
| 181 | |
| 182 | if (elem.value().eventId == event_id) { |
| 183 | replace_id = elem.key(); |
| 184 | break; |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | QList<QVariant> argumentList; |
| 190 | argumentList << "nheko"; // app_name |
| 191 | argumentList << (uint)replace_id; // replace_id |
| 192 | argumentList << ""; // app_icon |
| 193 | argumentList << roomName; // summary |
| 194 | argumentList << text; // body |
| 195 | |
| 196 | // The list of actions has always the action name and then a localized version of that |
| 197 | // action. Currently we just use an empty string for that. |
| 198 | // TODO(Nico): Look into what to actually put there. |
| 199 | QStringList actions; |
| 200 | actions << QStringList(QStringLiteral("default")) << QLatin1String(""); |
| 201 | if (!room_id.isEmpty()) { |
| 202 | actions << QStringLiteral("inline-reply") << QLatin1String(""); |
| 203 | } |
| 204 | argumentList << actions; // actions |
| 205 | argumentList << hints; // hints |
| 206 | argumentList << (int)-1; // timeout in ms |
| 207 | |
| 208 | QDBusPendingCall call = dbus.asyncCallWithArgumentList(QStringLiteral("Notify"), argumentList); |
| 209 | auto watcher = new QDBusPendingCallWatcher{call, this}; |
| 210 | connect( |
| 211 | watcher, &QDBusPendingCallWatcher::finished, this, [watcher, this, room_id, event_id]() { |
| 212 | if (watcher->reply().type() == QDBusMessage::ErrorMessage) |
| 213 | qDebug() << "D-Bus Error:" << watcher->reply().errorMessage(); |
| 214 | else |
| 215 | notificationIds[watcher->reply().arguments().first().toUInt()] = |
| 216 | roomEventId{room_id, event_id}; |
| 217 | watcher->deleteLater(); |
| 218 | }); |
| 219 | } |
| 220 | |
| 221 | void |
| 222 | NotificationsManager::closeNotification(uint id) |
| 223 | { |
| 224 | auto call = dbus.asyncCall(QStringLiteral("CloseNotification"), (uint)id); // replace_id |
| 225 | auto watcher = new QDBusPendingCallWatcher{call, this}; |
| 226 | connect(watcher, &QDBusPendingCallWatcher::finished, this, [watcher]() { |
| 227 | if (watcher->reply().type() == QDBusMessage::ErrorMessage) { |
| 228 | qDebug() << "D-Bus Error:" << watcher->reply().errorMessage(); |
| 229 | }; |
| 230 | watcher->deleteLater(); |
| 231 | }); |
| 232 | } |
| 233 | |
| 234 | void |
| 235 | NotificationsManager::removeNotification(const QString &roomId, const QString &eventId) |
| 236 | { |
| 237 | roomEventId reId = {roomId, eventId}; |
| 238 | for (auto elem = notificationIds.begin(); elem != notificationIds.end(); ++elem) { |
| 239 | if (elem.value().roomId != roomId) |
| 240 | continue; |
| 241 | |
| 242 | // close all notifications matching the eventId or having a lower |
| 243 | // notificationId |
| 244 | // This relies on the notificationId not wrapping around. This allows for |
| 245 | // approximately 2,147,483,647 notifications, so it is a bit unlikely. |
| 246 | // Otherwise we would need to store a 64bit counter instead. |
| 247 | closeNotification(elem.key()); |
| 248 | |
| 249 | // FIXME: compare index of event id of the read receipt and the notification instead |
| 250 | // of just the id to prevent read receipts of events without notification clearing |
| 251 | // all notifications in that room! |
| 252 | if (elem.value() == reId) |
| 253 | break; |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | void |
| 258 | NotificationsManager::actionInvoked(uint id, QString action) |
| 259 | { |
| 260 | if (notificationIds.contains(id)) { |
| 261 | roomEventId idEntry = notificationIds[id]; |
| 262 | if (action == QLatin1String("default")) { |
| 263 | emit notificationClicked(idEntry.roomId, idEntry.eventId); |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | // receive a wayland activation token from the notification manager |
| 269 | void |
| 270 | NotificationsManager::activationToken(uint, QString action) |
| 271 | { |
| 272 | nhlog::net()->debug("Got activation token for notification"); |
| 273 | qputenv("XDG_ACTIVATION_TOKEN", action.toUtf8()); |
| 274 | } |
| 275 | |
| 276 | void |
| 277 | NotificationsManager::notificationReplied(uint id, QString reply) |
| 278 | { |
| 279 | if (notificationIds.contains(id)) { |
| 280 | roomEventId idEntry = notificationIds[id]; |
| 281 | emit sendNotificationReply(idEntry.roomId, idEntry.eventId, reply); |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | void |
| 286 | NotificationsManager::notificationClosed(uint id, uint reason) |
| 287 | { |
| 288 | Q_UNUSED(reason); |
| 289 | notificationIds.remove(id); |
| 290 | } |
| 291 | |
| 292 | void |
| 293 | NotificationsManager::closeAllNotifications() |
| 294 | { |
| 295 | const auto ids = notificationIds.keys(); |
| 296 | for (const auto &id : ids) { |
| 297 | closeNotification(id); |
| 298 | notificationIds.remove(id); |
| 299 | } |
| 300 | } |