File: appservice.cpp

package info (click to toggle)
syncthingtray 2.0.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,124 kB
  • sloc: cpp: 34,081; xml: 1,705; java: 1,258; sh: 97; javascript: 54; makefile: 25
file content (578 lines) | stat: -rw-r--r-- 22,650 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
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
#include "./appservice.h"

#ifdef Q_OS_ANDROID
#include "./android.h"
#endif

#ifdef SYNCTHINGWIDGETS_USE_LIBSYNCTHING
#include <syncthing/interface.h>
#endif

#include <syncthingmodel/syncthingicons.h>

#include <QDebug>
#include <QStringBuilder>

#ifdef Q_OS_ANDROID
#include <QCoreApplication>
#include <QtCore/private/qandroidextras_p.h>
#include <QtEnvironmentVariables>
#endif

using namespace Data;

namespace QtGui {

/*!
 * \class AppService
 * \brief The AppService class manages the runtime of Syncthing for the Qt Quick GUI.
 * \remarks
 * - Under Android the app is split into two processes. One UI process and one service process. Hence the code
 *   that needs to run in the service process has been moved from the App class into the AppService class. The
 *   communication between these is implemented via Binder.
 * - Under other platforms an object of the AppService class is simply instantiated next to the main App object.
 *   There is no process boundary so communication between these is done via signals and slots.
 * - Under Android this class is accompanied by the Java class SyncthingService which implements certain
 *   Android-specific functionality in Java. Both classes also implement the notification handling because the
 *   Android service is a "foreground service" which means it is tied to a notification.
 * \sa https://developer.android.com/develop/background-work/services/fgs
 */

#ifdef SYNCTHINGTRAY_SERVICE_WITH_ICON_RENDERING
static constexpr auto textOnly = false;
#else
static constexpr auto textOnly = true;
#endif

/*!
 * \brief Initializes the Syncthing launcher and related platform-specific functionality.
 * \remarks
 * - Registers JNI functions for the Java class SyncthingService under Android. There is no
 *   "onNativeReady" call like in App because for services Qt itself provides this kind of
 *   synchronization.
 */
AppService::AppService(bool insecure, QObject *parent)
    : AppBase(insecure, textOnly, false, parent)
#ifdef Q_OS_ANDROID
    , m_clientsFollowingLog(false)
#endif
{
    qDebug() << "Initializing service app";

#ifdef Q_OS_ANDROID
    JniFn::registerServiceJniMethods(this);
#endif

#if defined(Q_OS_ANDROID) && defined(SYNCTHINGTRAY_SERVICE_WITH_ICON_RENDERING)
    // initialize experimental icon rendering within service to have icon on notification
    const auto scaleFactor = QJniObject(QNativeInterface::QAndroidApplication::context()).callMethod<jfloat>("scaleFactor", "()F");
    const auto darkmode = QJniObject(QNativeInterface::QAndroidApplication::context()).callMethod<jboolean>("isDarkmodeEnabled");
    qDebug() << "Scale factor for notification/service icons: " << scaleFactor;
    //qDebug() << "Darkmode for notification/service icons: " << darkmode;
    auto &iconManager = Data::IconManager::instance();
    //auto s = darkmode ? StatusIconSettings(StatusIconSettings::DarkTheme{}) : StatusIconSettings(StatusIconSettings::BrightTheme{});
    auto s = StatusIconSettings();
    s.renderSize *= 2 * scaleFactor;
    s.strokeWidth = StatusIconStrokeWidth::Thick;
    iconManager.applySettings(&s, &s, false, false);
    connect(&iconManager, &Data::IconManager::statusIconsChanged, this, &AppService::invalidateAndroidIconCache);
#endif

#ifdef Q_OS_ANDROID
    m_launcher.setManualStopHandler([] {
        QJniObject(QNativeInterface::QAndroidApplication::context())
            .callMethod<jint>("sendMessageToClients", static_cast<jint>(ActivityAction::FlagManualStop), 0, 0, QByteArray());
        return false;
    });
#endif

    connect(&m_connection, &SyncthingConnection::error, this, &AppService::handleConnectionError);
    connect(&m_connection, &SyncthingConnection::statusChanged, this, &AppService::handleConnectionStatusChanged);
    connect(&m_connection, &SyncthingConnection::newDevices, this, &AppService::handleChangedDevices);
    connect(&m_connection, &SyncthingConnection::autoReconnectIntervalChanged, this, &AppService::invalidateStatus);
    connect(&m_connection, &SyncthingConnection::hasOutOfSyncDirsChanged, this, &AppService::invalidateStatus);
    connect(&m_connection, &SyncthingConnection::devStatusChanged, this, &AppService::handleChangedDevices);
    connect(&m_connection, &SyncthingConnection::newErrors, this, &AppService::handleNewErrors);

    m_launcher.setEmittingOutput(true);
    connect(&m_launcher, &SyncthingLauncher::outputAvailable, this, &AppService::gatherLogsFromBytes);
    connect(&m_launcher, &SyncthingLauncher::errorOccurred, this, &AppService::handleSyncthingError, Qt::QueuedConnection);
    connect(&m_launcher, &SyncthingLauncher::runningChanged, this, &AppService::handleRunningChanged);
    connect(&m_launcher, &SyncthingLauncher::runningChanged, this, &AppService::broadcastLauncherStatus);
    connect(&m_launcher, &SyncthingLauncher::guiUrlChanged, this, &AppService::handleGuiUrlChanged);
    connect(&m_launcher, &SyncthingLauncher::guiUrlChanged, this, &AppService::broadcastLauncherStatus);
    connect(&m_launcher, &SyncthingLauncher::networkConnectionMeteredChanged, this, &AppService::broadcastLauncherStatus);

#ifdef Q_OS_ANDROID
    connect(&m_notifier, &SyncthingNotifier::newDevice, this, &AppService::showNewDevice);
    connect(&m_notifier, &SyncthingNotifier::newDir, this, &AppService::showNewDir);
    connect(this, &AppService::error, this, &AppService::showError);
#endif

    m_connection.setPollingFlags(SyncthingConnection::PollingFlags::MainEvents | SyncthingConnection::PollingFlags::RemoteIndexUpdated
        | SyncthingConnection::PollingFlags::Errors);

    if (!SyncthingLauncher::mainInstance()) {
        SyncthingLauncher::setMainInstance(&m_launcher);
    }

    reloadSettings();
}

AppService::~AppService()
{
    if (m_launcher.isRunning()) {
        qDebug() << "Terminating Syncthing";
        m_launcher.terminate();
    }
    qDebug() << "Destroying service";
    if (SyncthingLauncher::mainInstance() == &m_launcher) {
        SyncthingLauncher::setMainInstance(nullptr);
    }
#ifdef Q_OS_ANDROID
    JniFn::unregisterServiceJniMethods(this);
#endif
}

const QString &AppService::status()
{
    if (m_status.has_value()) {
        return *m_status;
    }
    if (m_connectToLaunched) {
        if (!m_launcher.isRunning()) {
            return m_status.emplace(m_launcher.runningStatus());
        } else if (m_launcher.isStarting()) {
            return m_status.emplace(tr("Backend is starting …"));
        }
    }
    return AppBase::status();
}

#ifdef Q_OS_ANDROID
/// \cond
static QByteArray serializeVariant(const QVariant &variant)
{
    auto res = QByteArray();
    auto stream = QDataStream(&res, QIODevice::WriteOnly);
    stream << variant;
    return res;
}
/// \endcond
#endif

void AppService::broadcastLauncherStatus()
{
    auto launcherStatus = m_launcher.overallStatus();
    launcherStatus[QStringLiteral("unixSocketPath")] = m_syncthingUnixSocketPath;
#ifdef Q_OS_ANDROID
    QJniObject(QNativeInterface::QAndroidApplication::context())
        .callMethod<jint>("sendMessageToClients", static_cast<jint>(ActivityAction::UpdateLauncherStatus), 0, 0, serializeVariant(launcherStatus));
#else
    emit launcherStatusChanged(launcherStatus);
#endif
}

bool AppService::applyLauncherSettings()
{
    const auto launcherSettingsObj = m_settings.value(QLatin1String("launcher")).toObject();
    const auto tweaksSettingsObj = m_settings.value(QLatin1String("tweaks")).toObject();
    m_launcher.setStoppingOnMeteredConnection(launcherSettingsObj.value(QLatin1String("stopOnMetered")).toBool());
    const auto shouldRun = launcherSettingsObj.value(QLatin1String("run")).toBool();
    const auto exePath = launcherSettingsObj.value(QLatin1String("exePath")).toString();
    const auto useUnixDomainSocket = tweaksSettingsObj.value(QLatin1String("useUnixDomainSocket")).toBool();
    const auto customSyncthingHome = launcherSettingsObj.value(QLatin1String("stHomeDir")).toString();
    m_syncthingConfigDir = customSyncthingHome.isEmpty() ? m_settingsDir->path() + QStringLiteral("/syncthing") : customSyncthingHome;
    m_syncthingDataDir = m_syncthingConfigDir;
    m_syncthingUnixSocketPath = useUnixDomainSocket ? settingsDir().path() + QStringLiteral("/syncthing.socket") : QString();
#ifdef Q_OS_ANDROID
    if (shouldRun) {
        if (const auto ipObj = QJniObject(QNativeInterface::QAndroidApplication::context()).callMethod<jstring>("getGatewayIPv4"); ipObj.isValid()) {
            const auto ip = ipObj.toString();
            qDebug() << "Setting FALLBACK_NET_GATEWAY_IPV4:" << ip;
            qputenv("FALLBACK_NET_GATEWAY_IPV4", ip.toUtf8());
        } else {
            qunsetenv("FALLBACK_NET_GATEWAY_IPV4");
        }
    }
#endif
    if (exePath.isEmpty()) {
#ifdef SYNCTHINGWIDGETS_USE_LIBSYNCTHING
        auto options = LibSyncthing::RuntimeOptions();
        options.configDir = m_syncthingConfigDir.toStdString();
        options.dataDir = options.configDir;
        if (!m_syncthingUnixSocketPath.isEmpty()) {
            options.guiAddress = "unix://" + m_syncthingUnixSocketPath.toStdString();
            options.flags = options.flags | LibSyncthing::RuntimeFlags::SkipPortProbing;
        }
        m_launcher.setLibSyncthingLogLevel(launcherSettingsObj.value(QLatin1String("logLevel")).toString());
        if (launcherSettingsObj.value(QLatin1String("writeLogFile")).toBool()) {
            if (!m_launcher.logFile().isOpen()) {
                m_launcher.logFile().setFileName(syncthingLogFilePath());
                if (!m_launcher.logFile().open(QIODeviceBase::WriteOnly | QIODeviceBase::Append | QIODeviceBase::Text)) {
                    emit error(tr("Unable to open persistent log file for Syncthing under \"%1\": %2")
                            .arg(m_launcher.logFile().fileName(), m_launcher.logFile().errorString()));
                    return false;
                }
            }
        } else {
            m_launcher.logFile().close();
        }
        m_launcher.setRunning(shouldRun, std::move(options));
#else
        if (shouldRun) {
            emit error(tr("This build of the app cannot launch Syncthing."));
            return false;
        }
#endif
    } else {
        auto args = QStringList();
        args.reserve(8);
        args.append(QStringLiteral("serve"));
        args.append(QStringLiteral("--no-browser"));
        args.append(QStringLiteral("--config"));
        args.append(m_syncthingConfigDir);
        args.append(QStringLiteral("--data"));
        args.append(m_syncthingDataDir);
        if (!m_syncthingUnixSocketPath.isEmpty()) {
            args.append(QStringLiteral("--gui-address=unix://") + m_syncthingUnixSocketPath);
            args.append(QStringLiteral("--no-port-probing"));
        }
        m_launcher.setRunning(shouldRun, exePath, args);
    }
    return true;
}

bool AppService::reloadSettings()
{
    qDebug() << "Reloading settings";
    const auto res = loadSettings(true);
    applyLauncherSettings();
    applyConnectionSettings(m_launcher.guiUrl());
    invalidateStatus();
    return res;
}

void AppService::terminateSyncthing()
{
    m_launcher.terminate();
}

void AppService::stopLibSyncthing()
{
    m_launcher.stopLibSyncthing();
}

void AppService::restartSyncthing()
{
    m_launcher.setManuallyStopped(true);
    m_connection.restart();
}

void AppService::shutdownSyncthing()
{
    m_launcher.setManuallyStopped(true);
    m_connection.shutdown();
}

void AppService::clearLog()
{
    m_log.clear();
}

void AppService::replayLog()
{
#ifdef Q_OS_ANDROID
    m_clientsFollowingLog = true;
    QJniObject(QNativeInterface::QAndroidApplication::context())
        .callMethod<jint>("sendMessageToClients", static_cast<jint>(ActivityAction::AppendLog), 0, 0, m_log);
#else
    emit logsAvailable(m_log);
#endif
}

#ifdef Q_OS_ANDROID
void AppService::showError(const QString &error)
{
    const auto ctx = QJniObject(QNativeInterface::QAndroidApplication::context());
    if (ctx.callMethod<jint>("sendMessageToClients", static_cast<jint>(ActivityAction::ShowError), 0, 0, error) > 0) {
        return;
    }
    const auto title = QJniObject::fromString(tr("Syncthing App ran into error"));
    const auto text = QJniObject::fromString(error);
    const auto subText = QJniObject::fromString(QString());
    static const auto page = QJniObject::fromString(QStringLiteral("internalErrors"));
#ifdef SYNCTHINGTRAY_SERVICE_WITH_ICON_RENDERING
    const auto &icon = makeAndroidIcon(commonForkAwesomeIcons().exclamation);
#else
    static const auto icon = QJniObject();
#endif
    updateExtraAndroidNotification(title, text, subText, page, icon);
}

void AppService::clearInternalErrors()
{
    clearAndroidExtraNotifications(3, 3 + m_internalErrors.size());
}

void AppService::handleMessageFromActivity(ServiceAction action, int arg1, int arg2, const QString &str)
{
    Q_UNUSED(arg1)
    Q_UNUSED(arg2)
    Q_UNUSED(str)
    qDebug() << "Received message from activity: " << static_cast<int>(action);
    switch (action) {
    case ServiceAction::ReloadSettings:
        QMetaObject::invokeMethod(this, "reloadSettings", Qt::QueuedConnection);
        break;
    case ServiceAction::TerminateSyncthing:
        QMetaObject::invokeMethod(this, "terminateSyncthing", Qt::QueuedConnection);
        break;
    case ServiceAction::RestartSyncthing:
        QMetaObject::invokeMethod(this, "restartSyncthing", Qt::QueuedConnection);
        break;
    case ServiceAction::ShutdownSyncthing:
        QMetaObject::invokeMethod(this, "shotdownSyncthing", Qt::QueuedConnection);
        break;
    case ServiceAction::ConnectToSyncthing:
        QMetaObject::invokeMethod(connection(), "connect", Qt::QueuedConnection);
        break;
    case ServiceAction::ReconnectToSyncthing:
        QMetaObject::invokeMethod(connection(), "reconnect", Qt::QueuedConnection);
        break;
    case ServiceAction::BroadcastLauncherStatus:
        QMetaObject::invokeMethod(this, "broadcastLauncherStatus", Qt::QueuedConnection);
        break;
    case ServiceAction::Reconnect:
        QMetaObject::invokeMethod(connection(), "reconnect", Qt::QueuedConnection);
        break;
    case ServiceAction::ClearInternalErrorNotifications:
        QMetaObject::invokeMethod(this, "clearInternalErrors", Qt::QueuedConnection);
        break;
    case ServiceAction::ClearLog:
        QMetaObject::invokeMethod(this, "clearLog", Qt::QueuedConnection);
        break;
    case ServiceAction::FollowLog:
        QMetaObject::invokeMethod(this, "replayLog", Qt::QueuedConnection);
        break;
    case ServiceAction::CloseLog:
        m_clientsFollowingLog = false;
        break;
    case ServiceAction::RequestErrors:
        QMetaObject::invokeMethod(connection(), "requestErrors", Qt::QueuedConnection);
        break;
    default:;
    }
}
#endif

void AppService::handleConnectionError(
    const QString &errorMessage, Data::SyncthingErrorCategory category, int networkError, const QNetworkRequest &request, const QByteArray &response)
{
    if (!InternalError::isRelevant(m_connection, category, errorMessage, networkError, false)) {
        return;
    }
#ifdef Q_OS_ANDROID
    auto error = InternalError(errorMessage, request.url(), response);
    showInternalError(error);
#else
    Q_UNUSED(errorMessage)
    Q_UNUSED(request)
    Q_UNUSED(response)
#endif
}

void AppService::invalidateStatus()
{
    AppBase::invalidateStatus();
#ifdef Q_OS_ANDROID
    updateAndroidNotification();
#endif
}

void AppService::gatherLogsFromString(const QString &newOutput)
{
#ifdef Q_OS_ANDROID
    if (m_clientsFollowingLog) {
        QJniObject(QNativeInterface::QAndroidApplication::context())
            .callMethod<jint>("sendMessageToClients", static_cast<jint>(ActivityAction::AppendLog), 0, 0, newOutput);
    }
#else
    emit logsAvailable(newOutput);
#endif
    m_log.append(newOutput);
}

void AppService::gatherLogsFromBytes(const QByteArray &newOutput)
{
    gatherLogsFromString(QString::fromUtf8(newOutput));
}

void AppService::handleSyncthingError(QProcess::ProcessError error)
{
    auto errorString = m_launcher.errorString();
    if (errorString.isEmpty()) {
        errorString = SyncthingProcess::genericErrorString(error);
    }
    auto lineBreak = m_log.isEmpty() || m_log.endsWith(QChar('\n')) ? QString() : QStringLiteral("\n");
    gatherLogsFromString(lineBreak + tr("An error occurred when running Syncthing: %2\n").arg(errorString));
}

void AppService::handleRunningChanged(bool isRunning)
{
    Q_UNUSED(isRunning)
    if (m_connectToLaunched) {
        invalidateStatus();
    }
}

void AppService::handleChangedDevices()
{
    m_statusInfo.updateConnectedDevices(m_connection);
#ifdef Q_OS_ANDROID
    updateAndroidNotification();
#endif
}

void AppService::handleNewErrors(const std::vector<Data::SyncthingError> &errors)
{
    Q_UNUSED(errors)
    invalidateStatus();
#ifdef Q_OS_ANDROID
    updateSyncthingErrorsNotification(errors);
#endif
}

void AppService::handleConnectionStatusChanged(Data::SyncthingStatus newStatus)
{
    invalidateStatus();
#ifdef Q_OS_ANDROID
    switch (newStatus) {
    case Data::SyncthingStatus::Reconnecting:
        clearSyncthingErrorsNotification();
        break;
    default:;
    }
#else
    Q_UNUSED(newStatus)
#endif
}

#ifdef Q_OS_ANDROID
#ifdef SYNCTHINGTRAY_SERVICE_WITH_ICON_RENDERING
void AppService::invalidateAndroidIconCache()
{
    m_statusInfo.updateConnectionStatus(m_connection);
    m_androidIconCache.clear();
    updateAndroidNotification();
}

QJniObject &AppService::makeAndroidIcon(const QIcon &icon)
{
    auto &cachedIcon = m_androidIconCache[&icon];
    if (!cachedIcon.isValid()) {
        cachedIcon = IconManager::makeAndroidBitmap(icon.pixmap(QSize(32, 32)).toImage());
    }
    return cachedIcon;
}
#endif

void AppService::updateAndroidNotification()
{
    const auto title = QJniObject::fromString(m_connection.isConnected() ? m_statusInfo.statusText() : status());
    const auto text = QJniObject::fromString(m_statusInfo.additionalStatusText());
    static const auto subText = QJniObject::fromString(QString());
#ifdef SYNCTHINGTRAY_SERVICE_WITH_ICON_RENDERING
    const auto &icon = makeAndroidIcon(m_statusInfo.statusIcon());
#else
    static const auto icon = QJniObject();
#endif
    QJniObject::callStaticMethod<void>("io/github/martchus/syncthingtray/SyncthingService", "updateNotification",
        "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/graphics/Bitmap;)V", title.object(), text.object(), subText.object(),
        icon.object());
}

void AppService::updateExtraAndroidNotification(
    const QJniObject &title, const QJniObject &text, const QJniObject &subText, const QJniObject &page, const QJniObject &icon, int id)
{
    QJniObject::callStaticMethod<void>("io/github/martchus/syncthingtray/SyncthingService", "updateExtraNotification",
        "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/graphics/Bitmap;I)V", title.object(), text.object(),
        subText.object(), page.object(), icon.object(), id ? id : ++m_androidNotificationId);
}

void AppService::clearAndroidExtraNotifications(int firstId, int lastId)
{
    QJniObject::callStaticMethod<void>("io/github/martchus/syncthingtray/SyncthingService", "cancelExtraNotification", "(II)V", firstId, lastId);
}

void AppService::updateSyncthingErrorsNotification(const std::vector<Data::SyncthingError> &newErrors)
{
    if (newErrors.empty()) {
        clearSyncthingErrorsNotification();
        return;
    }
    const auto syncthingErrors = newErrors.size();
    const auto &mostRecent = newErrors.back();
    const auto title = QJniObject::fromString(
        syncthingErrors == 1 ? tr("Syncthing error/notification") : tr("%1 Syncthing errors/notifications").arg(syncthingErrors));
    const auto text = QJniObject::fromString(syncthingErrors == 1 ? mostRecent.message : tr("Most recent: ") + mostRecent.message);
    const auto subText = QJniObject::fromString(QString::fromStdString(mostRecent.when.toString()));
    static const auto page = QJniObject::fromString(QStringLiteral("connectionErrors"));
#ifdef SYNCTHINGTRAY_SERVICE_WITH_ICON_RENDERING
    const auto &icon = makeAndroidIcon(commonForkAwesomeIcons().exclamation);
#else
    static const auto icon = QJniObject();
#endif
    updateExtraAndroidNotification(title, text, subText, page, icon, 2);
}

void AppService::clearSyncthingErrorsNotification()
{
    clearAndroidExtraNotifications(2, -1);
}

void AppService::showInternalError(const InternalError &error)
{
    const auto title = QJniObject::fromString(
        m_internalErrors.empty() ? tr("Syncthing API error") : tr("%1 Syncthing API errors").arg(m_internalErrors.size() + 1));
    const auto text = QJniObject::fromString(m_internalErrors.empty() ? error.message : tr("Most recent: ") + error.message);
    const auto subText = QJniObject::fromString(error.url.isEmpty() ? QString() : QStringLiteral("URL: ") + error.url.toString());
    static const auto page = QJniObject::fromString(QStringLiteral("internalErrors"));
#ifdef SYNCTHINGTRAY_SERVICE_WITH_ICON_RENDERING
    const auto &icon = makeAndroidIcon(commonForkAwesomeIcons().exclamation);
#else
    static const auto icon = QJniObject();
#endif
    updateExtraAndroidNotification(title, text, subText, page, icon, 3);
}

void AppService::showNewDevice(const QString &devId, const QString &message)
{
    const auto title = QJniObject::fromString(tr("Syncthing device wants to connect"));
    const auto text = QJniObject::fromString(message);
    static const auto subText = QJniObject::fromString(QString());
    const auto page = QJniObject::fromString(QStringLiteral("newdev:") + devId);
#ifdef SYNCTHINGTRAY_SERVICE_WITH_ICON_RENDERING
    const auto &icon = makeAndroidIcon(commonForkAwesomeIcons().networkWired);
#else
    static const auto icon = QJniObject();
#endif
    updateExtraAndroidNotification(title, text, subText, page, icon);
}

void AppService::showNewDir(const QString &devId, const QString &dirId, const QString &dirLabel, const QString &message)
{
    const auto title = QJniObject::fromString(tr("Syncthing device wants to share folder"));
    const auto text = QJniObject::fromString(message);
    static const auto subText = QJniObject::fromString(QString());
    const auto page = QJniObject::fromString(QStringLiteral("newfolder:") % devId % QChar(':') % dirId % QChar(':') % dirLabel);
#ifdef SYNCTHINGTRAY_SERVICE_WITH_ICON_RENDERING
    const auto &icon = makeAndroidIcon(commonForkAwesomeIcons().shareAlt);
#else
    static const auto icon = QJniObject();
#endif
    updateExtraAndroidNotification(title, text, subText, page, icon);
}
#endif

} // namespace QtGui