forked from linuxdeepin/deepin-update-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdatework.cpp
More file actions
1479 lines (1302 loc) · 55.9 KB
/
Copy pathupdatework.cpp
File metadata and controls
1479 lines (1302 loc) · 55.9 KB
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2011 - 2023 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: LGPL-3.0-or-later
#include "updatework.h"
#include "utils.h"
#include "dconfigwatcher.h"
#include "updateloghelper.h"
#include <QDBusError>
#include <QDesktopServices>
#include <QFuture>
#include <QFutureWatcher>
#include <QJsonArray>
#include <QJsonDocument>
#include <QMutexLocker>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QVariant>
#include <QtConcurrent>
#include <DDBusSender>
#include <DNotifySender>
Q_LOGGING_CATEGORY(DCC_UPDATE_WORKER, "dcc-update-worker")
using namespace DCC_NAMESPACE;
const QString TestingChannel = "testing Channel";
const QString TestingChannelPackage = "deepin-unstable-source";
const QString ServiceLink = QStringLiteral("https://insider.deepin.org");
const QString ChangeLogFile = "/usr/share/deepin/release-note/UpdateInfo.json";
const QString ChangeLogDic = "/usr/share/deepin/";
const QString UpdateLogTmpFile = "/tmp/deepin-update-log.json";
const int LOWEST_BATTERY_PERCENT = 60;
static const QStringList DCC_CONFIG_FILES {
"/etc/deepin/dde-control-center.conf",
"/usr/share/dde-control-center/dde-control-center.conf"
};
void notifyError(const QString &summary, const QString &body)
{
DUtil::DNotifySender(summary)
.appIcon("")
.appName("org.deepin.dde.control-center")
.appBody(body)
.timeOut(5000)
.call();
}
void notifyErrorWithoutBody(const QString &summary)
{
DUtil::DNotifySender(summary)
.appIcon("")
.appName("org.deepin.dde.control-center")
.timeOut(5000)
.call();
}
static int TestMirrorSpeedInternal(const QString& url, QPointer<QObject> baseObject)
{
if (!baseObject || QCoreApplication::closingDown()) {
return -1;
}
QStringList args;
args << url << "-s"
<< "1";
QProcess process;
process.start("netselect", args);
if (!process.waitForStarted()) {
return 10000;
}
do {
if (!baseObject || QCoreApplication::closingDown()) {
process.kill();
process.terminate();
process.waitForFinished(1000);
return -1;
}
if (process.waitForFinished(500))
break;
} while (process.state() == QProcess::Running);
const QString output = process.readAllStandardOutput().trimmed();
const QStringList result = output.split(' ');
if (!result.first().isEmpty()) {
return result.first().toInt();
}
return 10000;
}
UpdateWorker::UpdateWorker(UpdateModel* model, QObject* parent)
: QObject(parent)
, m_lastoreDConfig(DConfig::create("org.deepin.dde.lastore", "org.deepin.dde.lastore", "", this))
, m_model(model)
, m_updateInter(new UpdateDBusProxy(this))
, m_lastoreHeartBeatTimer(new QTimer(this))
, m_machineid(std::nullopt)
, m_testingChannelUrl(std::nullopt)
, m_doCheckUpdates(false)
, m_checkUpdateJob(nullptr)
, m_fixErrorJob(nullptr)
, m_downloadJob(nullptr)
, m_distUpgradeJob(nullptr)
, m_backupJob(nullptr)
, m_installPackageJob(nullptr)
, m_removePackageJob(nullptr)
{
qRegisterMetaType<UpdatesStatus>("UpdatesStatus");
qRegisterMetaType<UiActiveState>("UiActiveState");
qRegisterMetaType<ControlPanelType>("ControlPanelType");
initConnect();
}
UpdateWorker::~UpdateWorker()
{
deleteJob(m_checkUpdateJob);
deleteJob(m_fixErrorJob);
deleteJob(m_downloadJob);
deleteJob(m_distUpgradeJob);
deleteJob(m_backupJob);
deleteJob(m_installPackageJob);
deleteJob(m_removePackageJob);
if (m_lastoreHeartBeatTimer != nullptr) {
if (m_lastoreHeartBeatTimer->isActive()) {
m_lastoreHeartBeatTimer->stop();
}
delete m_lastoreHeartBeatTimer;
m_lastoreHeartBeatTimer = nullptr;
}
}
void UpdateWorker::initConnect()
{
QDBusConnection::systemBus().connect("com.deepin.license",
"/com/deepin/license/Info",
"com.deepin.license.Info",
"LicenseStateChange", this, SLOT(onLicenseStateChange()));
// systemActivationChanged是在线程中发出
connect(this, &UpdateWorker::systemActivationChanged, m_model, &UpdateModel::setSystemActivation, Qt::QueuedConnection);
connect(m_updateInter, &UpdateDBusProxy::BatteryPercentageChanged, this, &UpdateWorker::onPowerChange);
connect(m_updateInter, &UpdateDBusProxy::OnBatteryChanged, this, &UpdateWorker::onPowerChange);
connect(m_updateInter, &UpdateDBusProxy::UpdateModeChanged, this, &UpdateWorker::onUpdateModeChanged);
connect(m_updateInter, &UpdateDBusProxy::JobListChanged, this, &UpdateWorker::onJobListChanged);
connect(m_updateInter, &UpdateDBusProxy::UpdateStatusChanged, this, &UpdateWorker::onUpdateStatusChanged);
connect(m_updateInter, &UpdateDBusProxy::ClassifiedUpdatablePackagesChanged, this, &UpdateWorker::onClassifiedUpdatablePackagesChanged);
QDBusConnection::systemBus().connect("org.deepin.dde.Lastore1",
"/org/deepin/dde/Lastore1",
"org.freedesktop.DBus.Properties",
"PropertiesChanged", m_model, SLOT(onUpdatePropertiesChanged(QString, QVariantMap, QStringList)));
connect(m_updateInter, &UpdateDBusProxy::UpdateNotifyChanged, m_model, &UpdateModel::setUpdateNotify);
connect(m_updateInter, &UpdateDBusProxy::AutoCleanChanged, m_model, &UpdateModel::setAutoCleanCache);
connect(m_updateInter, &UpdateDBusProxy::AutoDownloadUpdatesChanged, m_model, &UpdateModel::setAutoDownloadUpdates);
connect(m_updateInter, &UpdateDBusProxy::MirrorSourceChanged, m_model, &UpdateModel::setDefaultMirror);
if (IsCommunitySystem) {
connect(m_updateInter, &UpdateDBusProxy::EnableChanged, m_model, &UpdateModel::setSmartMirrorSwitch);
}
m_lastoreHeartBeatTimer->setInterval(60000);
m_lastoreHeartBeatTimer->start();
connect(m_lastoreHeartBeatTimer, &QTimer::timeout, this, &UpdateWorker::refreshLastTimeAndCheckCircle);
connect(DConfigWatcher::instance(), &DConfigWatcher::notifyDConfigChanged, [this](const QString &moduleName, const QString &configName) {
qCDebug(DCC_UPDATE_WORKER) << "Config changed:" << moduleName << configName;
if (moduleName != "update") {
return;
}
if (configName == "updateThirdPartySource") {
m_model->setThirdPartyUpdateEnabled(DConfigWatcher::instance()->getValue(DConfigWatcher::update, configName).toString() != "Hidden");
} else if (configName == "updateSafety") {
m_model->setSecurityUpdateEnabled(DConfigWatcher::instance()->getValue(DConfigWatcher::update, configName).toString() != "Hidden");
} else if (configName == "updateHistoryEnabled") {
// m_model->setUpdateHistoryEnabled(DConfigWatcher::instance()->getValue(DConfigWatcher::update, configName).toBool());
} else if (configName == "p2pUpdateEnabled") {
// m_model->setP2PUpdateEnabled(DConfigWatcher::instance()->getValue(DConfigWatcher::update, configName).toBool());
}
});
}
void UpdateWorker::activate()
{
qCInfo(DCC_UPDATE_WORKER) << "Active update worker";
initConfig();
onLicenseStateChange();
onPowerChange();
updateSystemVersion();
refreshLastTimeAndCheckCircle();
initTestingChannel();
m_model->setUpdateMode(m_updateInter->updateMode());
m_model->setCheckUpdateMode(m_updateInter->checkUpdateMode());
m_model->setSecurityUpdateEnabled(DConfigWatcher::instance()->getValue(DConfigWatcher::update, "updateSafety").toString() != "Hidden");
m_model->setThirdPartyUpdateEnabled(DConfigWatcher::instance()->getValue(DConfigWatcher::update, "updateThirdPartySource").toString() != "Hidden");
m_model->setSpeedLimitConfig(m_updateInter->downloadSpeedLimitConfig().toUtf8());
m_model->setAutoDownloadUpdates(m_updateInter->autoDownloadUpdates());
QString config = m_updateInter->idleDownloadConfig();
m_model->setIdleDownloadConfig(IdleDownloadConfig::toConfig(config.toUtf8()));
m_model->setUpdateNotify(m_updateInter->updateNotify());
m_model->setAutoCleanCache(m_updateInter->autoClean());
m_model->setP2PUpdateEnabled(m_updateInter->p2pUpdateEnable());
if (IsCommunitySystem) {
m_model->setSmartMirrorSwitch(m_updateInter->enable());
}
#ifndef DISABLE_SYS_UPDATE_MIRRORS
refreshMirrors();
#endif
m_model->setUpdateStatus(m_updateInter->updateStatus().toUtf8());
if (!m_model->isUpdateDisabled()) {
// 获取当前的job
const QList<QDBusObjectPath> jobs = m_updateInter->jobList();
if (jobs.count() > 0) {
onJobListChanged(jobs);
// 如果处于下载中或者安装中的时候直接显示更新内容,不检查更新
const bool isDownloading = m_downloadJob && m_downloadJob->status() != "failed";
const bool isUpgrading = m_distUpgradeJob && m_distUpgradeJob->status() != "failed";
if (isUpgrading || isDownloading) {
auto watcher = new QDBusPendingCallWatcher(m_updateInter->GetUpdateLogs(SystemUpdate | SecurityUpdate), this);
connect(watcher, &QDBusPendingCallWatcher::finished, [this, watcher] {
watcher->deleteLater();
if (!watcher->isError()) {
QDBusPendingReply<QString> reply = watcher->reply();
UpdateLogHelper::ref().handleUpdateLog(reply.value());
} else {
qCWarning(DCC_UPDATE_WORKER) << "Get update log failed";
}
// 日志处理完了再显示更新内容界面
m_model->setLastStatus(CheckingSucceed, __LINE__);
setUpdateInfo();
});
}
}
}
}
void UpdateWorker::initConfig()
{
if (m_lastoreDConfig && m_lastoreDConfig->isValid()) {
m_model->setLastoreDaemonStatus(m_lastoreDConfig->value("lastore-daemon-status").toInt());
connect(m_lastoreDConfig, &DConfig::valueChanged, this, [this](const QString& key) {
if ("lastore-daemon-status" == key) {
bool ok;
int value = m_lastoreDConfig->value(key).toInt(&ok);
if (ok) {
m_model->setLastoreDaemonStatus(value);
}
}
});
} else {
qCWarning(DCC_UPDATE_WORKER) << "Lastore dconfig is nullptr or invalid";
}
}
void UpdateWorker::getLicenseState()
{
if (IsCommunitySystem) {
emit systemActivationChanged(true);
return;
}
QDBusInterface licenseInfo("com.deepin.license",
"/com/deepin/license/Info",
"com.deepin.license.Info",
QDBusConnection::systemBus());
if (!licenseInfo.isValid()) {
qCWarning(DCC_UPDATE_WORKER) << "License info dbus is invalid.";
return;
}
UiActiveState reply =
static_cast<UiActiveState>(licenseInfo.property("AuthorizationState").toInt());
emit systemActivationChanged(reply == UiActiveState::Authorized || reply == UiActiveState::TrialAuthorized);
}
bool UpdateWorker::checkDbusIsValid()
{
return checkJobIsValid(m_checkUpdateJob) && checkJobIsValid(m_downloadJob);
}
bool UpdateWorker::checkJobIsValid(QPointer<UpdateJobDBusProxy> dbusJob)
{
if (dbusJob.isNull())
return false;
if (dbusJob->isValid())
return true;
dbusJob->deleteLater();
return false;
}
void UpdateWorker::deleteJob(QPointer<UpdateJobDBusProxy> dbusJob)
{
if (!dbusJob.isNull()) {
dbusJob->deleteLater();
dbusJob = nullptr;
}
}
void UpdateWorker::cleanLaStoreJob(QPointer<UpdateJobDBusProxy> dbusJob)
{
if (dbusJob != nullptr) {
m_updateInter->CleanJob(dbusJob->id());
deleteJob(dbusJob);
}
}
UpdateErrorType UpdateWorker::analyzeJobErrorMessage(const QString& jobDescription, UpdatesStatus status)
{
qCWarning(DCC_UPDATE_WORKER) << "Job description:" << jobDescription;
QJsonParseError err_rpt;
QJsonDocument jobErrorMessage = QJsonDocument::fromJson(jobDescription.toUtf8(), &err_rpt);
if (err_rpt.error != QJsonParseError::NoError) {
qCWarning(DCC_UPDATE_WORKER) << "Parse json failed";
return UnKnown;
}
const QJsonObject& object = jobErrorMessage.object();
QString errorType = object.value("ErrType").toString();
if (errorType.contains("fetchFailed", Qt::CaseInsensitive) || errorType.contains("IndexDownloadFailed", Qt::CaseInsensitive)) {
if (status == DownloadFailed) {
return DownloadingNoNetwork;
}
return NoNetwork;
}
if (errorType.contains("unmetDependencies", Qt::CaseInsensitive) || errorType.contains("dependenciesBroken", Qt::CaseInsensitive)) {
return DependenciesBrokenError;
}
if (errorType.contains("insufficientSpace", Qt::CaseInsensitive)) {
if (status == DownloadFailed) {
return DownloadingNoSpace;
}
return NoSpace;
}
if (errorType.contains("interrupted", Qt::CaseInsensitive)) {
return DpkgInterrupted;
}
if (errorType.contains("platformUnreachable", Qt::CaseInsensitive)) {
return PlatformUnreachable;
}
if (errorType.contains("invalidSourceList", Qt::CaseInsensitive)) {
return InvalidSourceList;
}
return UnKnown;
}
void UpdateWorker::checkNeedDoUpdates()
{
qCInfo(DCC_UPDATE_WORKER) << "check need do updates";
if (m_model->isUpdateDisabled()) {
m_model->setShowCheckUpdate(false);
return;
}
// 如果当前正在检查更新,则不再检查
if (m_doCheckUpdates) {
qCDebug(DCC_UPDATE_WORKER) << "Is doing check updates";
return;
}
// 如果打开控制中心后第一次进入检查更新界面,则显示页面并进行检查
static bool doCheckFirst = true;
if (doCheckFirst) {
doCheckFirst = false;
m_model->setShowCheckUpdate(true);
doCheckUpdates();
return;
}
// 如果非第一次进入检查更新界面,则需要判断上次检查时间和当前时间查决定是否需要再次检查, 默认24小时内不再检查
static const int AUTO_CHECK_UPDATE_CIRCLE = 3600 * 24;
qint64 checkTimeInterval = QDateTime::fromString(m_model->lastCheckUpdateTime(), "yyyy-MM-dd hh:mm:ss").secsTo(QDateTime::currentDateTime());
bool bEnter = checkTimeInterval > AUTO_CHECK_UPDATE_CIRCLE;
qCDebug(DCC_UPDATE_WORKER) << "check time interval:" << checkTimeInterval << " need to check:" << bEnter;
if (bEnter) {
m_model->setShowCheckUpdate(true);
doCheckUpdates();
return;
}
m_model->setShowCheckUpdate(!m_model->isUpdatable());
if (!m_model->isUpdatable()) {
m_model->setCheckUpdateStatus(UpdatesStatus::Updated);
}
}
void UpdateWorker::doCheckUpdates()
{
qCInfo(DCC_UPDATE_WORKER) << "do check updates";
if (checkDbusIsValid()) {
qCWarning(DCC_UPDATE_WORKER) << "Check Dbus's validation failed do nothing";
return;
}
if (m_checkUpdateJob) {
qCWarning(DCC_UPDATE_WORKER) << "Is checking update, won't do it again";
return;
}
const auto& allUpdateStatuses = m_model->allUpdateStatus();
if (allUpdateStatuses.contains(BackingUp)
|| allUpdateStatuses.contains(Upgrading)
|| allUpdateStatuses.contains(Downloading)
|| allUpdateStatuses.contains(DownloadPaused)) {
qCInfo(DCC_UPDATE_WORKER) << "Lastore daemon is busy now, current statuses:" << allUpdateStatuses;
m_model->setShowCheckUpdate(false);
return;
}
m_model->resetDownloadInfo(); // 在检查更新前重置数据,避免有上次检查的数据残留
m_doCheckUpdates = true;
QDBusPendingCall call = m_updateInter->UpdateSource();
QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(call, this);
connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher] {
QDBusPendingReply<QDBusObjectPath> reply = *watcher;
if (reply.isError()) {
qCWarning(DCC_UPDATE_WORKER) << "Check update failed, error: " << reply.error().message();
m_model->setLastStatus(UpdatesStatus::CheckingFailed, __LINE__);
cleanLaStoreJob(m_checkUpdateJob);
m_doCheckUpdates = false;
} else {
const QString jobPath = reply.value().path();
qCInfo(DCC_UPDATE_WORKER) << "jobpath:" << jobPath;
setCheckUpdatesJob(jobPath);
}
watcher->deleteLater();
});
}
void UpdateWorker::setCheckUpdatesJob(const QString& jobPath)
{
qCInfo(DCC_UPDATE_WORKER) << "Set check updates job";
UpdatesStatus state = m_model->updateStatus(CPT_Downloading);
if (UpdatesStatus::Downloading != state && UpdatesStatus::DownloadPaused != state) {
m_model->setLastStatus(UpdatesStatus::Checking, __LINE__);
}
m_model->setCheckUpdateStatus(UpdatesStatus::Checking);
createCheckUpdateJob(jobPath);
}
void UpdateWorker::createCheckUpdateJob(const QString& jobPath)
{
qCInfo(DCC_UPDATE_WORKER) << "Create check update job: " << jobPath;
if (m_checkUpdateJob != nullptr) {
qCInfo(DCC_UPDATE_WORKER) << "Check update job existed";
return;
}
m_checkUpdateJob = new UpdateJobDBusProxy(jobPath, this);
connect(m_checkUpdateJob, &UpdateJobDBusProxy::StatusChanged, this, &UpdateWorker::onCheckUpdateStatusChanged);
connect(m_checkUpdateJob, &UpdateJobDBusProxy::ProgressChanged, m_model, &UpdateModel::setCheckUpdateProgress, Qt::QueuedConnection);
m_checkUpdateJob->ProgressChanged(m_checkUpdateJob->progress());
m_checkUpdateJob->StatusChanged(m_checkUpdateJob->status());
}
void UpdateWorker::refreshLastTimeAndCheckCircle()
{
QString checkTime;
m_updateInter->GetCheckIntervalAndTime(checkTime);
m_model->setLastCheckUpdateTime(checkTime);
}
void UpdateWorker::setUpdateInfo()
{
const QMap<QString, QStringList>& updatePackages = m_updateInter->classifiedUpdatablePackages();
QMap<UpdateType, UpdateItemInfo*> updateInfoMap = getAllUpdateInfo(updatePackages);
bool isUpdated = true;
for (auto info : updateInfoMap.values()) {
m_model->addUpdateInfo(info);
if (info->isUpdateAvailable()) {
isUpdated = false;
}
}
m_model->refreshUpdateStatus();
m_model->updateAvailableState();
m_model->setLastStatus(isUpdated ? Updated : UpdatesAvailable, __LINE__);
}
/**
* @brief 获取更新信息,包大小、日志等内容
*
* @param updatePackages 例如:{{“system”, {"dde-session-ui, code"}}, {"security", {"dde-session-shell"}}}
* @return QMap<ClassifyUpdateType, UpdateItemInfo *>
*/
QMap<UpdateType, UpdateItemInfo*> UpdateWorker::getAllUpdateInfo(const QMap<QString, QStringList>& updatePackages)
{
const QStringList& systemPackages = updatePackages.value(SYSTEM_UPGRADE_TYPE_STRING);
const QStringList& securityPackages = updatePackages.value(SECURITY_UPGRADE_TYPE_STRING);
const QStringList& unknownPackages = updatePackages.value(UNKNOWN_UPGRADE_STRING);
const quint64 updateMode = m_model->updateMode();
QMap<UpdateType, UpdateItemInfo*> resultMap;
UpdateItemInfo* systemItemInfo = new UpdateItemInfo(SystemUpdate);
systemItemInfo->setTypeString(SYSTEM_UPGRADE_TYPE_STRING);
systemItemInfo->setName(tr("System Updates"));
systemItemInfo->setExplain(tr("Fixed some known bugs and security vulnerabilities"));
systemItemInfo->setPackages(systemPackages);
setUpdateItemDownloadSize(systemItemInfo);
systemItemInfo->setUpdateModeEnabled(updateMode & UpdateType::SystemUpdate);
resultMap.insert(UpdateType::SystemUpdate, systemItemInfo);
UpdateItemInfo* securityItemInfo = new UpdateItemInfo(SecurityUpdate);
securityItemInfo->setTypeString(SECURITY_UPGRADE_TYPE_STRING);
securityItemInfo->setName(tr("Security Updates"));
securityItemInfo->setExplain(tr("Fixed some known bugs and security vulnerabilities"));
securityItemInfo->setPackages(securityPackages);
setUpdateItemDownloadSize(securityItemInfo);
securityItemInfo->setUpdateModeEnabled(updateMode & UpdateType::SecurityUpdate);
resultMap.insert(UpdateType::SecurityUpdate, securityItemInfo);
UpdateItemInfo* unkownItemInfo = new UpdateItemInfo(UnknownUpdate);
unkownItemInfo->setTypeString(UNKNOWN_UPGRADE_STRING);
unkownItemInfo->setName(tr("Third-party Repositories"));
unkownItemInfo->setPackages(unknownPackages);
setUpdateItemDownloadSize(unkownItemInfo);
unkownItemInfo->setUpdateModeEnabled(updateMode & UpdateType::UnknownUpdate);
resultMap.insert(UpdateType::UnknownUpdate, unkownItemInfo);
// 将更新日志根据`系统更新`or`安全更新`进行分类,并保存留用
for (UpdateType type : resultMap.keys()) {
UpdateLogHelper::ref().updateItemInfo(resultMap.value(type));
}
return resultMap;
}
void UpdateWorker::setUpdateItemDownloadSize(UpdateItemInfo* updateItem)
{
if (updateItem->packages().isEmpty()) {
return;
}
QDBusPendingCall call = m_updateInter->QueryAllSizeWithSource(updateItem->updateType());
QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(call, this);
connect(watcher, &QDBusPendingCallWatcher::finished, updateItem, [updateItem, watcher] {
QDBusPendingReply<qlonglong> reply = *watcher;
if (reply.isError()) {
qCWarning(DCC_UPDATE_WORKER) << "Get packages size error:" << reply.error().message();
} else {
qlonglong value = reply.value();
qCInfo(DCC_UPDATE_WORKER) << "Packages' size:" << value << ", name:" << updateItem->name();
updateItem->setDownloadSize(value);
}
watcher->deleteLater();
});
}
void UpdateWorker::startDownload(int updateTypes)
{
qCInfo(DCC_UPDATE_WORKER) << "Start download, update types: " << updateTypes;
cleanLaStoreJob(m_downloadJob);
// 直接设置为正在下载状态, 否则切换下载界面等待时间稍长,体验不好
m_model->setLastStatus(UpdatesStatus::DownloadWaiting, __LINE__, updateTypes);
m_model->setDownloadWaiting(true);
// 开始下载
QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(m_updateInter->PrepareDistUpgradePartly(updateTypes), this);
connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher] {
QDBusPendingReply<QDBusObjectPath> reply = *watcher;
if (reply.isError()) {
const QString& errorMessage = reply.error().message();
qCWarning(DCC_UPDATE_WORKER) << "Start download failed, error:" << errorMessage;
m_model->setLastErrorLog(DownloadFailed, errorMessage);
m_model->setLastError(DownloadFailed, analyzeJobErrorMessage(errorMessage, DownloadFailed));
cleanLaStoreJob(m_downloadJob);
} else {
const QString jobPath = reply.value().path();
qCInfo(DCC_UPDATE_WORKER) << "jobpath:" << jobPath;
setDownloadJob(jobPath);
}
watcher->deleteLater();
});
}
void UpdateWorker::stopDownload()
{
if (!m_downloadJob) {
qCWarning(DCC_UPDATE_WORKER) << "Download job is null";
return;
}
cleanLaStoreJob(m_downloadJob);
}
void UpdateWorker::onDownloadJobCtrl(int updateCtrlType)
{
if (m_downloadJob == nullptr) {
qCWarning(DCC_UPDATE_WORKER) << "Download job is nullptr";
return;
}
switch (updateCtrlType) {
case UpdateCtrlType::Start:
qCInfo(DCC_UPDATE_WORKER) << "Start download job";
m_updateInter->StartJob(m_downloadJob->id());
break;
case UpdateCtrlType::Pause:
qCInfo(DCC_UPDATE_WORKER) << "Pause download job";
m_updateInter->PauseJob(m_downloadJob->id());
break;
}
}
void UpdateWorker::setDownloadJob(const QString& jobPath)
{
qCInfo(DCC_UPDATE_WORKER) << "Set download job: " << jobPath;
QMutexLocker locker(&m_downloadMutex);
if (m_downloadJob) {
qCInfo(DCC_UPDATE_WORKER) << "Download job existed, do not create again";
return;
}
m_downloadJob = new UpdateJobDBusProxy(jobPath, this);
connect(m_downloadJob, &UpdateJobDBusProxy::ProgressChanged, m_model, &UpdateModel::setDownloadProgress);
connect(m_downloadJob, &UpdateJobDBusProxy::StatusChanged, this, &UpdateWorker::onDownloadStatusChanged);
connect(m_downloadJob, &UpdateJobDBusProxy::DescriptionChanged, this, [this](const QString &description) {
if (m_downloadJob && m_downloadJob->status() == "failed") {
m_model->setLastErrorLog(DownloadFailed, description);
}
});
onDownloadStatusChanged(m_downloadJob->status());
m_model->setDownloadProgress(m_downloadJob->progress());
}
void UpdateWorker::doUpgrade(int updateTypes, bool doBackup)
{
qCInfo(DCC_UPDATE_WORKER) << "Do upgrade, update types:" << updateTypes << ", whether do backup:" << doBackup;
cleanLaStoreJob(m_distUpgradeJob);
cleanLaStoreJob(m_backupJob);
QDBusPendingCall call = m_updateInter->DistUpgradePartly(updateTypes, doBackup);
QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(call, this);
connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, updateTypes, watcher, doBackup] {
QDBusPendingReply<QDBusObjectPath> reply = *watcher;
if (reply.isError()) {
qCWarning(DCC_UPDATE_WORKER) << "Call `DistUpgradePartly` failed, error:" << reply.error().message();
} else {
m_model->setLastStatus(UpgradeWaiting, __LINE__, updateTypes);
m_model->setUpgradeWaiting(true);
const QString jobPath = reply.value().path();
qCInfo(DCC_UPDATE_WORKER) << "jobpath:" << jobPath;
if (doBackup) {
setBackupJob(jobPath);
} else {
setDistUpgradeJob(jobPath);
}
}
watcher->deleteLater();
});
}
void UpdateWorker::reStart()
{
qCInfo(DCC_UPDATE_WORKER) << "request restart";
m_updateInter->Restart();
}
void UpdateWorker::modalUpgrade(bool rebootAfterUpgrade)
{
qCInfo(DCC_UPDATE_WORKER) << "request modal upgrade, reboot after upgrade:" << rebootAfterUpgrade;
if (rebootAfterUpgrade) {
m_updateInter->UpdateAndReboot();
} else {
m_updateInter->UpdateAndShutdown();
}
}
void UpdateWorker::setBackupJob(const QString& jobPath)
{
qCInfo(DCC_UPDATE_WORKER) << "Create backup upgrade job, path:" << jobPath;
if (m_backupJob || jobPath.isEmpty()) {
qCInfo(DCC_UPDATE_WORKER) << "Job is not null or job path is empty";
return;
}
m_backupJob = new UpdateJobDBusProxy(jobPath, this);
connect(m_backupJob, &UpdateJobDBusProxy::ProgressChanged, m_model, &UpdateModel::setBackupProgress);
connect(m_backupJob, &UpdateJobDBusProxy::StatusChanged, this, &UpdateWorker::onBackupStatusChanged);
connect(m_backupJob, &UpdateJobDBusProxy::DescriptionChanged, this, [this](const QString &description) {
if (m_backupJob->status() == "failed") {
m_model->setLastErrorLog(BackupFailed, description);
}
});
m_model->setBackupProgress(m_backupJob->progress());
onBackupStatusChanged(m_backupJob->status());
}
void UpdateWorker::setDistUpgradeJob(const QString& jobPath)
{
qCInfo(DCC_UPDATE_WORKER) << "Create dist upgrade job, path:" << jobPath;
if (m_distUpgradeJob || jobPath.isEmpty()) {
qCInfo(DCC_UPDATE_WORKER) << "Job is not null or job path is empty";
return;
}
m_distUpgradeJob = new UpdateJobDBusProxy(jobPath, this);
connect(m_distUpgradeJob, &UpdateJobDBusProxy::ProgressChanged, m_model, &UpdateModel::setDistUpgradeProgress);
connect(m_distUpgradeJob, &UpdateJobDBusProxy::StatusChanged, this, &UpdateWorker::onDistUpgradeStatusChanged);
connect(m_distUpgradeJob, &UpdateJobDBusProxy::DescriptionChanged, this, [this](const QString &description) {
if (m_distUpgradeJob->status() == "failed") {
m_model->setLastErrorLog(UpgradeFailed, description);
}
});
m_model->setDistUpgradeProgress(m_distUpgradeJob->progress());
onDistUpgradeStatusChanged(m_distUpgradeJob->status());
}
void UpdateWorker::updateSystemVersion()
{
const DConfig* dconfig = DConfigWatcher::instance()->getModulesConfig(DConfigWatcher::update);
if (dconfig && dconfig->isValid()) {
m_model->setShowVersion(dconfig->value("showVersion").toString());
}
QString sVersion = QString("%1 %2").arg(DSysInfo::uosProductTypeName()).arg(DSysInfo::majorVersion());
if (!IsServerSystem)
sVersion.append(" " + DSysInfo::uosEditionName());
m_model->setSystemVersionInfo(sVersion);
QSettings settings("/etc/os-baseline", QSettings::IniFormat);
m_model->setBaseline(settings.value("Baseline").toString());
}
void UpdateWorker::setFunctionUpdate(bool update)
{
quint64 updateMode = m_model->updateMode();
if (update) {
updateMode |= UpdateType::SystemUpdate;
} else {
updateMode &= ~UpdateType::SystemUpdate;
}
m_updateInter->setUpdateMode(updateMode);
}
void UpdateWorker::setSecurityUpdate(bool update)
{
quint64 updateMode = m_model->updateMode();
if (update) {
updateMode |= UpdateType::SecurityUpdate;
} else {
updateMode &= ~UpdateType::SecurityUpdate;
}
m_updateInter->setUpdateMode(updateMode);
}
void UpdateWorker::setThirdPartyUpdate(bool update)
{
quint64 updateMode = m_model->updateMode();
if (update) {
updateMode |= UpdateType::UnknownUpdate;
} else {
updateMode &= ~UpdateType::UnknownUpdate;
}
m_updateInter->setUpdateMode(updateMode);
}
void UpdateWorker::setDownloadSpeedLimitEnabled(bool enable)
{
auto config = m_model->speedLimitConfig();
config.downloadSpeedLimitEnabled = enable;
// dbus返回需要1s,导致界面更新慢,这里直接先更新model
m_model->setSpeedLimitConfig(config.toJson().toUtf8());
setDownloadSpeedLimitConfig(config.toJson());
}
void UpdateWorker::setDownloadSpeedLimitSize(const QString& size)
{
qCDebug(DCC_UPDATE_WORKER) << "set download speed limit size" << size;
auto config = m_model->speedLimitConfig();
config.limitSpeed = size;
setDownloadSpeedLimitConfig(config.toJson());
}
void UpdateWorker::setDownloadSpeedLimitConfig(const QString& config)
{
QDBusPendingCall call = m_updateInter->SetDownloadSpeedLimit(config);
QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(call, this);
connect(watcher, &QDBusPendingCallWatcher::finished, this, [call, watcher] {
if (call.isError()) {
qCWarning(DCC_UPDATE_WORKER) << "Set download speed limit config error: " << call.error().message();
}
watcher->deleteLater();
});
}
void UpdateWorker::setAutoDownloadUpdates(const bool& autoDownload)
{
m_updateInter->SetAutoDownloadUpdates(autoDownload);
if (autoDownload == false) {
m_updateInter->setAutoInstallUpdates(false);
}
}
void UpdateWorker::setIdleDownloadEnabled(bool enable)
{
auto config = m_model->idleDownloadConfig();
config.idleDownloadEnabled = enable;
setIdleDownloadConfig(config);
}
void UpdateWorker::setIdleDownloadBeginTime(QString time)
{
auto config = m_model->idleDownloadConfig();
config.beginTime = time;
config.endTime = adjustTimeFunc(config.beginTime, config.endTime, true);
setIdleDownloadConfig(config);
}
void UpdateWorker::setIdleDownloadEndTime(QString time)
{
auto config = m_model->idleDownloadConfig();
config.endTime = time;
config.beginTime = adjustTimeFunc(config.beginTime, config.endTime, false);
setIdleDownloadConfig(config);
}
void UpdateWorker::setIdleDownloadConfig(const IdleDownloadConfig& config)
{
// 避免dbus延时返回,导致界面更新慢,这里直接先更新model
m_model->setIdleDownloadConfig(config);
QDBusPendingCall call = m_updateInter->SetIdleDownloadConfig(QString(config.toJson()));
QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(call, this);
connect(watcher, &QDBusPendingCallWatcher::finished, this, [call, watcher] {
if (call.isError()) {
qCWarning(DCC_UPDATE_WORKER) << "Set idle download config error:" << call.error().message();
}
watcher->deleteLater();
});
}
// 规则:开始时间和结束时间不能相等,否则默认按相隔五分钟处理
// 修改开始时间时,如果不满足规则,那么自动调整结束时间,结束时间=开始时间+5分钟
// 修改结束时间时,如果不满足规则,那么自动调整开始时间,开始时间=结束时间-5分钟
QString UpdateWorker::adjustTimeFunc(const QString& start, const QString& end, bool returnEndTime)
{
if (start != end)
return returnEndTime ? end : start;
static const int MIN_INTERVAL_SECS = 5 * 60;
QDateTime dateTime(QDate::currentDate(), QTime::fromString(start));
return returnEndTime ? dateTime.addSecs(MIN_INTERVAL_SECS).time().toString("hh:mm")
: dateTime.addSecs(-MIN_INTERVAL_SECS).time().toString("hh:mm");
}
void UpdateWorker::setUpdateNotify(const bool notify)
{
m_updateInter->SetUpdateNotify(notify);
}
void UpdateWorker::setAutoCleanCache(const bool autoCleanCache)
{
m_updateInter->SetAutoClean(autoCleanCache);
}
void UpdateWorker::setSmartMirror(bool enable)
{
m_updateInter->SetEnable(enable);
}
void UpdateWorker::setMirrorSource(const MirrorInfo& mirror)
{
m_updateInter->SetMirrorSource(mirror.m_id);
}
void UpdateWorker::testMirrorSpeed()
{
QList<MirrorInfo> mirrors = m_model->mirrorInfos();
QStringList urlList;
for (MirrorInfo& info : mirrors) {
urlList << info.m_url;
}
// reset the data;
m_model->setMirrorSpeedInfo(QMap<QString, int>());
QFutureWatcher<int>* watcher = new QFutureWatcher<int>();
connect(watcher, &QFutureWatcher<int>::resultReadyAt, [this, urlList, watcher, mirrors](int index) {
QMap<QString, int> speedInfo = m_model->mirrorSpeedInfo();
int result = watcher->resultAt(index);
QString mirrorId = mirrors.at(index).m_id;
speedInfo[mirrorId] = result;
m_model->setMirrorSpeedInfo(speedInfo);
});
QPointer<QObject> guest(this);
QFuture<int> future = QtConcurrent::mapped(urlList, std::bind(TestMirrorSpeedInternal, std::placeholders::_1, guest));
watcher->setFuture(future);
}
void UpdateWorker::checkNetselect()
{
QProcess* process = new QProcess;
process->start("netselect", QStringList() << "127.0.0.1");
connect(process, &QProcess::errorOccurred, this, [this, process](QProcess::ProcessError error) {
if ((error == QProcess::FailedToStart) || (error == QProcess::Crashed)) {
m_model->setNetselectExist(false);
process->deleteLater();
}
});
connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, [this, process](int result) {
bool isNetselectExist = 0 == result;
if (!isNetselectExist) {
qCDebug(DCC_UPDATE_WORKER) << "Netselect 127.0.0.1 :" << isNetselectExist;
}
m_model->setNetselectExist(isNetselectExist);
process->deleteLater();
});
}
#ifndef DISABLE_SYS_UPDATE_MIRRORS
void UpdateWorker::refreshMirrors()
{
qCDebug(DCC_UPDATE_WORKER) << QDir::currentPath();
QFile file(":/update/themes/common/config/mirrors.json");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qCDebug(DCC_UPDATE_WORKER) << file.errorString();
return;
}
QJsonArray array = QJsonDocument::fromJson(file.readAll()).array();
QList<MirrorInfo> list;
for (auto item : array) {
QJsonObject obj = item.toObject();
MirrorInfo info;
info.m_id = obj.value("id").toString();
QString locale = QLocale::system().name();
if (!(QLocale::system().name() == "zh_CN" || QLocale::system().name() == "zh_TW")) {
locale = "zh_CN";
}
info.m_name = obj.value(QString("name_locale.%1").arg(locale)).toString();
info.m_url = obj.value("url").toString();
list << info;
}
m_model->setMirrorInfos(list);
m_model->setDefaultMirror(list[0].m_id);
}
#endif
void UpdateWorker::setTestingChannelEnable(const bool& enable)
{
qCDebug(DCC_UPDATE_WORKER) << "Testing:" << "setTestingChannelEnable" << enable;
if (enable) {
m_model->setTestingChannelStatus(TestingChannelStatus::WaitJoined);
} else {
m_model->setTestingChannelStatus(TestingChannelStatus::WaitToLeave);
}
auto machineidopt = getMachineId();
if (!machineidopt.has_value()) {
// INFO: 99lastore-token.conf is not generated, need wait for lastore to generating it, if
// it is not generated for a long time, please post a issue to lastore
qCWarning(DCC_UPDATE_WORKER)
<< "machineid need to read /etc/apt/apt.conf.d/99lastore-token.conf, the file is "
"generated by lastore. Maybe you need wait for the file to be generated.";
m_model->setTestingChannelStatus(TestingChannelStatus::NotJoined);
return;
}
// every time, clear the machineid in server
auto http = new QNetworkAccessManager(this);
QNetworkRequest request;
request.setUrl(QUrl(ServiceLink + "/api/v2/public/testing/machine/" + machineidopt.value()));
request.setRawHeader("content-type", "application/json");
QEventLoop loop;
connect(http, &QNetworkAccessManager::finished, this, [http, &loop](QNetworkReply *reply) {
reply->deleteLater();
http->deleteLater();