File: syncthingfileitemactionstaticdata.cpp

package info (click to toggle)
syncthingtray 1.7.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,804 kB
  • sloc: cpp: 31,085; xml: 1,694; java: 570; sh: 81; javascript: 53; makefile: 25
file content (217 lines) | stat: -rw-r--r-- 8,163 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
#include "./syncthingfileitemactionstaticdata.h"

#include <syncthingmodel/syncthingicons.h>

#include <syncthingconnector/syncthingconfig.h>
#include <syncthingconnector/syncthingconnection.h>
#include <syncthingconnector/syncthingconnectionsettings.h>

#include <c++utilities/application/argumentparser.h>
#include <c++utilities/io/ansiescapecodes.h>

#include <qtutilities/aboutdialog/aboutdialog.h>
#include <qtutilities/resources/resources.h>

#include <QAction>
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QSettings>

#include <iostream>

#include "resources/config.h"
#include "resources/qtconfig.h"

using namespace std;
using namespace CppUtilities::EscapeCodes;
using namespace QtUtilities;
using namespace Data;

SyncthingFileItemActionStaticData::SyncthingFileItemActionStaticData()
    : m_initialized(false)
{
}

void SyncthingFileItemActionStaticData::initialize()
{
    if (m_initialized) {
        return;
    }

    LOAD_QT_TRANSLATIONS;

    // load settings
    const QSettings settingsFile(QSettings::IniFormat, QSettings::UserScope, QStringLiteral(PROJECT_NAME));

    // determine path of Syncthing config file
    m_configFilePath = [&] {
        const QByteArray configPathFromEnv(qgetenv("KIO_SYNCTHING_CONFIG_PATH"));
        if (!configPathFromEnv.isEmpty()) {
            return QString::fromLocal8Bit(configPathFromEnv);
        }
        const QString configPathFromSettings = settingsFile.value(QStringLiteral("syncthingConfigPath")).toString();
        if (!configPathFromSettings.isEmpty()) {
            return configPathFromSettings;
        }
        return SyncthingConfig::locateConfigFile();
    }();
    applySyncthingConfiguration(m_configFilePath, settingsFile.value(QStringLiteral("syncthingApiKey")).toString(), true);

    // prevent unnecessary API calls (for the purpose of the context menu)
    m_connection.disablePolling();
    m_connection.setPollingFlags(SyncthingConnection::PollingFlags::MainEvents);

    // connect Signals & Slots for logging
    connect(&m_connection, &SyncthingConnection::error, this, &SyncthingFileItemActionStaticData::logConnectionError);
    if (qEnvironmentVariableIsSet("KIO_SYNCTHING_LOG_STATUS")) {
        connect(&m_connection, &SyncthingConnection::statusChanged, this, &SyncthingFileItemActionStaticData::logConnectionStatus);
    }

    m_initialized = true;
}

void SyncthingFileItemActionStaticData::logConnectionStatus()
{
    cerr << "Syncthing connection status changed to: " << m_connection.statusText().toLocal8Bit().data() << endl;
}

void SyncthingFileItemActionStaticData::logConnectionError(const QString &errorMessage, SyncthingErrorCategory errorCategory)
{
    switch (errorCategory) {
    case SyncthingErrorCategory::Parsing:
    case SyncthingErrorCategory::SpecificRequest:
        QMessageBox::critical(nullptr, tr("Syncthing connection error"), errorMessage);
        break;
    default:
        cerr << "Syncthing connection error: " << errorMessage.toLocal8Bit().data() << endl;
    }
}

void SyncthingFileItemActionStaticData::rescanDir(const QString &dirId, const QString &relpath)
{
    auto row = int();
    const auto *const dirInfo = m_connection.findDirInfo(dirId, row);
    if (dirInfo && !dirInfo->paused) {
        m_connection.rescan(dirId, relpath);
    }
}

void SyncthingFileItemActionStaticData::showAboutDialog()
{
    auto *const aboutDialog = new AboutDialog(nullptr, QStringLiteral(APP_NAME), aboutDialogAttribution(), QStringLiteral(APP_VERSION),
        CppUtilities::applicationInfo.dependencyVersions, QStringLiteral(APP_URL), QStringLiteral(APP_DESCRIPTION), aboutDialogImage());
    aboutDialog->setWindowTitle(tr("About") + QStringLiteral(" - " APP_NAME));
    aboutDialog->setWindowIcon(QIcon::fromTheme(QStringLiteral("syncthingtray")));
    aboutDialog->setAttribute(Qt::WA_DeleteOnClose);
    aboutDialog->show();
}

