-
Notifications
You must be signed in to change notification settings - Fork 947
Expand file tree
/
Copy pathfolderman.cpp
More file actions
2277 lines (1947 loc) · 82.4 KB
/
folderman.cpp
File metadata and controls
2277 lines (1947 loc) · 82.4 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 "folderman.h"
#include "configfile.h"
#include "folder.h"
#include "syncresult.h"
#include "theme.h"
#include "socketapi/socketapi.h"
#include "account.h"
#include "accountstate.h"
#include "accountmanager.h"
#include "filesystem.h"
#include "lockwatcher.h"
#include "common/asserts.h"
#include "gui/systray.h"
#include <pushnotifications.h>
#include <syncengine.h>
#include "updatee2eefolderusersmetadatajob.h"
#include "settings/migration.h"
#ifdef Q_OS_MACOS
#include <CoreServices/CoreServices.h>
#include "common/utility_mac_sandbox.h"
#ifdef BUILD_FILE_PROVIDER_MODULE
#include "macOS/fileprovider.h"
#endif
#endif
#include <QMessageBox>
#include <QtCore>
#include <QMutableSetIterator>
#include <QSet>
#include <QNetworkProxy>
namespace {
constexpr auto settingsAccountsC = "Accounts";
constexpr auto settingsFoldersC = "Folders";
constexpr auto settingsFoldersWithPlaceholdersC = "FoldersWithPlaceholders";
constexpr auto settingsVersionC = "version";
constexpr auto maxFoldersVersion = 1;
int numberOfSyncJournals(const QString &path)
{
return QDir(path).entryList({ QStringLiteral(".sync_*.db"), QStringLiteral("._sync_*.db") }, QDir::Hidden | QDir::Files).size();
}
}
namespace OCC {
Q_LOGGING_CATEGORY(lcFolderMan, "nextcloud.gui.folder.manager", QtInfoMsg)
FolderMan *FolderMan::_instance = nullptr;
FolderMan::FolderMan(QObject *parent)
: QObject(parent)
, _lockWatcher(new LockWatcher)
#ifdef Q_OS_WIN
, _navigationPaneHelper(this)
#endif
{
ASSERT(!_instance);
_instance = this;
_socketApi.reset(new SocketApi);
ConfigFile cfg;
std::chrono::milliseconds polltime = cfg.remotePollInterval();
qCInfo(lcFolderMan) << "setting remote poll timer interval to" << polltime.count() << "msec";
_etagPollTimer.setInterval(polltime.count());
QObject::connect(&_etagPollTimer, &QTimer::timeout, this, &FolderMan::slotEtagPollTimerTimeout);
_etagPollTimer.start();
_startScheduledSyncTimer.setSingleShot(true);
connect(&_startScheduledSyncTimer, &QTimer::timeout,
this, &FolderMan::slotStartScheduledFolderSync);
_timeScheduler.setInterval(5000);
_timeScheduler.setSingleShot(false);
connect(&_timeScheduler, &QTimer::timeout,
this, &FolderMan::slotScheduleFolderByTime);
_timeScheduler.start();
connect(AccountManager::instance(), &AccountManager::removeAccountFolders,
this, &FolderMan::slotRemoveFoldersForAccount);
connect(AccountManager::instance(), &AccountManager::accountSyncConnectionRemoved,
this, &FolderMan::slotAccountRemoved);
connect(_lockWatcher.data(), &LockWatcher::fileUnlocked,
this, &FolderMan::slotWatchedFileUnlocked);
connect(this, &FolderMan::folderListChanged, this, &FolderMan::slotSetupPushNotifications);
}
FolderMan *FolderMan::instance()
{
return _instance;
}
FolderMan::~FolderMan()
{
qDeleteAll(_folderMap);
_instance = nullptr;
}
const OCC::Folder::Map &FolderMan::map() const
{
return _folderMap;
}
void FolderMan::unloadFolder(Folder *f)
{
if (!f) {
return;
}
_socketApi->slotUnregisterPath(f->alias());
_folderMap.remove(f->alias());
disconnect(f, &Folder::syncStarted,
this, &FolderMan::slotFolderSyncStarted);
disconnect(f, &Folder::syncFinished,
this, &FolderMan::slotFolderSyncFinished);
disconnect(f, &Folder::syncStateChange,
this, &FolderMan::slotForwardFolderSyncStateChange);
disconnect(f, &Folder::syncPausedChanged,
this, &FolderMan::slotFolderSyncPaused);
disconnect(&f->syncEngine().syncFileStatusTracker(), &SyncFileStatusTracker::fileStatusChanged,
_socketApi.data(), &SocketApi::broadcastStatusPushMessage);
disconnect(f, &Folder::watchedFileChangedExternally,
&f->syncEngine().syncFileStatusTracker(), &SyncFileStatusTracker::slotPathTouched);
}
int FolderMan::unloadAndDeleteAllFolders()
{
int cnt = 0;
// clear the list of existing folders.
Folder::MapIterator i(_folderMap);
while (i.hasNext()) {
i.next();
Folder *f = i.value();
unloadFolder(f);
delete f;
cnt++;
}
ASSERT(_folderMap.isEmpty());
_lastSyncFolder = nullptr;
_currentSyncFolder = nullptr;
_scheduledFolders.clear();
emit folderListChanged(_folderMap);
emit scheduleQueueChanged();
return cnt;
}
void FolderMan::registerFolderWithSocketApi(Folder *folder)
{
if (!folder)
return;
if (!QDir(folder->path()).exists())
return;
// register the folder with the socket API
if (folder->canSync())
_socketApi->slotRegisterPath(folder->alias());
}
int FolderMan::setupFolders()
{
Utility::registerUriHandlerForLocalEditing();
unloadAndDeleteAllFolders();
auto settings = ConfigFile::settingsWithGroup(QLatin1String("Accounts"));
const auto accountsWithSettings = settings->childGroups();
if (accountsWithSettings.isEmpty()) {
const auto migratedFoldersCount = setupFoldersMigration();
if (migratedFoldersCount > 0) {
AccountManager::instance()->save(false); // don't save credentials, they had not been loaded from keychain
}
return migratedFoldersCount;
}
qCInfo(lcFolderMan) << "Setup folders from settings file";
// this is done in Application::configVersionMigration
QStringList skipSettingsKeys;
backwardMigrationSettingsKeys(&skipSettingsKeys, &skipSettingsKeys);
const auto accounts = AccountManager::instance()->accounts();
for (const auto &account : accounts) {
const auto id = account->account()->id();
if (!accountsWithSettings.contains(id)) {
continue;
}
settings->beginGroup(id);
// The "backwardsCompatible" flag here is related to migrating old
// database locations
auto process = [&](const QString &groupName, const bool backwardsCompatible, const bool foldersWithPlaceholders) {
settings->beginGroup(groupName);
if (skipSettingsKeys.contains(settings->group())) {
// Should not happen: bad container keys should have been deleted
qCWarning(lcFolderMan) << "Folder structure" << groupName << "is too new, ignoring";
} else {
setupFoldersHelper(*settings, account, skipSettingsKeys, backwardsCompatible, foldersWithPlaceholders);
}
settings->endGroup();
};
process(QStringLiteral("Folders"), true, false);
// See Folder::saveToSettings for details about why these exists.
process(QStringLiteral("Multifolders"), false, false);
process(QStringLiteral("FoldersWithPlaceholders"), false, true);
settings->endGroup(); // <account>
}
emit folderListChanged(_folderMap);
for (const auto folder : std::as_const(_folderMap)) {
folder->processSwitchedToVirtualFiles();
}
return _folderMap.size();
}
void FolderMan::setupFoldersHelper(QSettings &settings, AccountStatePtr account, const QStringList &ignoreKeys, bool backwardsCompatible, bool foldersWithPlaceholders)
{
const auto settingsChildGroups = settings.childGroups();
for (const auto &folderAlias : settingsChildGroups) {
// Skip folders with too-new version
settings.beginGroup(folderAlias);
if (ignoreKeys.contains(settings.group())) {
qCInfo(lcFolderMan) << "Folder" << folderAlias << "is too new, ignoring";
_additionalBlockedFolderAliases.insert(folderAlias);
settings.endGroup();
continue;
}
settings.endGroup();
FolderDefinition folderDefinition;
settings.beginGroup(folderAlias);
if (FolderDefinition::load(settings, folderAlias, &folderDefinition)) {
#ifdef Q_OS_MACOS
// macOS sandbox: Resolve the persisted security-scoped bookmark and
// start accessing the resource BEFORE any filesystem operations on
// the local sync folder path. The access handle will be transferred
// to the Folder object once it is created via addFolderInternal().
std::unique_ptr<Utility::MacSandboxPersistentAccess> securityScopedAccess;
bool bookmarkRefreshed = false;
if (!folderDefinition.securityScopedBookmarkData.isEmpty()) {
securityScopedAccess = Utility::MacSandboxPersistentAccess::createFromBookmarkData(
folderDefinition.securityScopedBookmarkData);
if (!securityScopedAccess || !securityScopedAccess->isValid()) {
qCWarning(lcFolderMan) << "Failed to restore security-scoped access for folder"
<< folderAlias << "at" << folderDefinition.localPath;
// Ensure we don't propagate an invalid or failed access handle.
securityScopedAccess.reset();
} else if (securityScopedAccess->isStale()) {
// Bookmark still works but macOS flagged it as stale.
// Recreate it now while we have access so future launches
// won't run into problems. The updated data will be
// persisted when folder->saveToSettings() is called.
const auto refreshed = Utility::createSecurityScopedBookmarkData(folderDefinition.localPath);
if (!refreshed.isEmpty()) {
folderDefinition.securityScopedBookmarkData = refreshed;
bookmarkRefreshed = true;
qCInfo(lcFolderMan) << "Refreshed stale security-scoped bookmark for folder"
<< folderAlias;
}
}
} else {
qCDebug(lcFolderMan) << "No security-scoped bookmark data for folder"
<< folderAlias;
}
#endif
auto defaultJournalPath = folderDefinition.defaultJournalPath(account->account());
// Migration: Old settings don't have journalPath
if (folderDefinition.journalPath.isEmpty()) {
folderDefinition.journalPath = defaultJournalPath;
}
// Migration #2: journalPath might be absolute (in DataAppDir most likely) move it back to the root of local tree
if (folderDefinition.journalPath.at(0) != QChar('.')) {
QFile oldJournal(folderDefinition.journalPath);
QFile oldJournalShm(folderDefinition.journalPath + QStringLiteral("-shm"));
QFile oldJournalWal(folderDefinition.journalPath + QStringLiteral("-wal"));
folderDefinition.journalPath = defaultJournalPath;
socketApi()->slotUnregisterPath(folderAlias);
auto settings = account->settings();
auto journalFileMoveSuccess = true;
// Due to db logic can't be sure which of these file exist.
if (oldJournal.exists()) {
journalFileMoveSuccess &= oldJournal.rename(folderDefinition.localPath + "/" + folderDefinition.journalPath);
}
if (oldJournalShm.exists()) {
journalFileMoveSuccess &= oldJournalShm.rename(folderDefinition.localPath + "/" + folderDefinition.journalPath + QStringLiteral("-shm"));
}
if (oldJournalWal.exists()) {
journalFileMoveSuccess &= oldJournalWal.rename(folderDefinition.localPath + "/" + folderDefinition.journalPath + QStringLiteral("-wal"));
}
if (!journalFileMoveSuccess) {
qCWarning(lcFolderMan) << "Wasn't able to move 3.0 syncjournal database files to new location. One-time loss off sync settings possible.";
} else {
qCInfo(lcFolderMan) << "Successfully migrated syncjournal database.";
}
auto vfs = createVfsFromPlugin(folderDefinition.virtualFilesMode);
if (!vfs && folderDefinition.virtualFilesMode != Vfs::Off) {
qCWarning(lcFolderMan) << "Could not load plugin for mode" << folderDefinition.virtualFilesMode;
}
const auto folder = addFolderInternal(folderDefinition, account.data(), std::move(vfs));
#ifdef Q_OS_MACOS
if (securityScopedAccess) {
folder->setSecurityScopedAccess(std::move(securityScopedAccess));
}
#endif
folder->saveToSettings();
continue;
}
// Migration: ._ files sometimes can't be created.
// So if the configured journalPath has a dot-underscore ("._sync_*.db")
// but the current default doesn't have the underscore, switch to the
// new default if no db exists yet.
if (folderDefinition.journalPath.startsWith("._sync_")
&& defaultJournalPath.startsWith(".sync_")
&& !QFile::exists(folderDefinition.absoluteJournalPath())) {
folderDefinition.journalPath = defaultJournalPath;
}
// Migration: If an old db is found, move it to the new name.
if (backwardsCompatible) {
SyncJournalDb::maybeMigrateDb(folderDefinition.localPath, folderDefinition.absoluteJournalPath());
}
const auto switchToVfs = isSwitchToVfsNeeded(folderDefinition);
if (switchToVfs) {
folderDefinition.virtualFilesMode = bestAvailableVfsMode();
}
auto vfs = createVfsFromPlugin(folderDefinition.virtualFilesMode);
if (!vfs) {
// TODO: Must do better error handling
qFatal("Could not load plugin");
}
if (const auto folder = addFolderInternal(std::move(folderDefinition), account.data(), std::move(vfs))) {
#ifdef Q_OS_MACOS
if (securityScopedAccess) {
folder->setSecurityScopedAccess(std::move(securityScopedAccess));
}
if (bookmarkRefreshed) {
folder->saveToSettings();
}
#endif
if (switchToVfs) {
folder->switchToVirtualFiles();
}
// Migrate the old "usePlaceholders" setting to the root folder pin state
if (settings.value(QLatin1String(settingsVersionC), 1).toInt() == 1
&& settings.value(QLatin1String("usePlaceholders"), false).toBool()) {
qCInfo(lcFolderMan) << "Migrate: From usePlaceholders to PinState::OnlineOnly";
folder->setRootPinState(PinState::OnlineOnly);
}
// Migration: Mark folders that shall be saved in a backwards-compatible way
if (backwardsCompatible)
folder->setSaveBackwardsCompatible(true);
if (foldersWithPlaceholders)
folder->setSaveInFoldersWithPlaceholders();
scheduleFolder(folder);
emit folderSyncStateChange(folder);
}
}
settings.endGroup();
}
}
int FolderMan::setupFoldersMigration()
{
ConfigFile cfg;
QDir storageDir(cfg.configPath());
_folderConfigPath = cfg.configPath();
auto configPath = _folderConfigPath;
#if !DISABLE_ACCOUNT_MIGRATION
Migration migration;
if (const auto legacyConfigPath = migration.discoveredLegacyConfigPath(); !legacyConfigPath.isEmpty()) {
configPath = legacyConfigPath;
qCInfo(lcFolderMan) << "Starting folder migration from legacy path:" << legacyConfigPath;
}
#endif
qCInfo(lcFolderMan) << "Setup folders from" << configPath;
QDir dir(configPath);
// We need to include hidden files just in case the alias starts with '.'
dir.setFilter(QDir::Files | QDir::Hidden);
// Exclude previous backed up configs e.g. oc.cfg.backup_20230831_133749_4.0.0
// only need the current config in use by the legacy application
const auto dirFiles = dir.entryList({"*.cfg"});
// Migrate all folders for each account found in legacy config file(s)
const auto legacyAccounts = AccountManager::instance()->accounts();
for (const auto &fileName : dirFiles) {
for (const auto &accountState : legacyAccounts) {
const auto fullFilePath = dir.filePath(fileName);
setupLegacyFolder(fullFilePath, accountState.data());
}
}
emit folderListChanged(_folderMap);
// return the number of valid folders.
return _folderMap.size();
}
void FolderMan::backwardMigrationSettingsKeys(QStringList *deleteKeys, QStringList *ignoreKeys)
{
auto settings = ConfigFile::settingsWithGroup(QLatin1String("Accounts"));
auto processSubgroup = [&](const QString &name) {
settings->beginGroup(name);
const auto foldersVersion = settings->value(QLatin1String(settingsVersionC), 1).toInt();
qCInfo(lcFolderMan) << "FolderDefinition::maxSettingsVersion:" << FolderDefinition::maxSettingsVersion();
if (foldersVersion <= maxFoldersVersion) {
const auto &childGroups = settings->childGroups();
for (const auto &folderAlias : childGroups) {
settings->beginGroup(folderAlias);
const auto folderVersion = settings->value(QLatin1String(settingsVersionC), 1).toInt();
if (folderVersion > FolderDefinition::maxSettingsVersion()) {
qCInfo(lcFolderMan) << "Ignoring folder:" << folderAlias << "version:" << folderVersion;
ignoreKeys->append(settings->group());
}
settings->endGroup();
}
} else {
qCInfo(lcFolderMan) << "Ignoring group:" << name << "version:" << foldersVersion;
deleteKeys->append(settings->group());
}
settings->endGroup();
};
const auto settingsChildGroups = settings->childGroups();
for (const auto &accountId : settingsChildGroups) {
settings->beginGroup(accountId);
processSubgroup("Folders");
processSubgroup("Multifolders");
processSubgroup("FoldersWithPlaceholders");
settings->endGroup();
}
}
bool FolderMan::ensureJournalGone(const QString &journalDbFile)
{
// remove the old journal file
while (QFile::exists(journalDbFile) && !QFile::remove(journalDbFile)) {
qCWarning(lcFolderMan) << "Could not remove old db file at" << journalDbFile;
int ret = QMessageBox::warning(nullptr, tr("Could not reset folder state"),
tr("An old sync journal \"%1\" was found, "
"but could not be removed. Please make sure "
"that no application is currently using it.")
.arg(QDir::fromNativeSeparators(QDir::cleanPath(journalDbFile))),
QMessageBox::Retry | QMessageBox::Abort);
if (ret == QMessageBox::Abort) {
return false;
}
}
return true;
}
#define SLASH_TAG QLatin1String("__SLASH__")
#define BSLASH_TAG QLatin1String("__BSLASH__")
#define QMARK_TAG QLatin1String("__QMARK__")
#define PERCENT_TAG QLatin1String("__PERCENT__")
#define STAR_TAG QLatin1String("__STAR__")
#define COLON_TAG QLatin1String("__COLON__")
#define PIPE_TAG QLatin1String("__PIPE__")
#define QUOTE_TAG QLatin1String("__QUOTE__")
#define LT_TAG QLatin1String("__LESS_THAN__")
#define GT_TAG QLatin1String("__GREATER_THAN__")
#define PAR_O_TAG QLatin1String("__PAR_OPEN__")
#define PAR_C_TAG QLatin1String("__PAR_CLOSE__")
QString FolderMan::escapeAlias(const QString &alias)
{
QString a(alias);
a.replace(QLatin1Char('/'), SLASH_TAG);
a.replace(QLatin1Char('\\'), BSLASH_TAG);
a.replace(QLatin1Char('?'), QMARK_TAG);
a.replace(QLatin1Char('%'), PERCENT_TAG);
a.replace(QLatin1Char('*'), STAR_TAG);
a.replace(QLatin1Char(':'), COLON_TAG);
a.replace(QLatin1Char('|'), PIPE_TAG);
a.replace(QLatin1Char('"'), QUOTE_TAG);
a.replace(QLatin1Char('<'), LT_TAG);
a.replace(QLatin1Char('>'), GT_TAG);
a.replace(QLatin1Char('['), PAR_O_TAG);
a.replace(QLatin1Char(']'), PAR_C_TAG);
return a;
}
SocketApi *FolderMan::socketApi()
{
return this->_socketApi.data();
}
QString FolderMan::unescapeAlias(const QString &alias)
{
QString a(alias);
a.replace(SLASH_TAG, QLatin1String("/"));
a.replace(BSLASH_TAG, QLatin1String("\\"));
a.replace(QMARK_TAG, QLatin1String("?"));
a.replace(PERCENT_TAG, QLatin1String("%"));
a.replace(STAR_TAG, QLatin1String("*"));
a.replace(COLON_TAG, QLatin1String(":"));
a.replace(PIPE_TAG, QLatin1String("|"));
a.replace(QUOTE_TAG, QLatin1String("\""));
a.replace(LT_TAG, QLatin1String("<"));
a.replace(GT_TAG, QLatin1String(">"));
a.replace(PAR_O_TAG, QLatin1String("["));
a.replace(PAR_C_TAG, QLatin1String("]"));
return a;
}
void FolderMan::setupLegacyFolder(const QString &fileNamePath, AccountState *accountState)
{
qCInfo(lcFolderMan) << " ` -> setting up:" << fileNamePath;
QString escapedFileNamePath(fileNamePath);
// check the unescaped variant (for the case when the filename comes out
// of the directory listing). If the file does not exist, escape the
// file and try again.
QFileInfo cfgFile(fileNamePath);
if (!cfgFile.exists()) {
// try the escaped variant.
escapedFileNamePath = escapeAlias(fileNamePath);
cfgFile.setFile(_folderConfigPath, escapedFileNamePath);
}
if (!cfgFile.isReadable()) {
qCWarning(lcFolderMan) << "Cannot read folder definition for alias " << cfgFile.filePath();
return;
}
QSettings settings(escapedFileNamePath, QSettings::IniFormat);
qCInfo(lcFolderMan) << " -> file path: " << settings.fileName();
// Check if the filename is equal to the group setting. If not, use the group
// name as an alias.
const auto groups = settings.childGroups();
if (groups.isEmpty()) {
qCWarning(lcFolderMan) << "empty file:" << cfgFile.filePath();
return;
}
if (!accountState) {
qCCritical(lcFolderMan) << "can't create folder without an account";
return;
}
auto migrateFoldersGroup = [&](const QString &folderGroupName) {
const auto childGroups = settings.childGroups();
if (childGroups.isEmpty()) {
qCDebug(lcFolderMan) << "There are no" << folderGroupName << "to migrate from account" << accountState->account()->id();
return;
}
for (const auto &alias : childGroups) {
settings.beginGroup(alias);
qCDebug(lcFolderMan) << "try to migrate" << folderGroupName << "alias:" << alias;
const auto path = settings.value(QLatin1String("localPath")).toString();
const auto targetPath = settings.value(QLatin1String("targetPath")).toString();
const auto journalPath = settings.value(QLatin1String("journalPath")).toString();
const auto paused = settings.value(QLatin1String("paused"), false).toBool();
const auto ignoreHiddenFiles = settings.value(QLatin1String("ignoreHiddenFiles"), false).toBool();
const auto virtualFilesMode = settings.value(QLatin1String("virtualFilesMode"), false).toString();
if (path.isEmpty()) {
qCDebug(lcFolderMan) << "localPath is empty";
settings.endGroup();
continue;
}
if (targetPath.isEmpty()) {
qCDebug(lcFolderMan) << "targetPath is empty";
settings.endGroup();
continue;
}
if (journalPath.isEmpty()) {
qCDebug(lcFolderMan) << "journalPath is empty";
settings.endGroup();
continue;
}
qCDebug(lcFolderMan) << folderGroupName << "located at" << path;
FolderDefinition folderDefinition;
folderDefinition.alias = alias;
folderDefinition.localPath = path;
folderDefinition.targetPath = targetPath;
folderDefinition.journalPath = journalPath;
folderDefinition.paused = paused;
folderDefinition.ignoreHiddenFiles = ignoreHiddenFiles;
if (const auto vfsMode = Vfs::modeFromString(virtualFilesMode)) {
folderDefinition.virtualFilesMode = *vfsMode;
} else {
qCWarning(lcFolderMan) << "Unknown virtualFilesMode:" << virtualFilesMode << "assuming 'off'";
}
qCDebug(lcFolderMan) << "folderDefinition.alias" << folderDefinition.alias;
qCDebug(lcFolderMan) << "folderDefinition.virtualFilesMode" << folderDefinition.virtualFilesMode;
#ifdef Q_OS_MACOS
// macOS sandbox: Legacy configs won't have bookmark data yet.
// Try to create one now — this will only succeed if the app
// currently has access (e.g. first migration run right after
// the user granted access via QFileDialog).
if (folderDefinition.securityScopedBookmarkData.isEmpty()) {
folderDefinition.securityScopedBookmarkData = Utility::createSecurityScopedBookmarkData(folderDefinition.localPath);
}
#endif
auto vfs = createVfsFromPlugin(folderDefinition.virtualFilesMode);
if (!vfs && folderDefinition.virtualFilesMode != Vfs::Off) {
qCWarning(lcFolderMan) << "Could not load plugin for mode" << folderDefinition.virtualFilesMode;
}
if (const auto folder = addFolderInternal(folderDefinition, accountState, std::move(vfs))) {
auto ok = true;
auto legacyBlacklist = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList,
&ok);
if (!ok) {
qCInfo(lcFolderMan) << "There was a problem retrieving the database selective sync for " << folder;
}
legacyBlacklist << settings.value(QLatin1String("blackList")).toStringList();
if (!legacyBlacklist.isEmpty()) {
qCInfo(lcFolderMan) << "Legacy selective sync list found:" << legacyBlacklist;
for (const auto &legacyFolder : std::as_const(legacyBlacklist)) {
folder->migrateBlackListPath(legacyFolder);
}
settings.remove(QLatin1String("blackList"));
}
folder->saveToSettings();
qCInfo(lcFolderMan) << "Migrated!" << folder->path();
settings.sync();
if (!folder) {
continue;
}
scheduleFolder(folder);
emit folderSyncStateChange(folder);
#ifdef Q_OS_WIN
Utility::migrateFavLink(folder->cleanPath());
#endif
}
settings.endGroup(); // folder alias
}
};
settings.beginGroup(settingsAccountsC);
qCDebug(lcFolderMan) << "try to migrate accountId:" << accountState->account()->id();
settings.beginGroup(accountState->account()->id());
settings.beginGroup(settingsFoldersWithPlaceholdersC);
migrateFoldersGroup(settingsFoldersWithPlaceholdersC);
#ifdef Q_OS_WIN
_navigationPaneHelper.scheduleUpdateCloudStorageRegistry();
#endif
settings.endGroup();
settings.beginGroup(settingsFoldersC);
migrateFoldersGroup(settingsFoldersC);
settings.endGroup();
settings.endGroup();
settings.endGroup();
return;
}
void FolderMan::slotFolderSyncPaused(Folder *f, bool paused)
{
if (!f) {
qCCritical(lcFolderMan) << "slotFolderSyncPaused called with empty folder";
return;
}
if (!paused) {
_disabledFolders.remove(f);
scheduleFolder(f);
} else {
_disabledFolders.insert(f);
}
}
void FolderMan::slotFolderCanSyncChanged()
{
auto *f = qobject_cast<Folder *>(sender());
ASSERT(f);
if (f->canSync()) {
_socketApi->slotRegisterPath(f->alias());
} else {
_socketApi->slotUnregisterPath(f->alias());
}
}
Folder *FolderMan::folder(const QString &alias)
{
if (!alias.isEmpty()) {
if (_folderMap.contains(alias)) {
return _folderMap[alias];
}
}
return nullptr;
}
void FolderMan::scheduleAllFolders()
{
const auto folderMapValues = _folderMap.values();
for (const auto f : folderMapValues) {
if (f && f->canSync()) {
scheduleFolder(f);
}
}
}
void FolderMan::forceSyncForFolder(Folder *folder)
{
// Terminate and reschedule any running sync
for (const auto folderInMap : map()) {
if (folderInMap->isSyncRunning()) {
folderInMap->slotTerminateSync();
scheduleFolder(folderInMap);
}
}
folder->slotWipeErrorBlacklist(); // issue #6757
folder->setSyncPaused(false);
// Insert the selected folder at the front of the queue
scheduleFolderNext(folder);
}
void FolderMan::removeE2eFiles(const AccountPtr &account) const
{
Q_ASSERT(!account->e2e()->isInitialized());
for (const auto folder : map()) {
if(folder->accountState()->account()->id() == account->id()) {
folder->removeLocalE2eFiles();
}
}
}
void FolderMan::slotScheduleAppRestart()
{
_appRestartRequired = true;
qCInfo(lcFolderMan) << "Application restart requested!";
}
void FolderMan::slotSyncOnceFileUnlocks(const QString &path)
{
_lockWatcher->addFile(path);
}
/*
* if a folder wants to be synced, it calls this slot and is added
* to the queue. The slot to actually start a sync is called afterwards.
*/
void FolderMan::scheduleFolder(Folder *f)
{
if (!f) {
qCCritical(lcFolderMan) << "slotScheduleSync called with null folder";
return;
}
auto alias = f->alias();
qCInfo(lcFolderMan) << "Schedule folder " << alias << " to sync!";
auto syncAgainDelay = std::chrono::seconds(0);
if (f->consecutiveFailingSyncs() > 2 && f->consecutiveFailingSyncs() <= 4) {
syncAgainDelay = std::chrono::seconds(10);
} else if (f->consecutiveFailingSyncs() > 4 && f->consecutiveFailingSyncs() <= 6) {
syncAgainDelay = std::chrono::seconds(30);
} else if (f->consecutiveFailingSyncs() > 6) {
syncAgainDelay = std::chrono::seconds(60);
}
if (!_scheduledFolders.contains(f)) {
if (!f->canSync()) {
qCInfo(lcFolderMan) << "Folder is not ready to sync, not scheduled!";
_socketApi->slotUpdateFolderView(f);
return;
}
if (syncAgainDelay == std::chrono::seconds(0)) {
f->prepareToSync();
emit folderSyncStateChange(f);
_scheduledFolders.enqueue(f);
emit scheduleQueueChanged();
startScheduledSyncSoon();
} else {
qCWarning(lcFolderMan()) << "going to delay the next sync run due to too many synchronization errors" << syncAgainDelay;
QTimer::singleShot(syncAgainDelay, this, [this, f] () {
f->prepareToSync();
emit folderSyncStateChange(f);
_scheduledFolders.enqueue(f);
emit scheduleQueueChanged();
startScheduledSyncSoon();
});
}
} else {
qCInfo(lcFolderMan) << "Sync for folder " << alias << " already scheduled, do not enqueue!";
if (syncAgainDelay == std::chrono::seconds(0)) {
startScheduledSyncSoon();
} else {
qCWarning(lcFolderMan()) << "going to delay the next sync run due to too many synchronization errors" << syncAgainDelay;
QTimer::singleShot(syncAgainDelay, this, [this] () {
startScheduledSyncSoon();
});
}
}
}
void FolderMan::scheduleFolderForImmediateSync(Folder *f)
{
_nextSyncShouldStartImmediately = true;
scheduleFolder(f);
}
void FolderMan::scheduleFolderNext(Folder *f)
{
auto alias = f->alias();
qCInfo(lcFolderMan) << "Schedule folder " << alias << " to sync! Front-of-queue.";
if (!f->canSync()) {
qCInfo(lcFolderMan) << "Folder is not ready to sync, not scheduled!";
return;
}
_scheduledFolders.removeAll(f);
f->prepareToSync();
emit folderSyncStateChange(f);
_scheduledFolders.prepend(f);
emit scheduleQueueChanged();
startScheduledSyncSoon();
}
void FolderMan::slotScheduleETagJob(const QString & /*alias*/, RequestEtagJob *job)
{
QObject::connect(job, &QObject::destroyed, this, &FolderMan::slotEtagJobDestroyed);
QMetaObject::invokeMethod(this, "slotRunOneEtagJob", Qt::QueuedConnection);
// maybe: add to queue
}
void FolderMan::slotEtagJobDestroyed(QObject * /*o*/)
{
// _currentEtagJob is automatically cleared
// maybe: remove from queue
QMetaObject::invokeMethod(this, "slotRunOneEtagJob", Qt::QueuedConnection);
}
void FolderMan::slotRunOneEtagJob()
{
if (_currentEtagJob.isNull()) {
Folder *folder = nullptr;
for (const auto f : std::as_const(_folderMap)) {
if (f->etagJob()) {
// Caveat: always grabs the first folder with a job, but we think this is Ok for now and avoids us having a separate queue.
_currentEtagJob = f->etagJob();
folder = f;
break;
}
}
if (_currentEtagJob.isNull()) {
//qCDebug(lcFolderMan) << "No more remote ETag check jobs to schedule.";
/* now it might be a good time to check for restarting... */
if (!isAnySyncRunning() && _appRestartRequired) {
restartApplication();
}
} else {
qCDebug(lcFolderMan) << "Scheduling" << folder->remoteUrl().toString() << "to check remote ETag";
_currentEtagJob->start(); // on destroy/end it will continue the queue via slotEtagJobDestroyed
}
}
}
void FolderMan::slotAccountStateChanged()
{
auto *accountState = qobject_cast<AccountState *>(sender());
if (!accountState) {
return;
}
QString accountName = accountState->account()->displayName();
if (accountState->isConnected()) {
qCInfo(lcFolderMan) << "Account" << accountName << "connected, scheduling its folders";
const auto folderMapValues = _folderMap.values();
for (const auto f : folderMapValues) {
if (f
&& f->canSync()
&& f->accountState() == accountState) {
scheduleFolder(f);
}
}
} else {
qCInfo(lcFolderMan) << "Account" << accountName << "disconnected or paused, "
"terminating or descheduling sync folders";
const auto folderValues = _folderMap.values();
for (const auto f : folderValues) {
if (f
&& f->isSyncRunning()
&& f->accountState() == accountState) {
f->slotTerminateSync();
}
}
QMutableListIterator<Folder *> it(_scheduledFolders);
while (it.hasNext()) {
Folder *f = it.next();
if (f->accountState() == accountState) {
it.remove();
}
}
emit scheduleQueueChanged();
}
}
// only enable or disable foldermans will schedule and do syncs.
// this is not the same as Pause and Resume of folders.
void FolderMan::setSyncEnabled(bool enabled)
{
if (!_syncEnabled && enabled && !_scheduledFolders.isEmpty()) {
// We have things in our queue that were waiting for the connection to come back on.
startScheduledSyncSoon();
}
_syncEnabled = enabled;
// force a redraw in case the network connect status changed
emit folderSyncStateChange(nullptr);
}
void FolderMan::startScheduledSyncSoon()
{
if (_startScheduledSyncTimer.isActive()) {
return;
}
if (_scheduledFolders.empty()) {
return;
}
if (isAnySyncRunning()) {
return;
}
qint64 msDelay = 100; // 100ms minimum delay
qint64 msSinceLastSync = 0;
// Require a pause based on the duration of the last sync run.
if (Folder *lastFolder = _lastSyncFolder) {
msSinceLastSync = lastFolder->msecSinceLastSync().count();
// 1s -> 1.5s pause
// 10s -> 5s pause
// 1min -> 12s pause
// 1h -> 90s pause
qint64 pause = qSqrt(lastFolder->msecLastSyncDuration().count()) / 20.0 * 1000.0;
msDelay = qMax(msDelay, pause);
}