-
Notifications
You must be signed in to change notification settings - Fork 946
Expand file tree
/
Copy pathaccountsettings.cpp
More file actions
1745 lines (1488 loc) · 70.2 KB
/
accountsettings.cpp
File metadata and controls
1745 lines (1488 loc) · 70.2 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: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2014 ownCloud GmbH
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "accountsettings.h"
#include "common/syncjournaldb.h"
#include "common/syncjournalfilerecord.h"
#include "qmessagebox.h"
#include "ui_accountsettings.h"
#include "theme.h"
#include "foldercreationdialog.h"
#include "folderman.h"
#include "folderwizard.h"
#include "folderstatusmodel.h"
#include "folderstatusdelegate.h"
#include "common/utility.h"
#include "guiutility.h"
#include "application.h"
#include "configfile.h"
#include "account.h"
#include "accountstate.h"
#include "userinfo.h"
#include "accountmanager.h"
#include "owncloudsetupwizard.h"
#include "creds/abstractcredentials.h"
#include "creds/httpcredentialsgui.h"
#include "tooltipupdater.h"
#include "filesystem.h"
#include "encryptfolderjob.h"
#include "syncresult.h"
#include "ignorelisteditor.h"
#include "wizard/owncloudwizard.h"
#include "networksettings.h"
#include "ui_mnemonicdialog.h"
#include <cmath>
#include <QDesktopServices>
#include <QDialogButtonBox>
#include <QDir>
#include <QListWidgetItem>
#include <QMessageBox>
#include <QAction>
#include <QVBoxLayout>
#include <QTreeView>
#include <QKeySequence>
#include <QIcon>
#include <QVariant>
#include <QJsonDocument>
#include <QToolTip>
#ifdef BUILD_FILE_PROVIDER_MODULE
#include "macOS/fileprovider.h"
#endif
#include "account.h"
namespace {
constexpr auto propertyFolder = "folder";
constexpr auto propertyPath = "path";
constexpr auto e2eUiActionIdKey = "id";
constexpr auto e2EeUiActionSetupEncryptionId = "setup_encryption";
constexpr auto e2EeUiActionForgetEncryptionId = "forget_encryption";
constexpr auto e2EeUiActionDisplayMnemonicId = "display_mnemonic";
constexpr auto e2EeUiActionMigrateCertificateId = "migrate_certificate";
}
namespace OCC {
class AccountSettings;
Q_LOGGING_CATEGORY(lcAccountSettings, "nextcloud.gui.account.settings", QtInfoMsg)
static const char progressBarStyleC[] =
"QProgressBar {"
"border: 1px solid grey;"
"border-radius: 5px;"
"text-align: center;"
"}"
"QProgressBar::chunk {"
"background-color: %1; width: 1px;"
"}";
void showEnableE2eeWithVirtualFilesWarningDialog(std::function<void(void)> onAccept)
{
const auto messageBox = new QMessageBox;
messageBox->setAttribute(Qt::WA_DeleteOnClose);
messageBox->setText(AccountSettings::tr("End-to-end Encryption with Virtual Files"));
messageBox->setInformativeText(AccountSettings::tr("You seem to have the Virtual Files feature enabled on this folder. "
"At the moment, it is not possible to implicitly download virtual files that are "
"end-to-end encrypted. To get the best experience with virtual files and "
"end-to-end encryption, make sure the encrypted folder is marked with "
"\"Make always available locally\"."));
messageBox->setIcon(QMessageBox::Warning);
const auto dontEncryptButton = messageBox->addButton(QMessageBox::StandardButton::Cancel);
Q_ASSERT(dontEncryptButton);
dontEncryptButton->setText(AccountSettings::tr("Do not encrypt folder"));
const auto encryptButton = messageBox->addButton(QMessageBox::StandardButton::Ok);
Q_ASSERT(encryptButton);
encryptButton->setText(AccountSettings::tr("Encrypt folder"));
QObject::connect(messageBox, &QMessageBox::accepted, onAccept);
messageBox->open();
}
void showEnableE2eeWarningDialog(std::function<void(void)> onAccept)
{
const auto messageBox = new QMessageBox;
messageBox->setAttribute(Qt::WA_DeleteOnClose);
messageBox->setText(AccountSettings::tr("End-to-end Encryption"));
messageBox->setTextFormat(Qt::RichText);
messageBox->setInformativeText(
AccountSettings::tr("This will encrypt your folder and all files within it. "
"These files will no longer be accessible without your encryption mnemonic key. "
"\n<b>This process is not reversible. Are you sure you want to proceed?</b>"));
messageBox->setIcon(QMessageBox::Warning);
const auto dontEncryptButton = messageBox->addButton(QMessageBox::StandardButton::Cancel);
Q_ASSERT(dontEncryptButton);
dontEncryptButton->setText(AccountSettings::tr("Do not encrypt folder"));
const auto encryptButton = messageBox->addButton(QMessageBox::StandardButton::Ok);
Q_ASSERT(encryptButton);
encryptButton->setText(AccountSettings::tr("Encrypt folder"));
QObject::connect(messageBox, &QMessageBox::accepted, onAccept);
messageBox->open();
}
/**
* Adjusts the mouse cursor based on the region it is on over the folder tree view.
*
* Used to show that one can click the red error list box by changing the cursor
* to the pointing hand.
*/
class MouseCursorChanger : public QObject
{
Q_OBJECT
public:
MouseCursorChanger(QObject *parent)
: QObject(parent)
{
}
QTreeView *folderList = nullptr;
FolderStatusModel *model = nullptr;
protected:
bool eventFilter(QObject *watched, QEvent *event) override
{
if (event->type() == QEvent::HoverMove) {
Qt::CursorShape shape = Qt::ArrowCursor;
const auto pos = folderList->mapFromGlobal(QCursor::pos());
const auto index = folderList->indexAt(pos);
if (model->classify(index) == FolderStatusModel::RootFolder &&
(FolderStatusDelegate::errorsListRect(folderList->visualRect(index)).contains(pos) ||
FolderStatusDelegate::optionsButtonRect(folderList->visualRect(index),folderList->layoutDirection()).contains(pos))) {
shape = Qt::PointingHandCursor;
}
folderList->setCursor(shape);
}
return QObject::eventFilter(watched, event);
}
};
AccountSettings::AccountSettings(AccountState *accountState, QWidget *parent)
: QWidget(parent)
, _ui(new Ui::AccountSettings)
, _model(new FolderStatusModel)
, _accountState(accountState)
, _userInfo(accountState, false, true)
{
_ui->setupUi(this);
_model->setAccountState(_accountState);
_model->setParent(this);
const auto delegate = new FolderStatusDelegate;
delegate->setParent(this);
// Connect styleChanged events to our widgets, so they can adapt (Dark-/Light-Mode switching)
connect(this, &AccountSettings::styleChanged, delegate, &FolderStatusDelegate::slotStyleChanged);
_ui->_folderList->header()->hide();
_ui->_folderList->setItemDelegate(delegate);
_ui->_folderList->setModel(_model);
#if defined(Q_OS_MACOS)
_ui->_folderList->setMinimumWidth(400);
#else
_ui->_folderList->setMinimumWidth(300);
#endif
new ToolTipUpdater(_ui->_folderList);
#if defined(BUILD_FILE_PROVIDER_MODULE)
const auto fileProviderTab = _ui->fileProviderTab;
const auto fpSettingsLayout = new QVBoxLayout(fileProviderTab);
const auto fpAccountUserIdAtHost = _accountState->account()->userIdAtHostWithPort();
const auto fpSettingsController = Mac::FileProviderSettingsController::instance();
const auto fpSettingsWidget = fpSettingsController->settingsViewWidget(fpAccountUserIdAtHost, fileProviderTab);
fpSettingsLayout->setContentsMargins(0, 0, 0, 0);
fpSettingsLayout->addWidget(fpSettingsWidget);
fileProviderTab->setLayout(fpSettingsLayout);
#else
const auto tabWidget = _ui->tabWidget;
const auto fileProviderTab = _ui->fileProviderTab;
if (const auto fileProviderWidgetTabIndex = tabWidget->indexOf(fileProviderTab); fileProviderWidgetTabIndex >= 0) {
tabWidget->removeTab(fileProviderWidgetTabIndex);
}
tabWidget->setCurrentIndex(0);
#endif
const auto connectionSettingsTab = _ui->connectionSettingsTab;
const auto connectionSettingsLayout = new QVBoxLayout(connectionSettingsTab);
const auto networkSettings = new NetworkSettings(_accountState->account(), connectionSettingsTab);
connectionSettingsLayout->setContentsMargins(0, 0, 0, 0);
connectionSettingsLayout->addWidget(networkSettings);
connectionSettingsTab->setLayout(connectionSettingsLayout);
const auto mouseCursorChanger = new MouseCursorChanger(this);
mouseCursorChanger->folderList = _ui->_folderList;
mouseCursorChanger->model = _model;
_ui->_folderList->setMouseTracking(true);
_ui->_folderList->setAttribute(Qt::WA_Hover, true);
_ui->_folderList->installEventFilter(mouseCursorChanger);
connect(this, &AccountSettings::removeAccountFolders,
AccountManager::instance(), &AccountManager::removeAccountFolders);
connect(_ui->_folderList, &QWidget::customContextMenuRequested,
this, &AccountSettings::slotCustomContextMenuRequested);
connect(_ui->_folderList, &QAbstractItemView::clicked,
this, &AccountSettings::slotFolderListClicked);
connect(_ui->_folderList, &QTreeView::expanded, this, &AccountSettings::refreshSelectiveSyncStatus);
connect(_ui->_folderList, &QTreeView::collapsed, this, &AccountSettings::refreshSelectiveSyncStatus);
connect(_ui->selectiveSyncNotification, &QLabel::linkActivated,
this, &AccountSettings::slotLinkActivated);
connect(_model, &FolderStatusModel::suggestExpand, _ui->_folderList, &QTreeView::expand);
connect(_model, &FolderStatusModel::dirtyChanged, this, &AccountSettings::refreshSelectiveSyncStatus);
refreshSelectiveSyncStatus();
connect(_model, &QAbstractItemModel::rowsInserted,
this, &AccountSettings::refreshSelectiveSyncStatus);
auto *syncNowAction = new QAction(this);
syncNowAction->setShortcut(QKeySequence(Qt::Key_F6));
connect(syncNowAction, &QAction::triggered, this, &AccountSettings::slotScheduleCurrentFolder);
addAction(syncNowAction);
auto *syncNowWithRemoteDiscovery = new QAction(this);
syncNowWithRemoteDiscovery->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_F6));
connect(syncNowWithRemoteDiscovery, &QAction::triggered, this, &AccountSettings::slotScheduleCurrentFolderForceRemoteDiscovery);
addAction(syncNowWithRemoteDiscovery);
slotHideSelectiveSyncWidget();
_ui->bigFolderUi->setVisible(false);
connect(_model, &QAbstractItemModel::dataChanged, this, &AccountSettings::slotSelectiveSyncChanged);
connect(_ui->selectiveSyncApply, &QAbstractButton::clicked, this, &AccountSettings::slotHideSelectiveSyncWidget);
connect(_ui->selectiveSyncCancel, &QAbstractButton::clicked, this, &AccountSettings::slotHideSelectiveSyncWidget);
connect(_ui->selectiveSyncApply, &QAbstractButton::clicked, _model, &FolderStatusModel::slotApplySelectiveSync);
connect(_ui->selectiveSyncCancel, &QAbstractButton::clicked, _model, &FolderStatusModel::resetFolders);
connect(_ui->bigFolderApply, &QAbstractButton::clicked, _model, &FolderStatusModel::slotApplySelectiveSync);
connect(_ui->bigFolderSyncAll, &QAbstractButton::clicked, _model, &FolderStatusModel::slotSyncAllPendingBigFolders);
connect(_ui->bigFolderSyncNone, &QAbstractButton::clicked, _model, &FolderStatusModel::slotSyncNoPendingBigFolders);
connect(FolderMan::instance(), &FolderMan::folderListChanged, _model, &FolderStatusModel::resetFolders);
connect(this, &AccountSettings::folderChanged, _model, &FolderStatusModel::resetFolders);
// quotaProgressBar style now set in customizeStyle()
/*QColor color = palette().highlight().color();
_ui->quotaProgressBar->setStyleSheet(QString::fromLatin1(progressBarStyleC).arg(color.name()));*/
// Connect E2E stuff
if (_accountState->isConnected()) {
setupE2eEncryption();
} else {
_ui->encryptionMessage->setText(tr("End-to-end encryption has not been initialized on this account."));
}
_ui->encryptionMessage->setCloseButtonVisible(false);
_ui->connectLabel->setText(tr("No account configured."));
connect(_accountState, &AccountState::stateChanged, this, &AccountSettings::slotAccountStateChanged);
slotAccountStateChanged();
connect(&_userInfo, &UserInfo::quotaUpdated,
this, &AccountSettings::slotUpdateQuota);
customizeStyle();
connect(_accountState->account()->e2e(), &ClientSideEncryption::startingDiscoveryEncryptionUsbToken,
Systray::instance(), &Systray::createEncryptionTokenDiscoveryDialog);
connect(_accountState->account()->e2e(), &ClientSideEncryption::finishedDiscoveryEncryptionUsbToken,
Systray::instance(), &Systray::destroyEncryptionTokenDiscoveryDialog);
}
void AccountSettings::slotE2eEncryptionMnemonicReady()
{
const auto actionDisableEncryption = addActionToEncryptionMessage(tr("Forget encryption setup"), e2EeUiActionForgetEncryptionId);
connect(actionDisableEncryption, &QAction::triggered, this, [this] {
forgetEncryptionOnDeviceForAccount(_accountState->account());
});
if (_accountState->account()->e2e()->userCertificateNeedsMigration()) {
slotE2eEncryptionCertificateNeedMigration();
}
if (!_accountState->account()->e2e()->getMnemonic().isEmpty()) {
const auto actionDisplayMnemonic = addActionToEncryptionMessage(tr("Display mnemonic"), e2EeUiActionDisplayMnemonicId);
connect(actionDisplayMnemonic, &QAction::triggered, this, [this]() {
displayMnemonic(_accountState->account()->e2e()->getMnemonic());
});
}
_ui->encryptionMessage->setMessageType(KMessageWidget::Positive);
_ui->encryptionMessage->setText(tr("Encryption is set-up. Remember to <b>Encrypt</b> a folder to end-to-end encrypt any new files added to it."));
_ui->encryptionMessage->setIcon(Theme::createColorAwareIcon(QStringLiteral(":/client/theme/lock.svg")));
_ui->encryptionMessage->show();
}
void AccountSettings::slotE2eEncryptionGenerateKeys()
{
connect(_accountState->account()->e2e(), &ClientSideEncryption::initializationFinished, this, &AccountSettings::slotE2eEncryptionInitializationFinished);
_accountState->account()->setE2eEncryptionKeysGenerationAllowed(true);
_accountState->account()->setAskUserForMnemonic(true);
_accountState->account()->e2e()->initialize(this);
}
void AccountSettings::slotE2eEncryptionInitializationFinished(bool isNewMnemonicGenerated)
{
disconnect(_accountState->account()->e2e(), &ClientSideEncryption::initializationFinished, this, &AccountSettings::slotE2eEncryptionInitializationFinished);
if (_accountState->account()->e2e()->isInitialized()) {
removeActionFromEncryptionMessage(e2EeUiActionSetupEncryptionId);
slotE2eEncryptionMnemonicReady();
if (isNewMnemonicGenerated) {
displayMnemonic(_accountState->account()->e2e()->getMnemonic());
}
Q_EMIT _accountState->account()->wantsFoldersSynced();
}
_accountState->account()->setAskUserForMnemonic(false);
}
void AccountSettings::slotEncryptFolderFinished(int status)
{
qCInfo(lcAccountSettings) << "Current folder encryption status code:" << status;
auto job = qobject_cast<EncryptFolderJob*>(sender());
Q_ASSERT(job);
if (!job->errorString().isEmpty()) {
QMessageBox::warning(nullptr, tr("Warning"), job->errorString());
}
const auto folder = job->property(propertyFolder).value<Folder *>();
Q_ASSERT(folder);
const auto path = job->property(propertyPath).toString();
const auto index = _model->indexForPath(folder, path);
Q_ASSERT(index.isValid());
_model->resetAndFetch(index.parent());
job->deleteLater();
}
QString AccountSettings::selectedFolderAlias() const
{
const auto selected = _ui->_folderList->selectionModel()->currentIndex();
if (!selected.isValid()) {
return "";
}
return _model->data(selected, FolderStatusDelegate::FolderAliasRole).toString();
}
void AccountSettings::slotToggleSignInState()
{
if (_accountState->isSignedOut()) {
_accountState->account()->resetRejectedCertificates();
_accountState->signIn();
} else {
_accountState->signOutByUi();
}
}
void AccountSettings::doExpand()
{
// Make sure at least the root items are expanded
for (int i = 0; i < _model->rowCount(); ++i) {
const auto idx = _model->index(i);
if (!_ui->_folderList->isExpanded(idx)) {
_ui->_folderList->setExpanded(idx, true);
}
}
}
bool AccountSettings::canEncryptOrDecrypt(const FolderStatusModel::SubFolderInfo *info)
{
if (const auto folderSyncStatus = info->_folder->syncResult().status(); info->_fileId.isEmpty()) {
auto message = tr("Please wait for the folder to sync before trying to encrypt it.");
if (folderSyncStatus == SyncResult::Status::Problem) {
message = tr("The folder has a minor sync problem. Encryption of this folder will be possible once it has synced successfully");
} else if (folderSyncStatus == SyncResult::Status::Error) {
message = tr("The folder has a sync error. Encryption of this folder will be possible once it has synced successfully");
}
QMessageBox msgBox;
msgBox.setText(message);
msgBox.exec();
return false;
}
if (!_accountState->account()->e2e() || !_accountState->account()->e2e()->isInitialized()) {
QMessageBox msgBox;
msgBox.setText(tr("You cannot encrypt this folder because the end-to-end encryption is not set-up yet on this device.\n"
"Would you like to do this now?"));
msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Ok);
const auto ret = msgBox.exec();
switch (ret) {
case QMessageBox::Ok:
slotE2eEncryptionGenerateKeys();
break;
case QMessageBox::Cancel:
default:
break;
}
return false;
}
// for some reason the actual folder in disk is info->_folder->path + info->_path.
QDir folderPath(info->_folder->path() + info->_path);
folderPath.setFilter( QDir::AllEntries | QDir::NoDotAndDotDot );
if (folderPath.count() != 0) {
QMessageBox msgBox;
msgBox.setText(tr("You cannot encrypt a folder with contents, please remove the files.\n"
"Wait for the new sync, then encrypt it."));
msgBox.exec();
return false;
}
return true;
}
void AccountSettings::slotMarkSubfolderEncrypted(FolderStatusModel::SubFolderInfo* folderInfo)
{
if (!canEncryptOrDecrypt(folderInfo)) {
return;
}
const auto folder = folderInfo->_folder;
Q_ASSERT(folder);
const auto folderAlias = folder->alias();
const auto path = folderInfo->_path;
const auto fileId = folderInfo->_fileId;
const auto encryptFolder = [this, fileId, path, folderAlias] {
const auto folder = FolderMan::instance()->folder(folderAlias);
if (!folder) {
qCWarning(lcAccountSettings) << "Could not encrypt folder because folder" << folderAlias << "does not exist anymore";
QMessageBox::warning(nullptr, tr("Encryption failed"), tr("Could not encrypt folder because the folder does not exist anymore"));
return;
}
// Folder info have directory paths in Foo/Bar/ convention...
Q_ASSERT(!path.startsWith('/') && path.endsWith('/'));
// But EncryptFolderJob expects directory path Foo/Bar convention
const auto choppedPath = path.chopped(1);
auto job = new OCC::EncryptFolderJob(accountsState()->account(), folder->journalDb(), choppedPath, choppedPath, folder->remotePath(), fileId);
job->setParent(this);
job->setProperty(propertyFolder, QVariant::fromValue(folder));
job->setProperty(propertyPath, QVariant::fromValue(path));
connect(job, &OCC::EncryptFolderJob::finished, this, &AccountSettings::slotEncryptFolderFinished);
job->start();
};
if (folder->virtualFilesEnabled() && folder->vfs().mode() == Vfs::WindowsCfApi) {
showEnableE2eeWithVirtualFilesWarningDialog(encryptFolder);
return;
}
showEnableE2eeWarningDialog(encryptFolder);
}
void AccountSettings::slotEditCurrentIgnoredFiles()
{
const auto folder = FolderMan::instance()->folder(selectedFolderAlias());
if (!folder) {
return;
}
openIgnoredFilesDialog(folder->path());
}
void AccountSettings::slotOpenMakeFolderDialog()
{
const auto selected = _ui->_folderList->selectionModel()->currentIndex();
if (!selected.isValid()) {
qCWarning(lcAccountSettings) << "Selection model current folder index is not valid.";
return;
}
const auto classification = _model->classify(selected);
if (classification != FolderStatusModel::SubFolder && classification != FolderStatusModel::RootFolder) {
return;
}
const auto folder = _model->infoForIndex(selected)->_folder;
Q_ASSERT(folder);
const auto fileName = [selected, classification, folder, this] {
QString result;
if (classification == FolderStatusModel::RootFolder) {
result = folder->path();
} else {
result = _model->data(selected, FolderStatusDelegate::FolderPathRole).toString();
}
if (result.endsWith('/')) {
result.chop(1);
}
return result;
}();
if (!fileName.isEmpty()) {
const auto folderCreationDialog = new FolderCreationDialog(fileName, this);
folderCreationDialog->setAttribute(Qt::WA_DeleteOnClose);
folderCreationDialog->open();
#ifdef Q_OS_MACOS
// The macOS FolderWatcher cannot detect file and folder changes made by the watching process -- us.
// So we need to manually invoke the slot that is called by watched folder changes.
connect(folderCreationDialog, &FolderCreationDialog::folderCreated, this, [folder, fileName](const QString &fullFolderPath) {
folder->slotWatchedPathChanged(fullFolderPath, Folder::ChangeReason::Other);
});
#endif
}
}
void AccountSettings::slotEditCurrentLocalIgnoredFiles()
{
const auto selected = _ui->_folderList->selectionModel()->currentIndex();
if (!selected.isValid() || _model->classify(selected) != FolderStatusModel::SubFolder) {
return;
}
const auto fileName = _model->data(selected, FolderStatusDelegate::FolderPathRole).toString();
openIgnoredFilesDialog(fileName);
}
void AccountSettings::openIgnoredFilesDialog(const QString & absFolderPath)
{
Q_ASSERT(QFileInfo(absFolderPath).isAbsolute());
const QString ignoreFile{absFolderPath + ".sync-exclude.lst"};
auto ignoreListEditor = new IgnoreListEditor(ignoreFile, this);
ignoreListEditor->setAttribute(Qt::WA_DeleteOnClose);
ignoreListEditor->open();
}
void AccountSettings::slotSubfolderContextMenuRequested(const QModelIndex& index, const QPoint& pos)
{
Q_UNUSED(pos);
QMenu menu;
auto ac = menu.addAction(tr("Open folder"));
connect(ac, &QAction::triggered, this, &AccountSettings::slotOpenCurrentLocalSubFolder);
const auto fileName = _model->data(index, FolderStatusDelegate::FolderPathRole).toString();
if (!QFile::exists(fileName)) {
ac->setEnabled(false);
}
const auto info = _model->infoForIndex(index);
const auto acc = _accountState->account();
if (acc->capabilities().clientSideEncryptionAvailable()) {
// Verify if the folder is empty before attempting to encrypt.
const auto isEncrypted = info->isEncrypted();
const auto isParentEncrypted = _model->isAnyAncestorEncrypted(index);
const auto isTopFolder = index.parent().isValid() && !index.parent().parent().isValid();
const auto isExternal = info->_isExternal;
if (!isEncrypted && !isParentEncrypted && !isExternal && isTopFolder) {
ac = menu.addAction(tr("Encrypt"));
connect(ac, &QAction::triggered, [this, info] { slotMarkSubfolderEncrypted(info); });
} else {
// Ignore decrypting for now since it only works with an empty folder
// connect(ac, &QAction::triggered, [this, &info] { slotMarkSubfolderDecrypted(info); });
}
}
ac = menu.addAction(tr("Edit Ignored Files"));
connect(ac, &QAction::triggered, this, &AccountSettings::slotEditCurrentLocalIgnoredFiles);
ac = menu.addAction(tr("Create new folder"));
connect(ac, &QAction::triggered, this, &AccountSettings::slotOpenMakeFolderDialog);
ac->setEnabled(QFile::exists(fileName));
const auto folder = info->_folder;
if (folder && folder->virtualFilesEnabled()) {
auto availabilityMenu = menu.addMenu(tr("Availability"));
// Has '/' suffix convention for paths here but VFS and
// sync engine expects no such suffix
Q_ASSERT(info->_path.endsWith('/'));
const auto remotePath = info->_path.chopped(1);
// It might be an E2EE mangled path, so let's try to demangle it
const auto journal = folder->journalDb();
SyncJournalFileRecord rec;
if (!journal->getFileRecordByE2eMangledName(remotePath, &rec)) {
qCWarning(lcFolderStatus) << "Could not get file record by E2E Mangled Name from local DB" << remotePath;
}
const auto path = rec.isValid() ? rec._path : remotePath;
ac = availabilityMenu->addAction(Utility::vfsPinActionText());
connect(ac, &QAction::triggered, this, [this, folder, path] { slotSetSubFolderAvailability(folder, path, PinState::AlwaysLocal); });
ac = availabilityMenu->addAction(Utility::vfsFreeSpaceActionText());
connect(ac, &QAction::triggered, this, [this, folder, path] { slotSetSubFolderAvailability(folder, path, PinState::OnlineOnly); });
}
menu.exec(QCursor::pos());
}
void AccountSettings::slotCustomContextMenuRequested(const QPoint &pos)
{
const auto treeView = _ui->_folderList;
const auto index = treeView->indexAt(pos);
if (!index.isValid()) {
return;
}
if (_model->classify(index) == FolderStatusModel::SubFolder) {
slotSubfolderContextMenuRequested(index, pos);
return;
}
if (_model->classify(index) != FolderStatusModel::RootFolder) {
return;
}
treeView->setCurrentIndex(index);
const auto alias = _model->data(index, FolderStatusDelegate::FolderAliasRole).toString();
const auto folderPaused = _model->data(index, FolderStatusDelegate::FolderSyncPaused).toBool();
const auto folderConnected = _model->data(index, FolderStatusDelegate::FolderAccountConnected).toBool();
const auto folderMan = FolderMan::instance();
const auto folder = folderMan->folder(alias);
if (!folder) {
return;
}
const auto menu = new QMenu(treeView);
menu->setAttribute(Qt::WA_DeleteOnClose);
auto ac = menu->addAction(tr("Open folder"));
connect(ac, &QAction::triggered, this, &AccountSettings::slotOpenCurrentFolder);
ac = menu->addAction(tr("Edit Ignored Files"));
connect(ac, &QAction::triggered, this, &AccountSettings::slotEditCurrentIgnoredFiles);
ac = menu->addAction(tr("Create new folder"));
connect(ac, &QAction::triggered, this, &AccountSettings::slotOpenMakeFolderDialog);
ac->setEnabled(QFile::exists(folder->path()));
if (!_ui->_folderList->isExpanded(index) && folder->supportsSelectiveSync()) {
ac = menu->addAction(tr("Choose what to sync"));
ac->setEnabled(folderConnected);
connect(ac, &QAction::triggered, this, &AccountSettings::doExpand);
}
if (!folderPaused) {
ac = menu->addAction(tr("Force sync now"));
if (folder && folder->isSyncRunning()) {
ac->setText(tr("Restart sync"));
}
ac->setEnabled(folderConnected);
connect(ac, &QAction::triggered, this, &AccountSettings::slotForceSyncCurrentFolder);
}
ac = menu->addAction(folderPaused ? tr("Resume sync") : tr("Pause sync"));
connect(ac, &QAction::triggered, this, &AccountSettings::slotEnableCurrentFolder);
ac = menu->addAction(tr("Remove folder sync connection"));
connect(ac, &QAction::triggered, this, &AccountSettings::slotRemoveCurrentFolder);
if (folder->virtualFilesEnabled()) {
auto availabilityMenu = menu->addMenu(tr("Availability"));
ac = availabilityMenu->addAction(Utility::vfsPinActionText());
connect(ac, &QAction::triggered, this, [this]() { slotSetCurrentFolderAvailability(PinState::AlwaysLocal); });
ac->setDisabled(Theme::instance()->enforceVirtualFilesSyncFolder());
ac = availabilityMenu->addAction(Utility::vfsFreeSpaceActionText());
connect(ac, &QAction::triggered, this, [this]() { slotSetCurrentFolderAvailability(PinState::OnlineOnly); });
ac = menu->addAction(tr("Disable virtual file support …"));
connect(ac, &QAction::triggered, this, &AccountSettings::slotDisableVfsCurrentFolder);
ac->setDisabled(Theme::instance()->enforceVirtualFilesSyncFolder());
}
if (const auto mode = bestAvailableVfsMode();
!Theme::instance()->disableVirtualFilesSyncFolder() &&
Theme::instance()->showVirtualFilesOption() && !folder->virtualFilesEnabled() && Vfs::checkAvailability(folder->path(), mode)) {
if (mode == Vfs::WindowsCfApi || ConfigFile().showExperimentalOptions()) {
ac = menu->addAction(tr("Enable virtual file support %1 …").arg(mode == Vfs::WindowsCfApi ? QString() : tr("(experimental)")));
// TODO: remove when UX decision is made
ac->setEnabled(!Utility::isPathWindowsDrivePartitionRoot(folder->path()));
//
connect(ac, &QAction::triggered, this, &AccountSettings::slotEnableVfsCurrentFolder);
}
}
menu->popup(treeView->mapToGlobal(pos));
}
void AccountSettings::slotFolderListClicked(const QModelIndex &indx)
{
if (indx.data(FolderStatusDelegate::AddButton).toBool()) {
// "Add Folder Sync Connection"
const auto treeView = _ui->_folderList;
const auto pos = treeView->mapFromGlobal(QCursor::pos());
QStyleOptionViewItem opt;
opt.initFrom(treeView);
const auto btnRect = treeView->visualRect(indx);
const auto btnSize = treeView->itemDelegateForIndex(indx)->sizeHint(opt, indx);
const auto actual = QStyle::visualRect(opt.direction, btnRect, QRect(btnRect.topLeft(), btnSize));
if (!actual.contains(pos)) {
return;
}
if (indx.flags() & Qt::ItemIsEnabled) {
slotAddFolder();
} else {
QToolTip::showText(
QCursor::pos(),
_model->data(indx, Qt::ToolTipRole).toString(),
this);
}
return;
}
if (_model->classify(indx) == FolderStatusModel::RootFolder) {
// tries to find if we clicked on the '...' button.
const auto treeView = _ui->_folderList;
const auto pos = treeView->mapFromGlobal(QCursor::pos());
if (FolderStatusDelegate::optionsButtonRect(treeView->visualRect(indx), layoutDirection()).contains(pos)) {
slotCustomContextMenuRequested(pos);
return;
}
if (FolderStatusDelegate::errorsListRect(treeView->visualRect(indx)).contains(pos)) {
emit showIssuesList(_accountState);
return;
}
// Expand root items on single click
if (_accountState && _accountState->state() == AccountState::Connected) {
const auto expanded = !(_ui->_folderList->isExpanded(indx));
_ui->_folderList->setExpanded(indx, expanded);
}
}
}
void AccountSettings::slotAddFolder()
{
const auto folderMan = FolderMan::instance();
folderMan->setSyncEnabled(false); // do not start more syncs.
const auto folderWizard = new FolderWizard(_accountState->account(), this);
folderWizard->setAttribute(Qt::WA_DeleteOnClose);
connect(folderWizard, &QDialog::accepted, this, &AccountSettings::slotFolderWizardAccepted);
connect(folderWizard, &QDialog::rejected, this, &AccountSettings::slotFolderWizardRejected);
folderWizard->open();
}
void AccountSettings::slotFolderWizardAccepted()
{
const auto folderWizard = qobject_cast<FolderWizard *>(sender());
const auto folderMan = FolderMan::instance();
qCInfo(lcAccountSettings) << "Folder wizard completed";
FolderDefinition definition;
definition.localPath = FolderDefinition::prepareLocalPath(
folderWizard->field(QLatin1String("sourceFolder")).toString());
definition.targetPath = FolderDefinition::prepareTargetPath(
folderWizard->property("targetPath").toString());
if (folderWizard->property("useVirtualFiles").toBool()) {
definition.virtualFilesMode = bestAvailableVfsMode();
}
{
QDir dir(definition.localPath);
if (!dir.exists()) {
qCInfo(lcAccountSettings) << "Creating folder" << definition.localPath;
if (!dir.mkpath(".")) {
QMessageBox::warning(this, tr("Folder creation failed"),
tr("<p>Could not create local folder <i>%1</i>.</p>")
.arg(Utility::escape(QDir::toNativeSeparators(definition.localPath))));
return;
}
}
FileSystem::setFolderMinimumPermissions(definition.localPath);
Utility::setupFavLink(definition.localPath);
}
/* take the value from the definition of already existing folders. All folders have
* the same setting so far.
* The default is to sync hidden files
*/
definition.ignoreHiddenFiles = folderMan->ignoreHiddenFiles();
#ifdef Q_OS_WIN
if (folderMan->navigationPaneHelper().showInExplorerNavigationPane()) {
definition.navigationPaneClsid = QUuid::createUuid();
}
#endif
const auto selectiveSyncBlackList = folderWizard->property("selectiveSyncBlackList").toStringList();
folderMan->setSyncEnabled(true);
const auto folder = folderMan->addFolder(_accountState, definition);
if (folder) {
if (definition.virtualFilesMode != Vfs::Off && folderWizard->property("useVirtualFiles").toBool()) {
folder->setRootPinState(PinState::OnlineOnly);
}
folder->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, selectiveSyncBlackList);
// The user already accepted the selective sync dialog. everything is in the white list
folder->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList,
QStringList() << QLatin1String("/"));
folderMan->scheduleAllFolders();
emit folderChanged();
}
}
void AccountSettings::slotFolderWizardRejected()
{
qCInfo(lcAccountSettings) << "Folder wizard cancelled";
const auto folderMan = FolderMan::instance();
folderMan->setSyncEnabled(true);
}
void AccountSettings::slotRemoveCurrentFolder()
{
const auto folder = FolderMan::instance()->folder(selectedFolderAlias());
const auto selected = _ui->_folderList->selectionModel()->currentIndex();
if (selected.isValid() && folder) {
const auto row = selected.row();
qCInfo(lcAccountSettings) << "Remove Folder alias " << folder->alias();
const auto shortGuiLocalPath = folder->shortGuiLocalPath();
auto messageBox = new QMessageBox(QMessageBox::Question,
tr("Confirm Folder Sync Connection Removal"),
tr("<p>Do you really want to stop syncing the folder <i>%1</i>?</p>"
"<p><b>Note:</b> This will <b>not</b> delete any files.</p>")
.arg(shortGuiLocalPath),
QMessageBox::NoButton,
this);
messageBox->setAttribute(Qt::WA_DeleteOnClose);
const auto yesButton = messageBox->addButton(tr("Remove Folder Sync Connection"), QMessageBox::YesRole);
messageBox->addButton(tr("Cancel"), QMessageBox::NoRole);
connect(messageBox, &QMessageBox::finished, this, [messageBox, yesButton, folder, row, this]{
if (messageBox->clickedButton() == yesButton) {
FolderMan::instance()->removeFolder(folder);
_model->removeRow(row);
// single folder fix to show add-button and hide remove-button
emit folderChanged();
}
});
messageBox->open();
}
}
void AccountSettings::slotOpenCurrentFolder()
{
const auto alias = selectedFolderAlias();
if (!alias.isEmpty()) {
emit openFolderAlias(alias);
}
}
void AccountSettings::slotOpenCurrentLocalSubFolder()
{
const auto selected = _ui->_folderList->selectionModel()->currentIndex();
if (!selected.isValid() || _model->classify(selected) != FolderStatusModel::SubFolder) {
return;
}
const auto fileName = _model->data(selected, FolderStatusDelegate::FolderPathRole).toString();
const auto url = QUrl::fromLocalFile(fileName);
QDesktopServices::openUrl(url);
}
void AccountSettings::slotEnableVfsCurrentFolder()
{
const auto folderMan = FolderMan::instance();
const auto folder = folderMan->folder(selectedFolderAlias());
const auto selected = _ui->_folderList->selectionModel()->currentIndex();
if (!selected.isValid() || !folder) {
return;
}
OwncloudWizard::askExperimentalVirtualFilesFeature(this, [folder, this](bool enable) {
if (!enable || !folder) {
return;
}
#ifdef Q_OS_WIN
// we might need to add or remove the panel entry as cfapi brings this feature out of the box
FolderMan::instance()->navigationPaneHelper().scheduleUpdateCloudStorageRegistry();
#endif
// It is unsafe to switch on vfs while a sync is running - wait if necessary.
const auto connection = std::make_shared<QMetaObject::Connection>();
const auto switchVfsOn = [folder, connection, this]() {
if (*connection) {
QObject::disconnect(*connection);
}
qCInfo(lcAccountSettings) << "Enabling vfs support for folder" << folder->path();
// Wipe selective sync blacklist
auto ok = false;
const auto oldBlacklist = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok);
folder->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, {});
// Change the folder vfs mode and load the plugin
folder->setVirtualFilesEnabled(true);
folder->setVfsOnOffSwitchPending(false);
// Setting to Unspecified retains existing data.
// Selective sync excluded folders become OnlineOnly.
folder->setRootPinState(PinState::Unspecified);
for (const auto &entry : oldBlacklist) {
folder->journalDb()->schedulePathForRemoteDiscovery(entry);
if (FileSystem::fileExists(entry) && !folder->vfs().setPinState(entry, PinState::OnlineOnly)) {
qCWarning(lcAccountSettings) << "Could not set pin state of" << entry << "to online only";
}
}
folder->slotNextSyncFullLocalDiscovery();
FolderMan::instance()->scheduleFolder(folder);
_ui->_folderList->doItemsLayout();
_ui->selectiveSyncStatus->setVisible(false);
};
if (folder->isSyncRunning()) {
*connection = connect(folder, &Folder::syncFinished, this, switchVfsOn);
folder->setVfsOnOffSwitchPending(true);
folder->slotTerminateSync();
_ui->_folderList->doItemsLayout();
} else {
switchVfsOn();
}
});
}
void AccountSettings::slotDisableVfsCurrentFolder()
{
const auto folderMan = FolderMan::instance();
const auto folder = folderMan->folder(selectedFolderAlias());
const auto selected = _ui->_folderList->selectionModel()->currentIndex();
if (!selected.isValid() || !folder) {
return;
}
const auto msgBox = new QMessageBox(
QMessageBox::Question,
tr("Disable virtual file support?"),
tr("This action will disable virtual file support. As a consequence contents of folders that "
"are currently marked as \"available online only\" will be downloaded."
"\n\n"
"The only advantage of disabling virtual file support is that the selective sync feature "
"will become available again."
"\n\n"
"This action will abort any currently running synchronization."));
const auto acceptButton = msgBox->addButton(tr("Disable support"), QMessageBox::AcceptRole);
msgBox->addButton(tr("Cancel"), QMessageBox::RejectRole);
connect(msgBox, &QMessageBox::finished, msgBox, [this, msgBox, folder, acceptButton] {
msgBox->deleteLater();
if (msgBox->clickedButton() != acceptButton|| !folder) {
return;
}
#ifdef Q_OS_WIN
// we might need to add or remove the panel entry as cfapi brings this feature out of the box
FolderMan::instance()->navigationPaneHelper().scheduleUpdateCloudStorageRegistry();