void SyncthingFileItemActionStaticData::selectSyncthingConfig()
{
    const auto configFilePath = QFileDialog::getOpenFileName(nullptr, tr("Select Syncthing config file") + QStringLiteral(" - " APP_NAME));
    if (!configFilePath.isEmpty()) {
        applySyncthingConfiguration(configFilePath, QString(), false);
    }
}

void SyncthingFileItemActionStaticData::appendNoteToError(QString &errorMessage, const QString &newSyncthingConfigFilePath) const
{
    if (!m_configFilePath.isEmpty() && m_configFilePath != newSyncthingConfigFilePath) {
        errorMessage += QChar('\n');
        errorMessage += tr("(still using config from \"%1\")").arg(m_configFilePath);
    }
}

bool SyncthingFileItemActionStaticData::applySyncthingConfiguration(
    const QString &syncthingConfigFilePath, const QString &syncthingApiKey, bool skipSavingConfig)
{
    clearCurrentError();

    // check for empty path
    if (syncthingConfigFilePath.isEmpty()) {
        setCurrentError(tr("Syncthing config file can not be automatically located"));
        return false;
    }

    // load Syncthing config
    SyncthingConfig config;
    if (!config.restore(syncthingConfigFilePath)) {
        auto errorMessage = tr("Unable to load Syncthing config from \"%1\"").arg(syncthingConfigFilePath);
        appendNoteToError(errorMessage, syncthingConfigFilePath);
        setCurrentError(errorMessage);
        return false;
    }
    cerr << Phrases::Info << "Syncthing config loaded from \"" << syncthingConfigFilePath.toLocal8Bit().data() << "\"" << Phrases::End;

    // check whether the URL is present
    if (config.guiAddress.isEmpty()) {
        auto errorMessage = tr("Syncthing config from \"%1\" does not contain GUI address.").arg(syncthingConfigFilePath);
        appendNoteToError(errorMessage, syncthingConfigFilePath);
        setCurrentError(errorMessage);
        return false;
    }

    // check whether the API key is present
    if (config.guiApiKey.isEmpty()) {
        config.guiApiKey = syncthingApiKey;
    }
    if (config.guiApiKey.isEmpty()) {
        config.guiApiKey = QInputDialog::getText(
            nullptr, tr("Enter API key"), tr("The selected config file does not contain an API key. Please enter the API key manually:"));
        if (config.guiApiKey.isEmpty()) {
            auto errorMessage = tr("No API key supplied for \"%1\".").arg(config.guiAddress);
            appendNoteToError(errorMessage, syncthingConfigFilePath);
            setCurrentError(errorMessage);
            return false;
        }
    }

    // make connection settings
    SyncthingConnectionSettings connectionSettings;
    connectionSettings.syncthingUrl = config.syncthingUrl();
    connectionSettings.apiKey.append(config.guiApiKey.toUtf8());

    // establish connection
    bool ok;
    int reconnectInterval = qEnvironmentVariableIntValue("KIO_SYNCTHING_RECONNECT_INTERVAL", &ok);
    if (!ok || reconnectInterval < 0) {
        reconnectInterval = 10000;
    }
    m_connection.setAutoReconnectInterval(reconnectInterval);
    m_connection.reconnect(connectionSettings);

    // save new config persistently
    if (!skipSavingConfig) {
        QSettings settings(QSettings::IniFormat, QSettings::UserScope, QStringLiteral(PROJECT_NAME));
        settings.setValue(QStringLiteral("syncthingConfigPath"), m_configFilePath = syncthingConfigFilePath);
        settings.setValue(QStringLiteral("syncthingApiKey"), config.guiApiKey);
    }

    return true;
}

void SyncthingFileItemActionStaticData::applyBrightCustomColorsSetting(const QPalette &palette)
{
    static const auto settings = [] {
        auto defaultSettings = StatusIconSettings();
        defaultSettings.strokeWidth = StatusIconStrokeWidth::Thick;
        return defaultSettings;
    }();
    auto &iconManager = IconManager::instance();
    iconManager.setPalette(palette);
    iconManager.applySettings(&settings, &settings, true, true);
}

void SyncthingFileItemActionStaticData::setCurrentError(const QString &currentError)
{
    if (m_currentError == currentError) {
        return;
    }
    const bool hadError = hasError();
    m_currentError = currentError;
    if (hadError != hasError()) {
        emit hasErrorChanged(hasError());
    }
    emit currentErrorChanged(m_currentError);
}