File indexing completed on 2024-04-28 15:29:13

0001 /*
0002     SPDX-FileCopyrightText: 2019 Piyush Aggarwal <piyushaggarwal002@gmail.com>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "notifybysnore.h"
0008 #include "debug_p.h"
0009 #include "knotification.h"
0010 #include "knotifyconfig.h"
0011 #include "knotificationreplyaction.h"
0012 
0013 #include <QGuiApplication>
0014 #include <QIcon>
0015 #include <QLocalSocket>
0016 
0017 #include <snoretoastactions.h>
0018 
0019 /*
0020  * On Windows a shortcut to your app is needed to be installed in the Start Menu
0021  * (and subsequently, registered with the OS) in order to show notifications.
0022  * Since KNotifications is a library, an app using it can't (feasibly) be properly
0023  * registered with the OS. It is possible we could come up with some complicated solution
0024  * which would require every KNotification-using app to do some special and probably
0025  * difficult to understand change to support Windows. Or we can have SnoreToast.exe
0026  * take care of all that nonsense for us.
0027  * Note that, up to this point, there have been no special
0028  * KNotifications changes to the generic application codebase to make this work,
0029  * just some tweaks to the Craft blueprint and packaging script
0030  * to pull in SnoreToast and trigger shortcut building respectively.
0031  * Be sure to have a shortcut installed in Windows Start Menu by SnoreToast.
0032  *
0033  * So the location doesn't matter, but it's only possible to register the internal COM server in an executable.
0034  * We could make it a static lib and link it in all KDE applications,
0035  * but to make the action center integration work, we would need to also compile a class
0036  * into the executable using a compile time uuid.
0037  *
0038  * The used header is meant to help with parsing the response.
0039  * The cmake target for LibSnoreToast is a INTERFACE lib, it only provides the include path.
0040  *
0041  *
0042  * Trigger the shortcut installation during the installation of your app; syntax for shortcut installation is -
0043  * ./SnoreToast.exe -install <absolute\address\of\shortcut> <absolute\address\to\app.exe> <appID>
0044  *
0045  * appID: use as-is from your app's QCoreApplication::applicationName() when installing the shortcut.
0046  * NOTE: Install the shortcut in Windows Start Menu folder.
0047  * For example, check out Craft Blueprint for Quassel-IRC or KDE Connect.
0048  */
0049 
0050 namespace
0051 {
0052 const QString SnoreToastExecName()
0053 {
0054     return QStringLiteral("SnoreToast.exe");
0055 }
0056 }
0057 
0058 NotifyBySnore::NotifyBySnore(QObject *parent)
0059     : KNotificationPlugin(parent)
0060 {
0061     m_server.listen(QString::number(qHash(qApp->applicationDirPath())));
0062     connect(&m_server, &QLocalServer::newConnection, this, [this]() {
0063         QLocalSocket *responseSocket = m_server.nextPendingConnection();
0064         connect(responseSocket, &QLocalSocket::readyRead, [this, responseSocket]() {
0065             const QByteArray rawNotificationResponse = responseSocket->readAll();
0066             responseSocket->deleteLater();
0067 
0068             const QString notificationResponse = QString::fromWCharArray(reinterpret_cast<const wchar_t *>(rawNotificationResponse.constData()),
0069                                                                          rawNotificationResponse.size() / sizeof(wchar_t));
0070             qCDebug(LOG_KNOTIFICATIONS) << notificationResponse;
0071 
0072             QMap<QString, QStringView> notificationResponseMap;
0073             for (const auto str : QStringView(notificationResponse).split(QLatin1Char(';'))) {
0074                 const int equalIndex = str.indexOf(QLatin1Char('='));
0075                 notificationResponseMap.insert(str.mid(0, equalIndex).toString(), str.mid(equalIndex + 1));
0076             }
0077 
0078             const QString responseAction = notificationResponseMap[QStringLiteral("action")].toString();
0079             const int responseNotificationId = notificationResponseMap[QStringLiteral("notificationId")].toInt();
0080 
0081             qCDebug(LOG_KNOTIFICATIONS) << "The notification ID is : " << responseNotificationId;
0082 
0083             KNotification *notification;
0084             const auto iter = m_notifications.constFind(responseNotificationId);
0085             if (iter != m_notifications.constEnd()) {
0086                 notification = iter.value();
0087             } else {
0088                 qCWarning(LOG_KNOTIFICATIONS) << "Received a response for an unknown notification.";
0089                 return;
0090             }
0091 
0092             std::wstring w_action(responseAction.size(), 0);
0093             responseAction.toWCharArray(const_cast<wchar_t *>(w_action.data()));
0094 
0095             switch (SnoreToastActions::getAction(w_action)) {
0096             case SnoreToastActions::Actions::Clicked:
0097                 qCDebug(LOG_KNOTIFICATIONS) << "User clicked on the toast.";
0098                 break;
0099 
0100             case SnoreToastActions::Actions::Hidden:
0101                 qCDebug(LOG_KNOTIFICATIONS) << "The toast got hidden.";
0102                 break;
0103 
0104             case SnoreToastActions::Actions::Dismissed:
0105                 qCDebug(LOG_KNOTIFICATIONS) << "User dismissed the toast.";
0106                 break;
0107 
0108             case SnoreToastActions::Actions::Timedout:
0109                 qCDebug(LOG_KNOTIFICATIONS) << "The toast timed out.";
0110                 break;
0111 
0112             case SnoreToastActions::Actions::ButtonClicked: {
0113                 qCDebug(LOG_KNOTIFICATIONS) << "User clicked an action button in the toast.";
0114                 const QString responseButton = notificationResponseMap[QStringLiteral("button")].toString();
0115                 QStringList s = m_notifications.value(responseNotificationId)->actions();
0116                 int actionNum = s.indexOf(responseButton) + 1; // QStringList starts with index 0 but not actions
0117                 Q_EMIT actionInvoked(responseNotificationId, actionNum);
0118                 break;
0119             }
0120 
0121             case SnoreToastActions::Actions::TextEntered: {
0122                 qCWarning(LOG_KNOTIFICATIONS) << "User entered some text in the toast.";
0123                 const QString replyText = notificationResponseMap[QStringLiteral("text")].toString();
0124                 qCWarning(LOG_KNOTIFICATIONS) << "Text entered was :: " << replyText;
0125                 Q_EMIT replied(responseNotificationId, replyText);
0126                 break;
0127             }
0128 
0129             default:
0130                 qCWarning(LOG_KNOTIFICATIONS) << "Unexpected behaviour with the toast. Please file a bug report / feature request.";
0131                 break;
0132             }
0133 
0134             // Action Center callbacks are not yet supported so just close the notification once done
0135             if (notification != nullptr) {
0136                 NotifyBySnore::close(notification);
0137             }
0138         });
0139     });
0140 }
0141 
0142 NotifyBySnore::~NotifyBySnore()
0143 {
0144     m_server.close();
0145 }
0146 
0147 void NotifyBySnore::notify(KNotification *notification, KNotifyConfig *config)
0148 {
0149     Q_UNUSED(config);
0150     // HACK work around that notification->id() is only populated after returning from here
0151     // note that config will be invalid at that point, so we can't pass that along
0152     QMetaObject::invokeMethod(
0153         this,
0154         [this, notification]() {
0155             NotifyBySnore::notifyDeferred(notification);
0156         },
0157         Qt::QueuedConnection);
0158 }
0159 
0160 void NotifyBySnore::notifyDeferred(KNotification *notification)
0161 {
0162     m_notifications.insert(notification->id(), notification);
0163 
0164     const QString notificationTitle = ((!notification->title().isEmpty()) ? notification->title() : qApp->applicationDisplayName());
0165     QStringList snoretoastArgsList{QStringLiteral("-id"),
0166                                    QString::number(notification->id()),
0167                                    QStringLiteral("-t"),
0168                                    notificationTitle,
0169                                    QStringLiteral("-m"),
0170                                    stripRichText(notification->text()),
0171                                    QStringLiteral("-appID"),
0172                                    qApp->applicationName(),
0173                                    QStringLiteral("-pid"),
0174                                    QString::number(qApp->applicationPid()),
0175                                    QStringLiteral("-pipename"),
0176                                    m_server.fullServerName()};
0177 
0178     // handle the icon for toast notification
0179     const QString iconPath = m_iconDir.path() + QLatin1Char('/') + QString::number(notification->id());
0180     const bool hasIcon = (notification->pixmap().isNull()) ? qApp->windowIcon().pixmap(1024, 1024).save(iconPath, "PNG") //
0181                                                            : notification->pixmap().save(iconPath, "PNG");
0182     if (hasIcon) {
0183         snoretoastArgsList << QStringLiteral("-p") << iconPath;
0184     }
0185 
0186     // if'd below, because SnoreToast currently doesn't support both textbox and buttons in the same notification
0187     if (notification->replyAction()) {
0188         snoretoastArgsList << QStringLiteral("-tb");
0189     } else if (!notification->actions().isEmpty()) {
0190         // add actions if any
0191         snoretoastArgsList << QStringLiteral("-b") << notification->actions().join(QLatin1Char(';'));
0192     }
0193 
0194     QProcess *snoretoastProcess = new QProcess();
0195     connect(snoretoastProcess, &QProcess::readyReadStandardError, [snoretoastProcess, snoretoastArgsList]() {
0196         const auto data = snoretoastProcess->readAllStandardError();
0197         qCDebug(LOG_KNOTIFICATIONS) << "SnoreToast process stderr:" << snoretoastArgsList << data;
0198     });
0199     connect(snoretoastProcess, &QProcess::readyReadStandardOutput, [snoretoastProcess, snoretoastArgsList]() {
0200         const auto data = snoretoastProcess->readAllStandardOutput();
0201         qCDebug(LOG_KNOTIFICATIONS) << "SnoreToast process stdout:" << snoretoastArgsList << data;
0202     });
0203     connect(snoretoastProcess, &QProcess::errorOccurred, this, [this, snoretoastProcess, snoretoastArgsList, iconPath](QProcess::ProcessError error) {
0204         qCWarning(LOG_KNOTIFICATIONS) << "SnoreToast process errored:" << snoretoastArgsList << error;
0205         snoretoastProcess->deleteLater();
0206         QFile::remove(iconPath);
0207     });
0208     connect(snoretoastProcess,
0209             qOverload<int, QProcess::ExitStatus>(&QProcess::finished),
0210             this,
0211             [this, snoretoastProcess, snoretoastArgsList, iconPath](int exitCode, QProcess::ExitStatus exitStatus) {
0212                 qCDebug(LOG_KNOTIFICATIONS) << "SnoreToast process finished:" << snoretoastArgsList;
0213                 qCDebug(LOG_KNOTIFICATIONS) << "code:" << exitCode << "status:" << exitStatus;
0214                 snoretoastProcess->deleteLater();
0215                 QFile::remove(iconPath);
0216             });
0217 
0218     qCDebug(LOG_KNOTIFICATIONS) << "SnoreToast process starting:" << snoretoastArgsList;
0219     snoretoastProcess->start(SnoreToastExecName(), snoretoastArgsList);
0220 }
0221 
0222 void NotifyBySnore::close(KNotification *notification)
0223 {
0224     qCDebug(LOG_KNOTIFICATIONS) << "Requested to close notification with ID:" << notification->id();
0225     if (m_notifications.constFind(notification->id()) == m_notifications.constEnd()) {
0226         qCWarning(LOG_KNOTIFICATIONS) << "Couldn't find the notification in m_notifications. Nothing to close.";
0227         return;
0228     }
0229 
0230     m_notifications.remove(notification->id());
0231 
0232     const QStringList snoretoastArgsList{QStringLiteral("-close"), QString::number(notification->id()), QStringLiteral("-appID"), qApp->applicationName()};
0233 
0234     qCDebug(LOG_KNOTIFICATIONS) << "Closing notification; SnoreToast process arguments:" << snoretoastArgsList;
0235     QProcess::startDetached(SnoreToastExecName(), snoretoastArgsList);
0236 
0237     finish(notification);
0238 }
0239 
0240 void NotifyBySnore::update(KNotification *notification, KNotifyConfig *config)
0241 {
0242     Q_UNUSED(notification);
0243     Q_UNUSED(config);
0244     qCWarning(LOG_KNOTIFICATIONS) << "updating a notification is not supported yet.";
0245 }
0246 
0247 #include "moc_notifybysnore.cpp"