-
Notifications
You must be signed in to change notification settings - Fork 692
Expand file tree
/
Copy pathfolder.cpp
More file actions
1259 lines (1084 loc) · 45.3 KB
/
Copy pathfolder.cpp
File metadata and controls
1259 lines (1084 loc) · 45.3 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
/*
* Copyright (C) by Duncan Mac-Vicar P. <duncan@kde.org>
* Copyright (C) by Daniel Molkentin <danimo@owncloud.com>
* Copyright (C) by Klaas Freitag <freitag@owncloud.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
#include "folder.h"
#include "account.h"
#include "accountmanager.h"
#include "accountstate.h"
#include "application.h"
#include "common/checksums.h"
#include "common/filesystembase.h"
#include "common/syncjournalfilerecord.h"
#include "common/version.h"
#include "common/vfs.h"
#include "configfile.h"
#include "filesystem.h"
#include "folderman.h"
#include "folderwatcher.h"
#include "libsync/graphapi/spacesmanager.h"
#include "localdiscoverytracker.h"
#include "scheduling/syncscheduler.h"
#include "settingsdialog.h"
#include "socketapi/socketapi.h"
#include "syncengine.h"
#include "syncresult.h"
#include "syncrunfilelog.h"
#include "theme.h"
#ifdef Q_OS_WIN
#include "common/utility_win.h"
#endif
#include <QTimer>
#include <QUrl>
#include <QDir>
#include <QSettings>
#include <QMessageBox>
using namespace std::chrono_literals;
namespace {
/* How often to retry a sync
* Either due to _engine->isAnotherSyncNeeded or a sync error
*/
constexpr int retrySyncLimitC = 3;
auto davUrlC()
{
return QStringLiteral("davUrl");
}
auto spaceIdC()
{
return QStringLiteral("spaceId");
}
auto displayNameC()
{
return QLatin1String("displayString");
}
// todo #52 - eliminate this config value and scrub configs next major release
[[deprecated("deployed concept is no longer supported and will be removed in client 8.0")]] auto deployedC()
{
return QStringLiteral("deployed");
}
auto priorityC()
{
return QStringLiteral("priority");
}
}
namespace OCC {
using namespace FileSystem::SizeLiterals;
Q_LOGGING_CATEGORY(lcFolder, "gui.folder", QtInfoMsg)
Folder::Folder(const FolderDefinition &definition, AccountState *accountState, std::unique_ptr<Vfs> &&vfs, bool ignoreHiddenFiles, QObject *parent)
: QObject(parent)
, _accountState(accountState)
, _definition(definition)
, _journal(_definition.absoluteJournalPath())
, _fileLog(new SyncRunFileLog)
, _vfs(vfs.release())
{
_timeSinceLastSyncStart.start();
_timeSinceLastSyncDone.start();
SyncResult::Status status = SyncResult::NotYetStarted;
if (definition.paused()) {
status = SyncResult::Paused;
}
setSyncState(status);
// check if the starting conditions are legit
if (_accountState && _accountState->account() && checkLocalPath()) {
prepareFolder(path());
// those errors should not persist over sessions
_journal.wipeErrorBlacklistCategory(SyncJournalErrorBlacklistRecord::Category::LocalSoftError);
// todo: the engine needs to be created externally, presumably by the folderman, and passed in by injection
// current impl can result in an invalid engine which is just a mess given the folder is useless without it
_engine.reset(new SyncEngine(_accountState->account(), webDavUrl(), path(), remotePath(), &_journal));
// pass the setting if hidden files are to be ignored, will be read in csync_update
_engine->setIgnoreHiddenFiles(ignoreHiddenFiles);
if (!_engine->loadDefaultExcludes()) {
qCWarning(lcFolder, "Could not read system exclude file");
}
connect(_accountState, &AccountState::isConnectedChanged, this, &Folder::canSyncChanged);
connect(_engine.data(), &SyncEngine::started, this, &Folder::slotSyncStarted, Qt::QueuedConnection);
connect(_engine.data(), &SyncEngine::finished, this, &Folder::slotSyncFinished, Qt::QueuedConnection);
connect(_engine.data(), &SyncEngine::transmissionProgress, this,
[this](const ProgressInfo &pi) { Q_EMIT ProgressDispatcher::instance()->progressInfo(this, pi); });
connect(_engine.data(), &SyncEngine::transmissionProgress, this, &Folder::progressUpdate);
connect(_engine.data(), &SyncEngine::itemCompleted, this, &Folder::slotItemCompleted);
connect(_engine.data(), &SyncEngine::seenLockedFile, FolderMan::instance(), &FolderMan::slotSyncOnceFileUnlocks);
connect(_engine.data(), &SyncEngine::aboutToPropagate,
this, &Folder::slotLogPropagationStart);
connect(_engine.data(), &SyncEngine::syncError, this, &Folder::slotSyncError);
connect(ProgressDispatcher::instance(), &ProgressDispatcher::folderConflicts,
this, &Folder::slotFolderConflicts);
connect(_engine.data(), &SyncEngine::excluded, this, [this](const QString &path) { Q_EMIT ProgressDispatcher::instance()->excluded(this, path); });
_localDiscoveryTracker.reset(new LocalDiscoveryTracker);
connect(_engine.data(), &SyncEngine::finished,
_localDiscoveryTracker.data(), &LocalDiscoveryTracker::slotSyncFinished);
connect(_engine.data(), &SyncEngine::itemCompleted,
_localDiscoveryTracker.data(), &LocalDiscoveryTracker::slotItemCompleted);
connect(_accountState->account()->spacesManager(), &GraphApi::SpacesManager::spaceChanged, this, [this](GraphApi::Space *changedSpace) {
if (_definition.spaceId() == changedSpace->id()) {
emit spaceChanged();
}
});
if (space())
emit spaceChanged();
// Potentially upgrade suffix vfs to windows vfs
OC_ENFORCE(_vfs);
// Initialize the vfs plugin. Do this after the UI is running, so we can show a dialog when something goes wrong.
QTimer::singleShot(0, this, &Folder::startVfs);
}
}
Folder::~Folder()
{
// If wipeForRemoval() was called the vfs has already shut down.
if (_vfs)
_vfs->stop();
// Reset then engine first as it will abort and try to access members of the Folder
_engine.reset();
}
Result<void, QString> Folder::checkPathLength(const QString &path)
{
#ifdef Q_OS_WIN
if (path.size() > MAX_PATH) {
if (!FileSystem::longPathsEnabledOnWindows()) {
return tr("The path '%1' is too long. Please enable long paths in the Windows settings or choose a different folder.").arg(path);
}
}
#else
Q_UNUSED(path)
#endif
return {};
}
GraphApi::Space *Folder::space() const
{
if (_accountState && _accountState->account() && _accountState->account()->spacesManager()) {
return _accountState->account()->spacesManager()->space(_definition.spaceId());
}
return nullptr;
}
bool Folder::checkLocalPath()
{
#ifdef Q_OS_WIN
QNtfsPermissionCheckGuard ntfs_perm;
#endif
const QFileInfo fi(_definition.localPath());
_canonicalLocalPath = fi.canonicalFilePath();
#ifdef Q_OS_MAC
// Workaround QTBUG-55896 (Should be fixed in Qt 5.8)
_canonicalLocalPath = _canonicalLocalPath.normalized(QString::NormalizationForm_C);
#endif
if (_canonicalLocalPath.isEmpty()) {
qCWarning(lcFolder) << "Broken symlink:" << _definition.localPath();
_canonicalLocalPath = _definition.localPath();
} else if (!_canonicalLocalPath.endsWith(QLatin1Char('/'))) {
_canonicalLocalPath.append(QLatin1Char('/'));
}
QString error;
if (fi.isDir() && fi.isReadable() && fi.isWritable()) {
auto pathLengthCheck = checkPathLength(_canonicalLocalPath);
if (!pathLengthCheck) {
error = pathLengthCheck.error();
}
if (error.isEmpty()) {
qCDebug(lcFolder) << "Checked local path ok";
if (!_journal.open()) {
error = tr("%1 failed to open the database.").arg(_definition.localPath());
}
}
} else {
// Check directory again
if (!FileSystem::fileExists(_definition.localPath(), fi)) {
error = tr("Local folder %1 does not exist.").arg(_definition.localPath());
} else if (!fi.isDir()) {
error = tr("%1 should be a folder but is not.").arg(_definition.localPath());
} else if (!fi.isReadable()) {
error = tr("%1 is not readable.").arg(_definition.localPath());
} else if (!fi.isWritable()) {
error = tr("%1 is not writable.").arg(_definition.localPath());
}
}
if (!error.isEmpty()) {
qCWarning(lcFolder) << error;
_syncResult.appendErrorString(error);
setSyncState(SyncResult::SetupError);
return false;
}
return true;
}
SyncOptions Folder::loadSyncOptions()
{
SyncOptions opt(_vfs);
ConfigFile cfgFile;
opt._moveFilesToTrash = cfgFile.moveToTrash();
// got a nullptr hit here - this is so shady but best I can do for now
opt._parallelNetworkJobs = (_accountState && _accountState->account() && _accountState->account()->isHttp2Supported()) ? 20 : 6;
opt.fillFromEnvironmentVariables();
return opt;
}
void Folder::prepareFolder(const QString &path)
{
#ifdef Q_OS_WIN
// First create a Desktop.ini so that the folder and favorite link show our application's icon.
const QFileInfo desktopIniPath{QStringLiteral("%1/Desktop.ini").arg(path)};
{
const QString updateIconKey = QStringLiteral("%1/UpdateIcon").arg(Theme::instance()->appName());
QSettings desktopIni(desktopIniPath.absoluteFilePath(), QSettings::IniFormat);
if (desktopIni.value(updateIconKey, true).toBool()) {
qCInfo(lcFolder) << "Creating" << desktopIni.fileName() << "to set a folder icon in Explorer.";
desktopIni.setValue(QStringLiteral(".ShellClassInfo/IconResource"), QDir::toNativeSeparators(qApp->applicationFilePath()));
desktopIni.setValue(updateIconKey, true);
} else {
qCInfo(lcFolder) << "Skip icon update for" << desktopIni.fileName() << "," << updateIconKey << "is disabled";
}
}
const QString longFolderPath = FileSystem::longWinPath(path);
const QString longDesktopIniPath = FileSystem::longWinPath(desktopIniPath.absoluteFilePath());
// Set the folder as system and Desktop.ini as hidden+system for explorer to pick it.
// https://msdn.microsoft.com/en-us/library/windows/desktop/cc144102
const DWORD folderAttrs = GetFileAttributesW(reinterpret_cast<const wchar_t *>(longFolderPath.utf16()));
if (!SetFileAttributesW(reinterpret_cast<const wchar_t *>(longFolderPath.utf16()), folderAttrs | FILE_ATTRIBUTE_SYSTEM)) {
const auto error = GetLastError();
qCWarning(lcFolder) << "SetFileAttributesW failed on" << longFolderPath << Utility::formatWinError(error);
}
if (!SetFileAttributesW(reinterpret_cast<const wchar_t *>(longDesktopIniPath.utf16()), FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) {
const auto error = GetLastError();
qCWarning(lcFolder) << "SetFileAttributesW failed on" << longDesktopIniPath << Utility::formatWinError(error);
}
#else
Q_UNUSED(path)
#endif
}
QString Folder::displayName() const
{
if (auto *s = space()) {
return s->displayName();
}
return _definition.displayName();
}
QString Folder::shortGuiLocalPath() const
{
QString p = _definition.localPath();
QString home = QDir::homePath();
if (!home.endsWith(QLatin1Char('/'))) {
home.append(QLatin1Char('/'));
}
if (p.startsWith(home)) {
p = p.mid(home.length());
}
if (p.length() > 1 && p.endsWith(QLatin1Char('/'))) {
p.chop(1);
}
return QDir::toNativeSeparators(p);
}
QString Folder::cleanPath() const
{
QString cleanedPath = QDir::cleanPath(_canonicalLocalPath);
if (cleanedPath.length() == 3 && cleanedPath.endsWith(QLatin1String(":/")))
cleanedPath.remove(2, 1);
return cleanedPath;
}
QUrl Folder::webDavUrl() const
{
GraphApi::Space *sp = space();
if (sp)
return sp->webDavUrl();
return _definition.webDavUrl();
}
QString Folder::remotePathTrailingSlash() const
{
const QString remote = remotePath();
if (!remote.endsWith((QLatin1Char('/'))))
return remote + QLatin1Char('/');
return remote;
}
bool Folder::isSyncRunning() const
{
return !hasSetupError() && _engine->isSyncRunning();
}
bool Folder::canSync() const
{
if (!_engine || !_accountState || !_accountState->account() || !_folderWatcher)
return false;
return isAvailable() && !syncPaused() && _accountState->readyForSync() && isReady() && _accountState->account()->hasCapabilities();
}
bool Folder::isReady() const
{
return _vfsIsReady;
}
void Folder::setSyncPaused(bool paused)
{
if (hasSetupError()) {
return;
}
if (paused == _definition.paused()) {
return;
}
_definition.setPaused(paused);
Q_EMIT syncPausedChanged(this, paused);
if (!paused) {
setSyncState(SyncResult::NotYetStarted);
} else {
setSyncState(SyncResult::Paused);
}
Q_EMIT canSyncChanged();
}
void Folder::setAvailable(bool available)
{
if (available != (space() != nullptr))
return;
_available = available;
_syncResult.reset();
if (!_available) {
_syncResult.setStatus(SyncResult::Status::Unavailable);
_syncResult.appendErrorString(tr("The folder has been disabled or removed from the server"));
} else {
_syncResult.setStatus(SyncResult::Status::NotYetStarted);
}
emit syncStateChange();
emit canSyncChanged();
}
bool Folder::isConnected()
{
return (_accountState && _accountState->isConnected());
}
void Folder::setSyncState(SyncResult::Status state)
{
if (state != _syncResult.status()) {
_syncResult.setStatus(state);
Q_EMIT syncStateChange();
}
}
void Folder::showSyncResultPopup()
{
if (_syncResult.firstItemNew()) {
createGuiLog(_syncResult.firstItemNew()->destination(), LogStatusNew, _syncResult.numNewItems());
}
if (_syncResult.firstItemDeleted()) {
createGuiLog(_syncResult.firstItemDeleted()->destination(), LogStatusRemove, _syncResult.numRemovedItems());
}
if (_syncResult.firstItemUpdated()) {
createGuiLog(_syncResult.firstItemUpdated()->destination(), LogStatusUpdated, _syncResult.numUpdatedItems());
}
if (_syncResult.firstItemRenamed()) {
LogStatus status(LogStatusRename);
// if the path changes it's rather a move
QDir renTarget = QFileInfo(_syncResult.firstItemRenamed()->_renameTarget).dir();
QDir renSource = QFileInfo(_syncResult.firstItemRenamed()->_file).dir();
if (renTarget != renSource) {
status = LogStatusMove;
}
createGuiLog(_syncResult.firstItemRenamed()->_file, status,
_syncResult.numRenamedItems(), _syncResult.firstItemRenamed()->_renameTarget);
}
if (_syncResult.firstNewConflictItem()) {
createGuiLog(_syncResult.firstNewConflictItem()->destination(), LogStatusConflict, _syncResult.numNewConflictItems());
}
if (int errorCount = _syncResult.numErrorItems()) {
createGuiLog(_syncResult.firstItemError()->_file, LogStatusError, errorCount);
}
qCInfo(lcFolder) << "Folder" << path() << "sync result: " << _syncResult.status();
}
void Folder::createGuiLog(const QString &filename, LogStatus status, int count,
const QString &renameTarget)
{
if (count > 0) {
QString file = QDir::toNativeSeparators(filename);
QString text;
switch (status) {
case LogStatusRemove:
if (count > 1) {
text = tr("%1 and %n other file(s) have been removed.", "", count - 1).arg(file);
} else {
text = tr("%1 has been removed.", "%1 names a file.").arg(file);
}
break;
case LogStatusNew:
if (count > 1) {
text = tr("%1 and %n other file(s) have been added.", "", count - 1).arg(file);
} else {
text = tr("%1 has been added.", "%1 names a file.").arg(file);
}
break;
case LogStatusUpdated:
if (count > 1) {
text = tr("%1 and %n other file(s) have been updated.", "", count - 1).arg(file);
} else {
text = tr("%1 has been updated.", "%1 names a file.").arg(file);
}
break;
case LogStatusRename:
if (count > 1) {
text = tr("%1 has been renamed to %2 and %n other file(s) have been renamed.", "", count - 1).arg(file, renameTarget);
} else {
text = tr("%1 has been renamed to %2.", "%1 and %2 name files.").arg(file, renameTarget);
}
break;
case LogStatusMove:
if (count > 1) {
text = tr("%1 has been moved to %2 and %n other file(s) have been moved.", "", count - 1).arg(file, renameTarget);
} else {
text = tr("%1 has been moved to %2.").arg(file, renameTarget);
}
break;
case LogStatusConflict:
if (count > 1) {
text = tr("%1 and %n other file(s) have sync conflicts.", "", count - 1).arg(file);
} else {
text = tr("%1 has a sync conflict. Please check the conflict file!").arg(file);
}
break;
case LogStatusError:
if (count > 1) {
text = tr("%1 and %n other file(s) could not be synced due to errors. See the log for details.", "", count - 1).arg(file);
} else {
text = tr("%1 could not be synced due to an error. See the log for details.").arg(file);
}
break;
}
if (!text.isEmpty()) {
ocApp()->gui()->slotShowOptionalTrayMessage(tr("Sync Activity"), text);
}
}
}
void Folder::startVfs()
{
if (!_accountState || !_accountState->account())
return;
OC_ENFORCE(_vfs);
OC_ENFORCE(_vfs->mode() == _definition.virtualFilesMode());
// todo: DC-219 check to see if this sync error makes it to the gui or not. We need to more clearly inform the user that they should
// create a new sync connection to the remote folder, and use improved checks in the folder wizard to make sure vfs is supported
// on the chosen path.
// ideally we want a check like this before we even get here, eg in the area of load folder from config - but need to be sure there is
// a place to clearly instruct the user that the folder sync needs to be re-built with a valid local path
QString result = Vfs::pathSupportDetail(path(), _vfs->mode());
if (!result.isEmpty()) {
_syncResult.appendErrorString(result);
setSyncState(SyncResult::SetupError);
return;
}
VfsSetupParams vfsParams(_accountState->account(), webDavUrl(), _engine.get());
vfsParams.filesystemPath = path();
vfsParams.remotePath = remotePathTrailingSlash();
vfsParams.journal = &_journal;
vfsParams.providerDisplayName = Theme::instance()->appNameGUI();
vfsParams.providerName = Theme::instance()->appName();
vfsParams.providerVersion = Version::version();
vfsParams.multipleAccountsRegistered = AccountManager::instance()->accounts().size() > 1;
connect(&_engine->syncFileStatusTracker(), &SyncFileStatusTracker::fileStatusChanged, _vfs.get(), &Vfs::fileStatusChanged);
connect(_vfs.get(), &Vfs::started, this, [this] {
// Immediately mark the sqlite temporaries as excluded. They get recreated
// on db-open and need to get marked again every time.
QString stateDbFile = _journal.databaseFilePath();
_vfs->fileStatusChanged(stateDbFile + QStringLiteral("-wal"), SyncFileStatus::StatusExcluded);
_vfs->fileStatusChanged(stateDbFile + QStringLiteral("-shm"), SyncFileStatus::StatusExcluded);
_engine->setSyncOptions(loadSyncOptions());
registerFolderWatcher();
connect(_vfs.get(), &Vfs::needSync, this, [this] {
if (canSync()) {
// the vfs plugin detected that its metadata is out of sync and requests a new sync
// the request has a high priority as it is probably issued after a user request
FolderMan::instance()->scheduler()->enqueueFolder(this, SyncScheduler::Priority::High);
}
});
_vfsIsReady = true;
// We are set up, schedule ourselves if we can.
// If not the scheduler will take care of it later.
if (canSync()) {
// Refactoring todo: also no. We need a general cleanup task to eval and fix all of these crossed triggers
// the only element that should emit FolderMan signals is FolderMan! same for any/all other classes
// I don't care if signals are now public: it is not correct for anyone but the owner to trigger them
FolderMan::instance()->scheduler()->enqueueFolder(this);
}
});
connect(_vfs.get(), &Vfs::error, this, [this](const QString &error) {
_syncResult.appendErrorString(error);
setSyncState(SyncResult::SetupError);
_vfsIsReady = false;
});
slotNextSyncFullLocalDiscovery();
_vfs->start(vfsParams);
}
void Folder::slotDiscardDownloadProgress()
{
// Delete from journal and from filesystem.
QDir folderpath(_definition.localPath());
QSet<QString> keep_nothing;
const QVector<SyncJournalDb::DownloadInfo> deleted_infos =
_journal.getAndDeleteStaleDownloadInfos(keep_nothing);
for (const auto &deleted_info : deleted_infos) {
const QString tmppath = folderpath.filePath(deleted_info._tmpfile);
qCInfo(lcFolder) << "Deleting temporary file: " << tmppath;
FileSystem::remove(tmppath);
}
}
int Folder::slotWipeErrorBlacklist()
{
return _journal.wipeErrorBlacklist();
}
void Folder::slotWatchedPathsChanged(const QSet<QString> &paths, ChangeReason reason)
{
if (!isReady()) {
// we might be switching backend
return;
}
bool needSync = false;
for (const auto &path : paths) {
Q_ASSERT(FileSystem::isChildPathOf(path, this->path()));
if (!FileSystem::isChildPathOf(path, this->path()))
continue;
const QString relativePath = path.mid(this->path().size());
if (reason == ChangeReason::UnLock) {
journalDb()->wipeErrorBlacklistEntry(relativePath, SyncJournalErrorBlacklistRecord::Category::LocalSoftError);
{
// horrible hack to compensate that we don't handle folder deletes on a per-file basis
qsizetype index = 0;
QString p = relativePath;
while ((index = p.lastIndexOf(QLatin1Char('/'))) != -1) {
p = p.left(index);
const auto rec = journalDb()->errorBlacklistEntry(p);
if (rec.isValid()) {
if (rec._errorCategory == SyncJournalErrorBlacklistRecord::Category::LocalSoftError) {
journalDb()->wipeErrorBlacklistEntry(p);
}
}
}
}
}
// Add to list of locally modified paths
//
// We do this before checking for our own sync-related changes to make
// extra sure to not miss relevant changes.
_localDiscoveryTracker->addTouchedPath(relativePath);
SyncJournalFileRecord record;
_journal.getFileRecord(relativePath.toUtf8(), &record);
if (reason != ChangeReason::UnLock) {
// Check that the mtime/size actually changed or there was
// an attribute change (pin state) that caused the notification
bool spurious = false;
if (record.isValid() && !FileSystem::fileChanged(QFileInfo{path}, record._fileSize, record._modtime, record._inode)) {
spurious = true;
if (auto pinState = _vfs->pinState(relativePath)) {
if (*pinState == PinState::AlwaysLocal && record.isVirtualFile())
spurious = false;
if (*pinState == PinState::OnlineOnly && record.isFile())
spurious = false;
}
}
if (spurious) {
qCInfo(lcFolder) << "Ignoring spurious notification for file" << relativePath;
continue; // probably a spurious notification
}
}
warnOnNewExcludedItem(record, relativePath);
Q_EMIT watchedFileChangedExternally(path);
needSync = true;
}
if (needSync && canSync()) {
FolderMan::instance()->scheduler()->enqueueFolder(this);
}
}
void Folder::implicitlyHydrateFile(const QString &relativepath)
{
qCInfo(lcFolder) << "Implicitly hydrate virtual file:" << relativepath;
// Set in the database that we should download the file
SyncJournalFileRecord record;
_journal.getFileRecord(relativepath.toUtf8(), &record);
if (!record.isValid()) {
qCInfo(lcFolder) << "Did not find file in db";
return;
}
if (!record.isVirtualFile()) {
qCInfo(lcFolder) << "The file is not virtual";
return;
}
record._type = ItemTypeVirtualFileDownload;
_journal.setFileRecord(record);
// Change the file's pin state if it's contradictory to being hydrated
// (suffix-virtual file's pin state is stored at the hydrated path)
const auto pin = _vfs->pinState(relativepath);
if (pin && *pin == PinState::OnlineOnly) {
std::ignore = _vfs->setPinState(relativepath, PinState::Unspecified);
}
// Add to local discovery
schedulePathForLocalDiscovery(relativepath);
FolderMan::instance()->scheduler()->enqueueFolder(this);
}
void Folder::setVirtualFilesEnabled(bool enabled)
{
Vfs::Mode newMode = _definition.virtualFilesMode();
if (enabled && _definition.virtualFilesMode() == Vfs::Off) {
newMode = VfsPluginManager::instance().bestAvailableVfsMode();
} else if (!enabled) {
newMode = Vfs::Off;
}
if (newMode == _definition.virtualFilesMode()) {
return;
}
if (isSyncRunning()) {
connect(this, &Folder::syncFinished, this, [this, newMode] { changeVfsMode(newMode); }, Qt::SingleShotConnection);
slotTerminateSync(tr("Switching VFS mode on folder '%1'").arg(displayName()));
} else {
changeVfsMode(newMode);
}
}
// Refactoring todo: this still causes THREE saves to config file which is potentially excessive for large
// sets.
// I think the best way to fix it is to avoid calling setSyncPaused as that emits a couple of changes,
// which may be overkill for this temp setting change (ie running to paused and back to running)
// needs a deeper look. For the moment most of the pain related to this is avoided because we now only
// connect the folder after it's set up, so the saves during setup are avoided = huge improvement already.
void Folder::changeVfsMode(Vfs::Mode newMode)
{
if (newMode == _definition.virtualFilesMode()) {
return;
}
// This is tested in TestSyncVirtualFiles::testWipeVirtualSuffixFiles, so for changes here, have them reflected in that test.
const bool wasPaused = _definition.paused();
if (!wasPaused) {
setSyncPaused(true);
}
// stash the previous blacklist
bool ok;
const auto oldBlacklist = journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, ok);
if (!ok) {
qCWarning(lcFolder) << "Unable to retrieve previous selective sync blacklist for folder: " << _definition.localPath();
return;
}
// clear previous blacklist
journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, {});
// Wipe the dehydrated files from the DB, they will get downloaded on the next sync. We need to do this, otherwise the files
// are in the DB but not on disk, so the client assumes they are deleted, and removes them from the remote.
_vfs->wipeDehydratedVirtualFiles();
// Tear down and disconnect the VFS
_vfsIsReady = false;
_vfs->stop();
_vfs->unregisterFolder();
disconnect(_vfs.get(), nullptr, this, nullptr);
disconnect(&_engine->syncFileStatusTracker(), nullptr, _vfs.get(), nullptr);
// _vfs is a shared pointer...
// Refactor todo: who is it shared with? It appears to be shared with the SyncOptions. SyncOptions instance is then
// passed to the engine. It is not clear to me how/when the options vfs shared ptr gets updated to match this
// new/reset instance but this should be high prio to work this out as wow this is dangerous. the todo is basically: eval the use of
// this _vfs pointer and make it consistent and SAFE across uses
_vfs.reset(VfsPluginManager::instance().createVfsFromPlugin(newMode).release());
// Restart VFS.
_definition.setVirtualFilesMode(newMode);
if (newMode != Vfs::Off) {
// schedule blacklisted folders for rediscovery
connect(_vfs.get(), &Vfs::started, this, [oldBlacklist, this] {
for (const auto &entry : oldBlacklist) {
journalDb()->schedulePathForRemoteDiscovery(entry);
// Refactoring todo: from what I can see, in 98% of cases the return val of setPinState is ignored
// do we actually need that return value?! if so why aren't we using it?
std::ignore = vfs().setPinState(entry, PinState::OnlineOnly);
}
});
}
if (!wasPaused) {
setSyncPaused(wasPaused);
}
startVfs();
Q_EMIT vfsModeChanged(this, newMode);
}
bool Folder::isDeployed() const
{
return _definition.isDeployed();
}
bool Folder::isFileExcludedAbsolute(const QString &fullPath) const
{
if (OC_ENSURE_NOT(_engine.isNull())) {
return _engine->isExcluded(fullPath);
}
return true;
}
bool Folder::isFileExcludedRelative(const QString &relativePath) const
{
return isFileExcludedAbsolute(path() + relativePath);
}
void Folder::slotTerminateSync(const QString &reason)
{
if (isReady()) {
qCInfo(lcFolder) << "folder " << path() << " Terminating!";
if (_engine->isSyncRunning()) {
_engine->abort(reason);
setSyncState(SyncResult::SyncAbortRequested);
}
}
}
void Folder::wipeForRemoval()
{
// we can't acces those variables
if (hasSetupError()) {
return;
}
// prevent interaction with the db etc
_vfsIsReady = false;
// stop reacting to changes
// especially the upcoming deletion of the db
// Refactoring todo: this may not be safe - using deleteLater on a real pointer is probably more reasonable.
_folderWatcher.reset();
// Delete files that have been partially downloaded.
slotDiscardDownloadProgress();
// Unregister the socket API so it does not keep the .sync_journal file open
FolderMan::instance()->socketApi()->slotUnregisterPath(this);
_journal.close(); // close the sync journal
// Remove db and temporaries
const QString stateDbFile = _engine->journal()->databaseFilePath();
QFile file(stateDbFile);
if (file.exists()) {
if (!file.remove()) {
qCCritical(lcFolder) << "Failed to remove existing csync StateDB " << stateDbFile;
} else {
qCInfo(lcFolder) << "wipe: Removed csync StateDB " << stateDbFile;
}
} else {
qCWarning(lcFolder) << "statedb is empty, can not remove.";
}
// Also remove other db related files
QFile::remove(stateDbFile + QStringLiteral(".ctmp"));
QFile::remove(stateDbFile + QStringLiteral("-shm"));
QFile::remove(stateDbFile + QStringLiteral("-wal"));
QFile::remove(stateDbFile + QStringLiteral("-journal"));
_vfs->stop();
_vfs->unregisterFolder();
_vfs.reset(nullptr); // warning: folder now in an invalid state
}
bool Folder::reloadExcludes()
{
// reloadExcludes returns true *if the excludes were successfully reloaded*.
// If the engine is missing the excludes
// can't be reloaded so return here should be false? Erik agrees - caller never checks the value anyway
if (!_engine) {
return false;
}
return _engine->reloadExcludes();
}
void Folder::startSync()
{
if (!isReady() || !_folderWatcher) {
qCWarning(lcFolder) << "Folder sync attempted before ready and/or without valid folder watcher";
return;
}
if (!OC_ENSURE(!isSyncRunning())) {
qCCritical(lcFolder) << "ERROR sync is still running and new sync requested.";
return;
}
if (!OC_ENSURE(canSync())) {
qCCritical(lcFolder) << "ERROR folder is currently not sync able.";
return;
}
_timeSinceLastSyncStart.start();
setSyncState(SyncResult::SyncPrepare);
_syncResult.reset();
qCInfo(lcFolder) << "*** Start syncing " << remoteUrl().toString() << "client version"
<< Theme::instance()->aboutVersions(Theme::VersionFormat::OneLiner);
_fileLog->start(path());
if (!reloadExcludes()) {
slotSyncError(tr("Could not read system exclude file"));
QMetaObject::invokeMethod(
this, [this] { slotSyncFinished(false); }, Qt::QueuedConnection);
return;
}
// get the latest touched files
// this will enqueue this folder again, it doesn't matter
slotWatchedPathsChanged(_folderWatcher->popChangeSet(), Folder::ChangeReason::Other);
const std::chrono::milliseconds fullLocalDiscoveryInterval = ConfigFile().fullLocalDiscoveryInterval();
const bool hasDoneFullLocalDiscovery = _timeSinceLastFullLocalDiscovery.isValid();
// negative fullLocalDiscoveryInterval means we don't require periodic full runs
const bool periodicFullLocalDiscoveryNow =
fullLocalDiscoveryInterval.count() >= 0 && _timeSinceLastFullLocalDiscovery.hasExpired(fullLocalDiscoveryInterval.count());
if (_folderWatcher && _folderWatcher->isReliable()
&& hasDoneFullLocalDiscovery
&& !periodicFullLocalDiscoveryNow) {
qCInfo(lcFolder) << "Allowing local discovery to read from the database";
_engine->setLocalDiscoveryOptions(
LocalDiscoveryStyle::DatabaseAndFilesystem,
_localDiscoveryTracker->localDiscoveryPaths());
_localDiscoveryTracker->startSyncPartialDiscovery();
} else {
qCInfo(lcFolder) << "Forbidding local discovery to read from the database";
_engine->setLocalDiscoveryOptions(LocalDiscoveryStyle::FilesystemOnly);
_localDiscoveryTracker->startSyncFullDiscovery();
}
QMetaObject::invokeMethod(_engine.data(), &SyncEngine::startSync, Qt::QueuedConnection);
Q_EMIT syncStarted();
}
void Folder::reloadSyncOptions()
{
_engine->setSyncOptions(loadSyncOptions());
}
void Folder::slotSyncError(const QString &message, ErrorCategory category)
{
_syncResult.appendErrorString(message);
Q_EMIT ProgressDispatcher::instance()->syncError(this, message, category);
}
void Folder::slotSyncStarted()
{
qCInfo(lcFolder) << "#### Propagation start ####################################################";
setSyncState(SyncResult::SyncRunning);
}
void Folder::slotSyncFinished(bool success)
{
if (!isReady()) {
// probably removing the folder
qCWarning(lcFolder) << "Folder not ready after sync finished";
return;
}
qCInfo(lcFolder) << "Client version" << Theme::instance()->aboutVersions(Theme::VersionFormat::OneLiner);
bool syncError = !_syncResult.errorStrings().isEmpty();
if (syncError) {
qCWarning(lcFolder) << "SyncEngine finished with ERROR";
} else {
qCInfo(lcFolder) << "SyncEngine finished without problem.";
}
_fileLog->finish();
showSyncResultPopup();
auto anotherSyncNeeded = false;
auto syncStatus = SyncResult::Status::Undefined;
if (syncError) {
syncStatus = SyncResult::Error;
} else if (_syncResult.foundFilesNotSynced()) {
syncStatus = SyncResult::Problem;
} else if (_definition.paused()) {
// Maybe the sync was terminated because the user paused the folder
syncStatus = SyncResult::Paused;
} else {
syncStatus = SyncResult::Success;
}
// Count the number of syncs that have failed in a row.
if (syncStatus == SyncResult::Success || syncStatus == SyncResult::Problem) {
_consecutiveFailingSyncs = 0;
} else {
_consecutiveFailingSyncs++;
anotherSyncNeeded |= _consecutiveFailingSyncs <= retrySyncLimitC;
qCInfo(lcFolder) << "the last" << _consecutiveFailingSyncs << "syncs failed";
}
if (syncStatus == SyncResult::Success && success) {
// Clear the white list as all the folders that should be on that list are sync-ed
journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, {});