aboutsummaryrefslogtreecommitdiffstats
path: root/src/m_ver_check/VersionCheckingModule.cpp
blob: 078df1090554e00b81d390a47532741b9c2c5dd5 (plain)
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
/**
 * 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 <QMetaType>
#include <QtNetwork>

#include "BKTUSVersionCheckTask.h"
#include "GFModule.h"
#include "GFModuleIdentity.h"
#include "GitHubVersionCheckTask.h"
#include "SoftwareVersion.h"
#include "UpdateTab.h"
#include "Utils.h"

auto OnActivate() -> GFResult {
  LOG_INFO("version checking module activating");
  return GFResult::Ok();
}

namespace {

auto CheckUpdate(const GFEvent& event) -> GFEventResult {
  if (event.Str("api") == "bktus") {
    MLogInfo("checking updating using api of bktus.com");
    auto* task = new BKTUSVersionCheckTask();
    QObject::connect(
        task, &BKTUSVersionCheckTask::SignalUpgradeVersion,
        QThread::currentThread(), [event](const SoftwareVersion& sv) {
          gf::sdk::SetCacheText(
              GFModuleSdkContext(), GF_STORE_DURABLE, "update_checking_cache",
              (QJsonDocument(sv.ToJson()).toJson()).constData());
          return GFEventResult::Ok();
        });
    QObject::connect(task, &BKTUSVersionCheckTask::SignalUpgradeVersion, task,
                     &QObject::deleteLater);
    task->Run();
  } else {
    MLogInfo("checking updating using api of github.com");
    auto* task = new GitHubVersionCheckTask();
    QObject::connect(
        task, &GitHubVersionCheckTask::SignalUpgradeVersion,
        QCoreApplication::instance(), [event](const SoftwareVersion& sv) {
          gf::sdk::SetCacheText(
              GFModuleSdkContext(), GF_STORE_DURABLE, "update_checking_cache",
              (QJsonDocument(sv.ToJson()).toJson()).constData());
          return GFEventResult::Ok();
        });
    QObject::connect(task, &GitHubVersionCheckTask::SignalUpgradeVersion, task,
                     &QObject::deleteLater);
    task->Run();
  }
  // The check runs asynchronously and its callback answers, so nothing is
  // answered here.
  return GFEventResult::Deferred();
}

auto RaiseUpdateDialog(QWidget* parent) -> QDialog* {
  auto* dialog = new QDialog(parent);
  dialog->setWindowTitle(
      QCoreApplication::translate("GTrC", "Check for Updates"));
  dialog->setModal(true);
  dialog->setAttribute(Qt::WA_DeleteOnClose);
  auto* layout = new QVBoxLayout();
  auto* update_tab = new UpdateTab(dialog);
  layout->addWidget(update_tab);
  dialog->setLayout(layout);
  dialog->resize(500, 600);
  dialog->show();
  return dialog;
}

}  // namespace

auto OnMainwindowMenuMounted(const GFEvent& event) -> GFEventResult {
  LOG_DEBUG("main window menu mounted event: processing");

  if (!event.Has("main_window")) {
    LOG_DEBUG("main window menu mounted event: no main_window found");
    return GFEventResult::Bad("no main_window found");
  }

  auto* main_window = GFUIObject<QMainWindow>(event.Str("main_window"));
  if (!main_window) {
    LOG_ERROR(
        "main window menu mounted: main_window handle invalid or not "
        "QMainWindow");
    return GFEventResult::Bad("main_window handle invalid or not QMainWindow");
  }

  auto p_mw = QPointer<QMainWindow>(main_window);

  if (!event.Has("help_menu")) {
    LOG_DEBUG("main window menu mounted event: no help_menu found");
    return GFEventResult::Bad("no help_menu found");
  }

  auto* help_menu = GFUIObject<QMenu>(event.Str("help_menu"));
  if (!help_menu) {
    LOG_ERROR(
        "main window menu mounted: help_menu handle invalid or not "
        "QMenu");
    return GFEventResult::Bad("help_menu handle invalid or not QMenu");
  }

  auto p_help_menu = QPointer<QMenu>(help_menu);

  LOG_DEBUG("adding check update action to help menu");

  QMetaObject::invokeMethod(
      QApplication::instance(),
      [&]() -> void {
        if (!p_mw || !p_help_menu) {
          LOG_ERROR(
              "main window menu mounted: main_window or help_menu was deleted "
              "before invoking the check update action");
          return;
        }

        QWidget* parent =
            qobject_cast<QWidget*>(static_cast<QObject*>(main_window));
        auto* action = new QAction(
            QCoreApplication::translate("GTrC", "Check for Updates"), nullptr);
        action->setToolTip(QCoreApplication::translate(
            "GTrC", "Check for updates from the Internet."));
        action->setIcon(QIcon(":/icons/update.png"));
        QObject::connect(action, &QAction::triggered, parent,
                         [=]() -> void { RaiseUpdateDialog(parent); });
        help_menu->addAction(action);
      },
      Qt::BlockingQueuedConnection);
  return GFEventResult::Ok();
}

auto OnApplicationLoaded(const GFEvent& event) -> GFEventResult {
  LOG_DEBUG("application starting completed event: processing");

  auto* parent = GFUIObject<QWidget>(
      event.Has("main_window") ? event.Str("main_window") : "");
  if (!parent) {
    LOG_ERROR("application loaded: main_window handle invalid or not QWidget");
    return GFEventResult::Bad("main_window handle invalid or not QWidget");
  }

  // check version information
  auto settings = qobject_cast<QSettings*>(
      static_cast<QObject*>(GFStorageSettingsRoot(GFModuleSdkContext())));
  if (!settings) {
    LOG_ERROR("application loaded: global settings handle invalid");
    return GFEventResult::Bad("global settings handle invalid");
  }

  // ensure that it will not perform at the first startup before wizard is done
  if (!settings->contains("network/prohibit_update_checking")) {
    LOG_DEBUG(
        "application loaded: prohibit_update_checking setting "
        "not found");
    return GFEventResult::Ok();
  }

  auto update_checking_api =
      settings->value("network/update_checking_api", "github").toString();
  FLOG_DEBUG("application loaded: update checking api: %1",
             update_checking_api);

  // we only check for update if the user did set the option to allow it
  auto prohibit_update_checking =
      settings->value("network/prohibit_update_checking", true).toBool();
  FLOG_DEBUG("application loaded: prohibit update checking: %1",
             prohibit_update_checking);

  if (prohibit_update_checking) {
    LOG_DEBUG("application loaded: update checking is prohibited");
    return GFEventResult::Ok();
  }

  auto cache = gf::sdk::CacheText(GFModuleSdkContext(), GF_STORE_DURABLE,
                                  "update_checking_cache");
  auto json = QJsonDocument::fromJson(cache.toUtf8());

  if (json.isEmpty() || !json.isObject()) {
    LOG_DEBUG(
        "application loaded: no valid cached version info found, "
        "checking update");
    return CheckUpdate(event);
  }

  SoftwareVersion sv;
  sv.FromJson(json.object());

  FLOG_DEBUG("got software version meta data: %1", json.toJson());
  if (sv.timestamp.addDays(1) < QDateTime::currentDateTime()) {
    return CheckUpdate(event);
  }

  FillGrtWithVersionInfo(sv);

  if (sv.NeedUpgrade() || !sv.CurrentVersionReleased() ||
      !sv.current_commit_hash_publish_in_remote) {
    LOG_INFO(
        "software version is outdated or not fully released, notifying user");

    QMetaObject::invokeMethod(
        QApplication::instance(),
        [=]() {
          auto* dialog = RaiseUpdateDialog(parent);
          Q_UNUSED(dialog);
        },
        Qt::QueuedConnection);
  }

  return GFEventResult::Ok();
}

auto OnNetworkSettingsTabUiCreated(const GFEvent& event) -> GFEventResult {
  LOG_DEBUG("network settings tab ui created event: processing");

  auto* tab = GFUIObject<QWidget>(event.Has("network_settings_tab")
                                      ? event.Str("network_settings_tab")
                                      : "");
  if (!tab) {
    LOG_ERROR(
        "network settings tab ui created: network_settings_tab handle "
        "invalid or not QWidget");
    return GFEventResult::Bad(
        "network_settings_tab handle invalid or not QWidget");
  }

  auto* capability_group_box = GFUIObject<QGroupBox>(
      event.Has("capability_group_box") ? event.Str("capability_group_box")
                                        : "");

  if (!capability_group_box) {
    LOG_ERROR(
        "network settings tab ui created: capability_group_box handle "
        "invalid or not QGroupBox");
    return GFEventResult::Bad(
        "capability_group_box handle invalid or not QGroupBox");
  }

  QMetaObject::invokeMethod(
      QApplication::instance(),
      [=]() {
        auto* update_checking_check_box = new QCheckBox(
            QCoreApplication::translate("GTrC",
                                        "Checking for version updates when the "
                                        "application starts."),
            capability_group_box);
        update_checking_check_box->setObjectName("update_checking_check_box");

        capability_group_box->layout()->addWidget(update_checking_check_box);

        auto* github_radio_button =
            new QRadioButton(QCoreApplication::translate("GTrC", "GitHub"),
                             capability_group_box);
        auto* bktus_radio_button =
            new QRadioButton(QCoreApplication::translate("GTrC", "BKTUS.com"),
                             capability_group_box);

        auto layout = new QHBoxLayout();
        layout->addWidget(new QLabel(
            QCoreApplication::translate("GTrC", "Update Checking API:"),
            capability_group_box));
        layout->addWidget(github_radio_button);
        layout->addWidget(bktus_radio_button);

        capability_group_box->layout()->addItem(layout);

        auto* update_api_group = new QButtonGroup(tab);
        update_api_group->setObjectName("update_api_group");
        update_api_group->addButton(github_radio_button);
        update_api_group->addButton(bktus_radio_button);
      },
      Qt::QueuedConnection);

  return GFEventResult::Ok();
}

auto OnNetworkSettingsTabApplySettings(const GFEvent& event) -> GFEventResult {
  LOG_DEBUG("network settings tab apply settings event: processing");
  auto* settings = qobject_cast<QSettings*>(
      static_cast<QObject*>(GFStorageSettingsRoot(GFModuleSdkContext())));
  if (!settings) {
    LOG_ERROR(
        "network settings tab apply settings: global settings handle "
        "invalid");
    return GFEventResult::Bad("global settings handle invalid");
  }
  auto* tab = GFUIObject<QWidget>(event.Has("network_settings_tab")
                                      ? event.Str("network_settings_tab")
                                      : "");
  if (!tab) {
    LOG_ERROR(
        "network settings tab apply settings: network_settings_tab "
        "handle invalid or not QWidget");
    return GFEventResult::Bad(
        "network_settings_tab handle invalid or not QWidget");
  }

  // we need to apply the settings in the main thread to avoid some
  // potential racing conditions
  auto p_tab = QPointer<QWidget>(tab);

  QMetaObject::invokeMethod(
      QApplication::instance(),
      [=]() {
        if (!p_tab) {
          LOG_ERROR(
              "network settings tab apply settings: network_settings_tab "
              "already deleted when applying settings");
          return;
        }
        auto* update_checking_check_box =
            p_tab->findChild<QCheckBox*>("update_checking_check_box");
        if (update_checking_check_box) {
          settings->setValue(
              "network/version_checking/"
              "check_for_updates_on_startup",
              update_checking_check_box->isChecked());
        }

        auto* update_api_group =
            tab->findChild<QButtonGroup*>("update_api_group");
        if (update_api_group) {
          QString api = "github";
          if (update_api_group->buttons().at(1)->isChecked()) {
            api = "bktus";
          }
          settings->setValue("network/version_checking/update_checking_api",
                             api);
        }

        FLOG_DEBUG(
            "network settings tab apply settings: version checking "
            "settings applied, "
            "check for updates on startup: %1, update checking api: %2",
            update_checking_check_box
                ? QString::number(update_checking_check_box->isChecked())
                : "null",
            update_api_group
                ? (update_api_group->buttons().at(1)->isChecked() ? "bktus"
                                                                  : "github")
                : "null");
      },
      Qt::QueuedConnection);

  return GFEventResult::Ok();
}

auto OnNetworkSettingsTabLoadSettings(const GFEvent& event) -> GFEventResult {
  LOG_DEBUG("network settings tab load settings event: processing");

  auto* settings = qobject_cast<QSettings*>(
      static_cast<QObject*>(GFStorageSettingsRoot(GFModuleSdkContext())));

  if (!settings) {
    LOG_ERROR(
        "network settings tab load settings: global settings handle "
        "invalid");
    return GFEventResult::Bad("global settings handle invalid");
  }

  auto* tab = GFUIObject<QWidget>(event.Has("network_settings_tab")
                                      ? event.Str("network_settings_tab")
                                      : "");
  if (!tab) {
    LOG_ERROR(
        "network settings tab load settings: network_settings_tab "
        "handle invalid or not QWidget");
    return GFEventResult::Bad(
        "network_settings_tab handle invalid or not QWidget");
  }

  QMetaObject::invokeMethod(
      QApplication::instance(),
      [=]() {
        auto* update_checking_check_box =
            tab->findChild<QCheckBox*>("update_checking_check_box");
        if (update_checking_check_box) {
          auto check_for_updates_on_startup =
              settings
                  ->value(
                      "network/version_checking/"
                      "check_for_updates_on_startup",
                      false)
                  .toBool();
          update_checking_check_box->setChecked(check_for_updates_on_startup);
        }

        auto* update_api_group =
            tab->findChild<QButtonGroup*>("update_api_group");
        if (update_api_group) {
          auto update_checking_api =
              settings
                  ->value("network/version_checking/update_checking_api",
                          "github")
                  .toString();
          if (update_checking_api == "github") {
            update_api_group->buttons().at(0)->setChecked(true);
          } else {
            update_api_group->buttons().at(1)->setChecked(true);
          }
        }
      },
      Qt::BlockingQueuedConnection);

  return GFEventResult::Ok();
}

auto OnUnload() -> void { LOG_INFO("version checking module unregistering"); }

// The module's whole framework surface.
constexpr GFEventBinding kEvents[] = {
    {"APPLICATION_LOADED", &OnApplicationLoaded},
    {"MAINWINDOW_MENU_MOUNTED", &OnMainwindowMenuMounted},
    {"NETWORK_SETTINGS_TAB_APPLY_SETTINGS", &OnNetworkSettingsTabApplySettings},
    {"NETWORK_SETTINGS_TAB_LOAD_SETTINGS", &OnNetworkSettingsTabLoadSettings},
    {"NETWORK_SETTINGS_TAB_UI_CREATED", &OnNetworkSettingsTabUiCreated},
};

constexpr GFModuleHooks kHooks = {
    sizeof(GFModuleHooks),
    GF_MODULE_ID,
    GF_MODULE_VERSION,
    GF_MODULE_TRANSLATION_CONTEXT,
    &OnActivate,
    nullptr,  // the settings tab is built through events, so nothing to undo
    &OnUnload,
    kEvents,
    std::size(kEvents),
};

extern "C" GF_MODULE_EXPORT auto GFModuleGetApi(uint32_t abi)
    -> const GFModuleApi* {
  return GFModuleRuntimeGetApi(abi, &kHooks);
}