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
|
/**
* Copyright (C) 2021-2024 Saturneric <eric@bktus.com>
*
* This file is part of GpgFrontend.
*
* GpgFrontend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GpgFrontend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>.
*
* The initial version of the source code is inherited from
* the gpg4usb project, which is under GPL-3.0-or-later.
*
* All the source code of GpgFrontend was modified and released by
* Saturneric <eric@bktus.com> starting on May 12, 2021.
*
* SPDX-License-Identifier: GPL-3.0-or-later
*
*/
#include "VersionCheckingModule.h"
#include <GFSDKBuildInfo.h>
#include <GFSDKLog.h>
#include <GFSDKUI.h>
#include <GFSDKHostCommands.hpp>
#include <QCheckBox>
#include <QGroupBox>
#include <QPointer>
#include <QVBoxLayout>
#include <QtNetwork>
#include <atomic>
#include "GFModule.h"
#include "GFModuleIdentity.h"
#include "GFModuleTr.h"
#include "UpdateChecker.h"
#include "UpdateTab.h"
#include "Utils.h"
namespace {
/// Spelled unqualified: lupdate misreads `gf::cmd::Meta kMeta{` in a class
/// body and warns about an unknown namespace.
using CommandMeta = gf::cmd::Meta;
/// Whether to check at startup. The Host's own setting: the setup wizard
/// asks it, and this module's settings page shows the same switch rather
/// than a second one that could disagree.
constexpr auto kProhibitKey = "network/prohibit_update_check";
/// The checker's state, last known good result included.
constexpr auto kStateKey = "update_checking_state";
std::atomic<bool> g_stopped{false};
QPointer<UpdateChecker> g_checker;
/// A GitHub API GET through Qt. Every request answers, success or not: a
/// transport failure is status 0, and the transfer timeout bounds a server
/// that never replies.
auto MakeFetcher(QNetworkAccessManager* nam) -> UpdateChecker::Fetcher {
return [nam = QPointer<QNetworkAccessManager>(nam)](
const QUrl& url, const UpdateChecker::Reply& reply) {
if (nam.isNull()) {
reply(0, {});
return;
}
QNetworkRequest request(url);
request.setTransferTimeout(30000);
request.setHeader(QNetworkRequest::UserAgentHeader,
GFAppUserAgent(GFModuleSdkContext()));
request.setRawHeader("Accept", "application/vnd.github+json");
request.setRawHeader("X-GitHub-Api-Version", "2022-11-28");
auto* r = nam->get(request);
QObject::connect(r, &QNetworkReply::finished, r, [r, reply] {
const int status =
r->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
FLOG_DEBUG("update check reply: %1, http status: %2, error: %3",
r->url().toString(), status, r->errorString());
const auto body = r->readAll();
r->deleteLater();
reply(status, body);
});
};
}
auto MakeStore() -> UpdateChecker::Store {
return {
[] {
return gf::sdk::CacheText(GFModuleSdkContext(), GF_STORE_DURABLE,
kStateKey)
.toUtf8();
},
[](const QByteArray& data) {
gf::sdk::SetCacheText(GFModuleSdkContext(), GF_STORE_DURABLE, kStateKey,
QString::fromUtf8(data));
},
};
}
/// On the GUI thread, where the checker and its requests live.
template <typename F>
void OnGuiThread(F&& f) {
QMetaObject::invokeMethod(QCoreApplication::instance(), std::forward<F>(f));
}
void OpenUpdateDialog() {
Commands().Invoke<gf::cmd::host::ViewOpen>(
{gf::cmd::ViewRef{QStringLiteral(GF_MODULE_ID ".update")}});
}
/// The update dialog, in a frame the Host owns.
class UpdateWidget : public QWidget, public gf::ui::DialogWidget {
public:
UpdateWidget() {
auto* layout = new QVBoxLayout(this);
layout->addWidget(new UpdateTab(this));
}
};
/// Settings > Updates: whether to check at startup. Nothing else is worth a
/// setting: there is one release server, and a day is the right interval.
class UpdateSettingsWidget : public QWidget, public gf::ui::SettingsWidget {
public:
UpdateSettingsWidget() {
auto* box = new QGroupBox(GTrC::tr("Update Checking"), this);
auto* column = new QVBoxLayout(box);
check_ = new QCheckBox(
GTrC::tr("Checking for version updates when the application "
"starts."),
box);
column->addWidget(check_);
auto* layout = new QVBoxLayout(this);
layout->addWidget(box);
layout->addStretch();
}
void LoadSettings() override {
check_->setChecked(!gf::sdk::Setting(GFModuleSdkContext(), GF_SETTING_HOST,
kProhibitKey, true)
.toBool());
}
auto ApplySettings() -> bool override {
return gf::sdk::SetSetting(GFModuleSdkContext(), GF_SETTING_HOST,
kProhibitKey, !check_->isChecked());
}
private:
QCheckBox* check_;
};
/// Help > Check for Updates.
struct CheckForUpdates {
static constexpr CommandMeta kMeta{
GF_MODULE_ID ".check_for_updates",
GTrC::Noop("Check for Updates"),
GTrC::Noop("See whether a newer GpgFrontend is available"),
"",
0,
gf::cmd::kNeedsGuiThread};
using Args = gf::cmd::Unit;
using Result = gf::cmd::Unit;
};
auto DoCheckForUpdates(const gf::cmd::CommandContext& /*ctx*/,
const gf::cmd::Unit& /*args*/)
-> gf::cmd::Outcome<gf::cmd::Unit> {
OpenUpdateDialog();
return gf::cmd::Outcome<gf::cmd::Unit>::Success({});
}
} // namespace
auto VersionChecker() -> UpdateChecker* {
if (g_stopped.load()) return nullptr;
if (g_checker.isNull()) {
auto* ctx = GFModuleSdkContext();
auto* nam = new QNetworkAccessManager();
g_checker = new UpdateChecker({QString::fromUtf8(GFAppVersion(ctx)),
QString::fromUtf8(GFAppGitCommitHash(ctx))},
MakeFetcher(nam), MakeStore());
nam->setParent(g_checker);
QObject::connect(g_checker, &UpdateChecker::Changed, g_checker,
[checker = g_checker.data()] {
FillGrtWithVersionInfo(checker->State());
});
FillGrtWithVersionInfo(g_checker->State());
}
return g_checker;
}
auto OnActivate() -> GFResult {
LOG_INFO("version checking module activating");
g_stopped.store(false);
// Left behind by 1.5 and earlier: a cache in the old format, and the choice
// of a check service that no longer exists.
gf::sdk::RemoveCache(GFModuleSdkContext(), GF_STORE_DURABLE,
"update_checking_cache");
gf::sdk::RemoveSetting(GFModuleSdkContext(), GF_SETTING_MODULE,
"update_checking_api");
const bool dialog = gf::ui::RegisterNativeWidget<UpdateWidget>(
"update", {GTrC::Noop("Check for Updates"), "", "", "", "", 0, 0},
[](const QCborMap& /*args*/) { return new UpdateWidget(); });
const bool settings = gf::ui::RegisterNativeWidget<UpdateSettingsWidget>(
"settings",
{GTrC::Noop("Updates"), GTrC::Noop("update,version,check,github"), "", "",
"", 0, 0},
[](const QCborMap& /*args*/) { return new UpdateSettingsWidget(); });
return dialog && settings
? GFResult::Ok()
: GFResult::Fail("the update widgets were not registered");
}
auto OnDeactivate() -> GFResult {
// No check starts from here on; the checker and its requests go with the
// event loop's next turn, on the thread that owns them.
g_stopped.store(true);
if (!g_checker.isNull()) {
QMetaObject::invokeMethod(g_checker.data(), &QObject::deleteLater,
Qt::QueuedConnection);
}
return GFResult::Ok();
}
auto OnApplicationLoaded(const GFEvent& /*event*/) -> GFEventResult {
LOG_DEBUG("application starting completed event: processing");
// Absent until the setup wizard has run: no check before the user has been
// asked whether to check at all.
const auto prohibited =
gf::sdk::Setting(GFModuleSdkContext(), GF_SETTING_HOST, kProhibitKey);
if (!prohibited.isValid()) {
LOG_DEBUG("application loaded: the setup wizard has not asked yet");
return GFEventResult::Ok();
}
if (prohibited.toBool()) {
LOG_DEBUG("application loaded: update checking is prohibited");
return GFEventResult::Ok();
}
// In the background, and quietly: a newer release shows as a badge on
// Help > Check for Updates, never as a window.
OnGuiThread([] {
if (auto* checker = VersionChecker()) checker->Start(CheckMode::kIfStale);
});
// An observation, answered at once: the check runs on its own.
return GFEventResult::Ok();
}
auto OnUnload() -> void { LOG_INFO("version checking module unregistering"); }
// The module's whole framework surface.
constexpr std::array<GFEventBinding, 1> kEvents = {{
{"APPLICATION_LOADED", &OnApplicationLoaded},
}};
const std::array<gf::cmd::Binding, 1> kCommands = {
gf::cmd::Bind<CheckForUpdates, &DoCheckForUpdates>(),
};
const GFModuleHooks kHooks = {
sizeof(GFModuleHooks),
GF_MODULE_ID,
GF_MODULE_VERSION,
GF_MODULE_TRANSLATION_CONTEXT,
&OnActivate,
&OnDeactivate, // stops a running check; the Host withdraws the rest
&OnUnload,
kEvents.data(),
kEvents.size(),
kCommands.data(),
kCommands.size(),
};
extern "C" GF_MODULE_EXPORT auto GFModuleGetApi(uint32_t abi)
-> const GFModuleApi* {
return GFModuleRuntimeGetApi(abi, &kHooks);
}
|