folder.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567
  1. /*
  2. * Copyright (C) by Duncan Mac-Vicar P. <duncan@kde.org>
  3. * Copyright (C) by Daniel Molkentin <danimo@owncloud.com>
  4. * Copyright (C) by Klaas Freitag <freitag@owncloud.com>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful, but
  12. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  13. * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  14. * for more details.
  15. */
  16. #include "config.h"
  17. #include "account.h"
  18. #include "accountmanager.h"
  19. #include "accountstate.h"
  20. #include "folder.h"
  21. #include "folderman.h"
  22. #include "logger.h"
  23. #include "configfile.h"
  24. #include "networkjobs.h"
  25. #include "common/syncjournalfilerecord.h"
  26. #include "syncresult.h"
  27. #include "clientproxy.h"
  28. #include "syncengine.h"
  29. #include "syncrunfilelog.h"
  30. #include "socketapi/socketapi.h"
  31. #include "theme.h"
  32. #include "filesystem.h"
  33. #include "localdiscoverytracker.h"
  34. #include "csync_exclude.h"
  35. #include "common/vfs.h"
  36. #include "creds/abstractcredentials.h"
  37. #include "settingsdialog.h"
  38. #include <QTimer>
  39. #include <QUrl>
  40. #include <QDir>
  41. #include <QSettings>
  42. #include <QMessageBox>
  43. #include <QPushButton>
  44. #include <QApplication>
  45. namespace {
  46. #ifndef VERSION_C
  47. #define VERSION_C
  48. constexpr auto versionC = "version";
  49. #endif
  50. }
  51. namespace OCC {
  52. Q_LOGGING_CATEGORY(lcFolder, "nextcloud.gui.folder", QtInfoMsg)
  53. Folder::Folder(const FolderDefinition &definition,
  54. AccountState *accountState, std::unique_ptr<Vfs> vfs,
  55. QObject *parent)
  56. : QObject(parent)
  57. , _accountState(accountState)
  58. , _definition(definition)
  59. , _lastSyncDuration(0)
  60. , _journal(_definition.absoluteJournalPath())
  61. , _fileLog(new SyncRunFileLog)
  62. , _vfs(vfs.release())
  63. {
  64. _timeSinceLastSyncStart.start();
  65. _timeSinceLastSyncDone.start();
  66. SyncResult::Status status = SyncResult::NotYetStarted;
  67. if (definition.paused) {
  68. status = SyncResult::Paused;
  69. }
  70. _syncResult.setStatus(status);
  71. // check if the local path exists
  72. checkLocalPath();
  73. _syncResult.setFolder(_definition.alias);
  74. _engine.reset(new SyncEngine(_accountState->account(), path(), initializeSyncOptions(), remotePath(), &_journal));
  75. // pass the setting if hidden files are to be ignored, will be read in csync_update
  76. _engine->setIgnoreHiddenFiles(_definition.ignoreHiddenFiles);
  77. ConfigFile::setupDefaultExcludeFilePaths(_engine->excludedFiles());
  78. if (!reloadExcludes())
  79. qCWarning(lcFolder, "Could not read system exclude file");
  80. connect(_accountState.data(), &AccountState::isConnectedChanged, this, &Folder::canSyncChanged);
  81. connect(_engine.data(), &SyncEngine::rootEtag, this, &Folder::etagRetrievedFromSyncEngine);
  82. connect(_engine.data(), &SyncEngine::started, this, &Folder::slotSyncStarted, Qt::QueuedConnection);
  83. connect(_engine.data(), &SyncEngine::finished, this, &Folder::slotSyncFinished, Qt::QueuedConnection);
  84. connect(_engine.data(), &SyncEngine::aboutToRemoveAllFiles,
  85. this, &Folder::slotAboutToRemoveAllFiles);
  86. connect(_engine.data(), &SyncEngine::transmissionProgress, this, &Folder::slotTransmissionProgress);
  87. connect(_engine.data(), &SyncEngine::itemCompleted,
  88. this, &Folder::slotItemCompleted);
  89. connect(_engine.data(), &SyncEngine::newBigFolder,
  90. this, &Folder::slotNewBigFolderDiscovered);
  91. connect(_engine.data(), &SyncEngine::seenLockedFile, FolderMan::instance(), &FolderMan::slotSyncOnceFileUnlocks);
  92. connect(_engine.data(), &SyncEngine::aboutToPropagate,
  93. this, &Folder::slotLogPropagationStart);
  94. connect(_engine.data(), &SyncEngine::syncError, this, &Folder::slotSyncError);
  95. connect(_engine.data(), &SyncEngine::addErrorToGui, this, &Folder::slotAddErrorToGui);
  96. _scheduleSelfTimer.setSingleShot(true);
  97. _scheduleSelfTimer.setInterval(SyncEngine::minimumFileAgeForUpload);
  98. connect(&_scheduleSelfTimer, &QTimer::timeout,
  99. this, &Folder::slotScheduleThisFolder);
  100. connect(ProgressDispatcher::instance(), &ProgressDispatcher::folderConflicts,
  101. this, &Folder::slotFolderConflicts);
  102. _localDiscoveryTracker.reset(new LocalDiscoveryTracker);
  103. connect(_engine.data(), &SyncEngine::finished,
  104. _localDiscoveryTracker.data(), &LocalDiscoveryTracker::slotSyncFinished);
  105. connect(_engine.data(), &SyncEngine::itemCompleted,
  106. _localDiscoveryTracker.data(), &LocalDiscoveryTracker::slotItemCompleted);
  107. connect(_accountState->account().data(), &Account::capabilitiesChanged, this, &Folder::slotCapabilitiesChanged);
  108. // Potentially upgrade suffix vfs to windows vfs
  109. ENFORCE(_vfs);
  110. if (_definition.virtualFilesMode == Vfs::WithSuffix
  111. && _definition.upgradeVfsMode) {
  112. if (isVfsPluginAvailable(Vfs::WindowsCfApi)) {
  113. if (auto winvfs = createVfsFromPlugin(Vfs::WindowsCfApi)) {
  114. // Wipe the existing suffix files from fs and journal
  115. SyncEngine::wipeVirtualFiles(path(), _journal, *_vfs);
  116. // Then switch to winvfs mode
  117. _vfs.reset(winvfs.release());
  118. _definition.virtualFilesMode = Vfs::WindowsCfApi;
  119. }
  120. }
  121. saveToSettings();
  122. }
  123. // Initialize the vfs plugin
  124. startVfs();
  125. }
  126. Folder::~Folder()
  127. {
  128. // If wipeForRemoval() was called the vfs has already shut down.
  129. if (_vfs)
  130. _vfs->stop();
  131. // Reset then engine first as it will abort and try to access members of the Folder
  132. _engine.reset();
  133. }
  134. void Folder::checkLocalPath()
  135. {
  136. const QFileInfo fi(_definition.localPath);
  137. _canonicalLocalPath = fi.canonicalFilePath();
  138. #ifdef Q_OS_MAC
  139. // Workaround QTBUG-55896 (Should be fixed in Qt 5.8)
  140. _canonicalLocalPath = _canonicalLocalPath.normalized(QString::NormalizationForm_C);
  141. #endif
  142. if (_canonicalLocalPath.isEmpty()) {
  143. qCWarning(lcFolder) << "Broken symlink:" << _definition.localPath;
  144. _canonicalLocalPath = _definition.localPath;
  145. } else if (!_canonicalLocalPath.endsWith('/')) {
  146. _canonicalLocalPath.append('/');
  147. }
  148. if (fi.isDir() && fi.isReadable()) {
  149. qCDebug(lcFolder) << "Checked local path ok";
  150. } else {
  151. // Check directory again
  152. if (!FileSystem::fileExists(_definition.localPath, fi)) {
  153. _syncResult.appendErrorString(tr("Local folder %1 does not exist.").arg(_definition.localPath));
  154. _syncResult.setStatus(SyncResult::SetupError);
  155. } else if (!fi.isDir()) {
  156. _syncResult.appendErrorString(tr("%1 should be a folder but is not.").arg(_definition.localPath));
  157. _syncResult.setStatus(SyncResult::SetupError);
  158. } else if (!fi.isReadable()) {
  159. _syncResult.appendErrorString(tr("%1 is not readable.").arg(_definition.localPath));
  160. _syncResult.setStatus(SyncResult::SetupError);
  161. }
  162. }
  163. }
  164. QString Folder::shortGuiRemotePathOrAppName() const
  165. {
  166. if (remotePath().length() > 0 && remotePath() != QLatin1String("/")) {
  167. QString a = QFile(remotePath()).fileName();
  168. if (a.startsWith('/')) {
  169. a = a.remove(0, 1);
  170. }
  171. return a;
  172. } else {
  173. return Theme::instance()->appNameGUI();
  174. }
  175. }
  176. QString Folder::alias() const
  177. {
  178. return _definition.alias;
  179. }
  180. QString Folder::path() const
  181. {
  182. return _canonicalLocalPath;
  183. }
  184. QString Folder::shortGuiLocalPath() const
  185. {
  186. QString p = _definition.localPath;
  187. QString home = QDir::homePath();
  188. if (!home.endsWith('/')) {
  189. home.append('/');
  190. }
  191. if (p.startsWith(home)) {
  192. p = p.mid(home.length());
  193. }
  194. if (p.length() > 1 && p.endsWith('/')) {
  195. p.chop(1);
  196. }
  197. return QDir::toNativeSeparators(p);
  198. }
  199. bool Folder::ignoreHiddenFiles()
  200. {
  201. bool re(_definition.ignoreHiddenFiles);
  202. return re;
  203. }
  204. void Folder::setIgnoreHiddenFiles(bool ignore)
  205. {
  206. _definition.ignoreHiddenFiles = ignore;
  207. }
  208. QString Folder::cleanPath() const
  209. {
  210. QString cleanedPath = QDir::cleanPath(_canonicalLocalPath);
  211. if (cleanedPath.length() == 3 && cleanedPath.endsWith(":/"))
  212. cleanedPath.remove(2, 1);
  213. return cleanedPath;
  214. }
  215. bool Folder::isBusy() const
  216. {
  217. return isSyncRunning();
  218. }
  219. bool Folder::isSyncRunning() const
  220. {
  221. return _engine->isSyncRunning() || (_vfs && _vfs->isHydrating());
  222. }
  223. QString Folder::remotePath() const
  224. {
  225. return _definition.targetPath;
  226. }
  227. QString Folder::remotePathTrailingSlash() const
  228. {
  229. QString result = remotePath();
  230. if (!result.endsWith('/'))
  231. result.append('/');
  232. return result;
  233. }
  234. QUrl Folder::remoteUrl() const
  235. {
  236. return Utility::concatUrlPath(_accountState->account()->davUrl(), remotePath());
  237. }
  238. bool Folder::syncPaused() const
  239. {
  240. return _definition.paused;
  241. }
  242. bool Folder::canSync() const
  243. {
  244. return !syncPaused() && accountState()->isConnected();
  245. }
  246. void Folder::setSyncPaused(bool paused)
  247. {
  248. if (paused == _definition.paused) {
  249. return;
  250. }
  251. _definition.paused = paused;
  252. saveToSettings();
  253. if (!paused) {
  254. setSyncState(SyncResult::NotYetStarted);
  255. } else {
  256. setSyncState(SyncResult::Paused);
  257. }
  258. emit syncPausedChanged(this, paused);
  259. emit syncStateChange();
  260. emit canSyncChanged();
  261. }
  262. void Folder::setSyncState(SyncResult::Status state)
  263. {
  264. if (_silenceErrorsUntilNextSync && state == SyncResult::Error) {
  265. _syncResult.setStatus(SyncResult::Status::Success);
  266. return;
  267. }
  268. _syncResult.setStatus(state);
  269. }
  270. SyncResult Folder::syncResult() const
  271. {
  272. return _syncResult;
  273. }
  274. void Folder::prepareToSync()
  275. {
  276. _syncResult.reset();
  277. _syncResult.setStatus(SyncResult::NotYetStarted);
  278. }
  279. void Folder::slotRunEtagJob()
  280. {
  281. qCInfo(lcFolder) << "Trying to check" << remoteUrl().toString() << "for changes via ETag check. (time since last sync:" << (_timeSinceLastSyncDone.elapsed() / 1000) << "s)";
  282. AccountPtr account = _accountState->account();
  283. if (_requestEtagJob) {
  284. qCInfo(lcFolder) << remoteUrl().toString() << "has ETag job queued, not trying to sync";
  285. return;
  286. }
  287. if (!canSync()) {
  288. qCInfo(lcFolder) << "Not syncing. :" << remoteUrl().toString() << _definition.paused << AccountState::stateString(_accountState->state());
  289. return;
  290. }
  291. // Do the ordinary etag check for the root folder and schedule a
  292. // sync if it's different.
  293. _requestEtagJob = new RequestEtagJob(account, remotePath(), this);
  294. _requestEtagJob->setTimeout(60 * 1000);
  295. // check if the etag is different when retrieved
  296. QObject::connect(_requestEtagJob.data(), &RequestEtagJob::etagRetrieved, this, &Folder::etagRetrieved);
  297. FolderMan::instance()->slotScheduleETagJob(alias(), _requestEtagJob);
  298. // The _requestEtagJob is auto deleting itself on finish. Our guard pointer _requestEtagJob will then be null.
  299. }
  300. void Folder::etagRetrieved(const QByteArray &etag, const QDateTime &tp)
  301. {
  302. // re-enable sync if it was disabled because network was down
  303. FolderMan::instance()->setSyncEnabled(true);
  304. if (_lastEtag != etag) {
  305. qCInfo(lcFolder) << "Compare etag with previous etag: last:" << _lastEtag << ", received:" << etag << "-> CHANGED";
  306. _lastEtag = etag;
  307. slotScheduleThisFolder();
  308. }
  309. _accountState->tagLastSuccessfullETagRequest(tp);
  310. }
  311. void Folder::etagRetrievedFromSyncEngine(const QByteArray &etag, const QDateTime &time)
  312. {
  313. qCInfo(lcFolder) << "Root etag from during sync:" << etag;
  314. accountState()->tagLastSuccessfullETagRequest(time);
  315. _lastEtag = etag;
  316. }
  317. void Folder::showSyncResultPopup()
  318. {
  319. if (_syncResult.firstItemNew()) {
  320. createGuiLog(_syncResult.firstItemNew()->destination(), LogStatusNew, _syncResult.numNewItems());
  321. }
  322. if (_syncResult.firstItemDeleted()) {
  323. createGuiLog(_syncResult.firstItemDeleted()->destination(), LogStatusRemove, _syncResult.numRemovedItems());
  324. }
  325. if (_syncResult.firstItemUpdated()) {
  326. createGuiLog(_syncResult.firstItemUpdated()->destination(), LogStatusUpdated, _syncResult.numUpdatedItems());
  327. }
  328. if (_syncResult.firstItemRenamed()) {
  329. LogStatus status(LogStatusRename);
  330. // if the path changes it's rather a move
  331. QDir renTarget = QFileInfo(_syncResult.firstItemRenamed()->_renameTarget).dir();
  332. QDir renSource = QFileInfo(_syncResult.firstItemRenamed()->_file).dir();
  333. if (renTarget != renSource) {
  334. status = LogStatusMove;
  335. }
  336. createGuiLog(_syncResult.firstItemRenamed()->_file, status,
  337. _syncResult.numRenamedItems(), _syncResult.firstItemRenamed()->_renameTarget);
  338. }
  339. if (_syncResult.firstNewConflictItem()) {
  340. createGuiLog(_syncResult.firstNewConflictItem()->destination(), LogStatusConflict, _syncResult.numNewConflictItems());
  341. }
  342. if (int errorCount = _syncResult.numErrorItems()) {
  343. createGuiLog(_syncResult.firstItemError()->_file, LogStatusError, errorCount);
  344. }
  345. if (int lockedCount = _syncResult.numLockedItems()) {
  346. createGuiLog(_syncResult.firstItemLocked()->_file, LogStatusFileLocked, lockedCount);
  347. }
  348. qCInfo(lcFolder) << "Folder" << _syncResult.folder() << "sync result: " << _syncResult.status();
  349. }
  350. void Folder::createGuiLog(const QString &filename, LogStatus status, int count,
  351. const QString &renameTarget)
  352. {
  353. if (count > 0) {
  354. Logger *logger = Logger::instance();
  355. QString file = QDir::toNativeSeparators(filename);
  356. QString text;
  357. switch (status) {
  358. case LogStatusRemove:
  359. if (count > 1) {
  360. text = tr("%1 and %n other file(s) have been removed.", "", count - 1).arg(file);
  361. } else {
  362. text = tr("%1 has been removed.", "%1 names a file.").arg(file);
  363. }
  364. break;
  365. case LogStatusNew:
  366. if (count > 1) {
  367. text = tr("%1 and %n other file(s) have been added.", "", count - 1).arg(file);
  368. } else {
  369. text = tr("%1 has been added.", "%1 names a file.").arg(file);
  370. }
  371. break;
  372. case LogStatusUpdated:
  373. if (count > 1) {
  374. text = tr("%1 and %n other file(s) have been updated.", "", count - 1).arg(file);
  375. } else {
  376. text = tr("%1 has been updated.", "%1 names a file.").arg(file);
  377. }
  378. break;
  379. case LogStatusRename:
  380. if (count > 1) {
  381. text = tr("%1 has been renamed to %2 and %n other file(s) have been renamed.", "", count - 1).arg(file, renameTarget);
  382. } else {
  383. text = tr("%1 has been renamed to %2.", "%1 and %2 name files.").arg(file, renameTarget);
  384. }
  385. break;
  386. case LogStatusMove:
  387. if (count > 1) {
  388. text = tr("%1 has been moved to %2 and %n other file(s) have been moved.", "", count - 1).arg(file, renameTarget);
  389. } else {
  390. text = tr("%1 has been moved to %2.").arg(file, renameTarget);
  391. }
  392. break;
  393. case LogStatusConflict:
  394. if (count > 1) {
  395. text = tr("%1 has and %n other file(s) have sync conflicts.", "", count - 1).arg(file);
  396. } else {
  397. text = tr("%1 has a sync conflict. Please check the conflict file!").arg(file);
  398. }
  399. break;
  400. case LogStatusError:
  401. if (count > 1) {
  402. text = tr("%1 and %n other file(s) could not be synced due to errors. See the log for details.", "", count - 1).arg(file);
  403. } else {
  404. text = tr("%1 could not be synced due to an error. See the log for details.").arg(file);
  405. }
  406. break;
  407. case LogStatusFileLocked:
  408. if (count > 1) {
  409. text = tr("%1 and %n other file(s) are currently locked.", "", count -1).arg(file);
  410. } else {
  411. text = tr("%1 is currently locked.").arg(file);
  412. }
  413. break;
  414. }
  415. if (!text.isEmpty()) {
  416. // Ignores the settings in case of an error or conflict
  417. if(status == LogStatusError || status == LogStatusConflict)
  418. logger->postOptionalGuiLog(tr("Sync Activity"), text);
  419. }
  420. }
  421. }
  422. void Folder::startVfs()
  423. {
  424. ENFORCE(_vfs);
  425. ENFORCE(_vfs->mode() == _definition.virtualFilesMode);
  426. VfsSetupParams vfsParams;
  427. vfsParams.filesystemPath = path();
  428. vfsParams.displayName = shortGuiRemotePathOrAppName();
  429. vfsParams.alias = alias();
  430. vfsParams.navigationPaneClsid = navigationPaneClsid().toString();
  431. vfsParams.remotePath = remotePathTrailingSlash();
  432. vfsParams.account = _accountState->account();
  433. vfsParams.journal = &_journal;
  434. vfsParams.providerName = Theme::instance()->appNameGUI();
  435. vfsParams.providerVersion = Theme::instance()->version();
  436. vfsParams.multipleAccountsRegistered = AccountManager::instance()->accounts().size() > 1;
  437. connect(_vfs.data(), &Vfs::beginHydrating, this, &Folder::slotHydrationStarts);
  438. connect(_vfs.data(), &Vfs::doneHydrating, this, &Folder::slotHydrationDone);
  439. connect(&_engine->syncFileStatusTracker(), &SyncFileStatusTracker::fileStatusChanged,
  440. _vfs.data(), &Vfs::fileStatusChanged);
  441. _vfs->start(vfsParams);
  442. // Immediately mark the sqlite temporaries as excluded. They get recreated
  443. // on db-open and need to get marked again every time.
  444. QString stateDbFile = _journal.databaseFilePath();
  445. _journal.open();
  446. _vfs->fileStatusChanged(stateDbFile + "-wal", SyncFileStatus::StatusExcluded);
  447. _vfs->fileStatusChanged(stateDbFile + "-shm", SyncFileStatus::StatusExcluded);
  448. }
  449. int Folder::slotDiscardDownloadProgress()
  450. {
  451. // Delete from journal and from filesystem.
  452. QDir folderpath(_definition.localPath);
  453. QSet<QString> keep_nothing;
  454. const QVector<SyncJournalDb::DownloadInfo> deleted_infos =
  455. _journal.getAndDeleteStaleDownloadInfos(keep_nothing);
  456. for (const auto &deleted_info : deleted_infos) {
  457. const QString tmppath = folderpath.filePath(deleted_info._tmpfile);
  458. qCInfo(lcFolder) << "Deleting temporary file: " << tmppath;
  459. FileSystem::remove(tmppath);
  460. }
  461. return deleted_infos.size();
  462. }
  463. int Folder::downloadInfoCount()
  464. {
  465. return _journal.downloadInfoCount();
  466. }
  467. int Folder::errorBlackListEntryCount()
  468. {
  469. return _journal.errorBlackListEntryCount();
  470. }
  471. int Folder::slotWipeErrorBlacklist()
  472. {
  473. return _journal.wipeErrorBlacklist();
  474. }
  475. void Folder::slotWatchedPathChanged(const QString &path, ChangeReason reason)
  476. {
  477. if (!path.startsWith(this->path())) {
  478. qCDebug(lcFolder) << "Changed path is not contained in folder, ignoring:" << path;
  479. return;
  480. }
  481. auto relativePath = path.midRef(this->path().size());
  482. // Add to list of locally modified paths
  483. //
  484. // We do this before checking for our own sync-related changes to make
  485. // extra sure to not miss relevant changes.
  486. auto relativePathBytes = relativePath.toUtf8();
  487. _localDiscoveryTracker->addTouchedPath(relativePathBytes);
  488. // The folder watcher fires a lot of bogus notifications during
  489. // a sync operation, both for actual user files and the database
  490. // and log. Therefore we check notifications against operations
  491. // the sync is doing to filter out our own changes.
  492. #ifdef Q_OS_MAC
  493. // On OSX the folder watcher does not report changes done by our
  494. // own process. Therefore nothing needs to be done here!
  495. #else
  496. // Use the path to figure out whether it was our own change
  497. if (_engine->wasFileTouched(path)) {
  498. qCDebug(lcFolder) << "Changed path was touched by SyncEngine, ignoring:" << path;
  499. return;
  500. }
  501. #endif
  502. SyncJournalFileRecord record;
  503. if (!_journal.getFileRecord(relativePathBytes, &record)) {
  504. qCWarning(lcFolder) << "could not get file from local DB" << relativePathBytes;
  505. }
  506. if (reason != ChangeReason::UnLock) {
  507. // Check that the mtime/size actually changed or there was
  508. // an attribute change (pin state) that caused the notification
  509. bool spurious = false;
  510. if (record.isValid()
  511. && !FileSystem::fileChanged(path, record._fileSize, record._modtime)) {
  512. spurious = true;
  513. if (auto pinState = _vfs->pinState(relativePath.toString())) {
  514. if (*pinState == PinState::AlwaysLocal && record.isVirtualFile())
  515. spurious = false;
  516. if (*pinState == PinState::OnlineOnly && record.isFile())
  517. spurious = false;
  518. }
  519. }
  520. if (spurious) {
  521. qCInfo(lcFolder) << "Ignoring spurious notification for file" << relativePath;
  522. return; // probably a spurious notification
  523. }
  524. }
  525. warnOnNewExcludedItem(record, relativePath);
  526. emit watchedFileChangedExternally(path);
  527. // Also schedule this folder for a sync, but only after some delay:
  528. // The sync will not upload files that were changed too recently.
  529. scheduleThisFolderSoon();
  530. }
  531. void Folder::slotFilesLockReleased(const QSet<QString> &files)
  532. {
  533. qCDebug(lcFolder) << "Going to unlock office files" << files;
  534. for (const auto &file : files) {
  535. const auto fileRecordPath = fileFromLocalPath(file);
  536. SyncJournalFileRecord rec;
  537. const auto canUnlockFile = journalDb()->getFileRecord(fileRecordPath, &rec)
  538. && rec.isValid()
  539. && rec._lockstate._locked
  540. && rec._lockstate._lockOwnerType == static_cast<qint64>(SyncFileItem::LockOwnerType::UserLock)
  541. && rec._lockstate._lockOwnerId == _accountState->account()->davUser();
  542. if (!canUnlockFile) {
  543. qCDebug(lcFolder) << "Skipping file" << file << "with rec.isValid():" << rec.isValid()
  544. << "and rec._lockstate._lockOwnerId:" << rec._lockstate._lockOwnerId << "and davUser:" << _accountState->account()->davUser();
  545. continue;
  546. }
  547. const QString remoteFilePath = remotePathTrailingSlash() + rec.path();
  548. qCDebug(lcFolder) << "Unlocking an office file" << remoteFilePath;
  549. _officeFileLockReleaseUnlockSuccess = connect(_accountState->account().data(), &Account::lockFileSuccess, this, [this, remoteFilePath]() {
  550. disconnect(_officeFileLockReleaseUnlockSuccess);
  551. qCDebug(lcFolder) << "Unlocking an office file succeeded" << remoteFilePath;
  552. startSync();
  553. });
  554. _officeFileLockReleaseUnlockFailure = connect(_accountState->account().data(), &Account::lockFileError, this, [this, remoteFilePath](const QString &message) {
  555. disconnect(_officeFileLockReleaseUnlockFailure);
  556. qCWarning(lcFolder) << "Failed to unlock a file:" << remoteFilePath << message;
  557. });
  558. _accountState->account()->setLockFileState(remoteFilePath, journalDb(), SyncFileItem::LockStatus::UnlockedItem);
  559. }
  560. }
  561. void Folder::implicitlyHydrateFile(const QString &relativepath)
  562. {
  563. qCInfo(lcFolder) << "Implicitly hydrate virtual file:" << relativepath;
  564. // Set in the database that we should download the file
  565. SyncJournalFileRecord record;
  566. ;
  567. if (!_journal.getFileRecord(relativepath.toUtf8(), &record)) {
  568. qCWarning(lcFolder) << "could not get file from local DB" << relativepath;
  569. return;
  570. }
  571. if (!record.isValid()) {
  572. qCInfo(lcFolder) << "Did not find file in db";
  573. return;
  574. }
  575. if (!record.isVirtualFile()) {
  576. qCInfo(lcFolder) << "The file is not virtual";
  577. return;
  578. }
  579. record._type = ItemTypeVirtualFileDownload;
  580. const auto result = _journal.setFileRecord(record);
  581. if (!result) {
  582. qCWarning(lcFolder) << "Error when setting the file record to the database" << record._path << result.error();
  583. return;
  584. }
  585. // Change the file's pin state if it's contradictory to being hydrated
  586. // (suffix-virtual file's pin state is stored at the hydrated path)
  587. const auto pin = _vfs->pinState(relativepath);
  588. if (pin && *pin == PinState::OnlineOnly) {
  589. if (!_vfs->setPinState(relativepath, PinState::Unspecified)) {
  590. qCWarning(lcFolder) << "Could not set pin state of" << relativepath << "to unspecified";
  591. }
  592. }
  593. // Add to local discovery
  594. schedulePathForLocalDiscovery(relativepath);
  595. slotScheduleThisFolder();
  596. }
  597. void Folder::setVirtualFilesEnabled(bool enabled)
  598. {
  599. Vfs::Mode newMode = _definition.virtualFilesMode;
  600. if (enabled && _definition.virtualFilesMode == Vfs::Off) {
  601. newMode = bestAvailableVfsMode();
  602. } else if (!enabled && _definition.virtualFilesMode != Vfs::Off) {
  603. newMode = Vfs::Off;
  604. }
  605. if (newMode != _definition.virtualFilesMode) {
  606. // TODO: Must wait for current sync to finish!
  607. SyncEngine::wipeVirtualFiles(path(), _journal, *_vfs);
  608. _vfs->stop();
  609. _vfs->unregisterFolder();
  610. disconnect(_vfs.data(), nullptr, this, nullptr);
  611. disconnect(&_engine->syncFileStatusTracker(), nullptr, _vfs.data(), nullptr);
  612. _vfs.reset(createVfsFromPlugin(newMode).release());
  613. _definition.virtualFilesMode = newMode;
  614. startVfs();
  615. if (newMode != Vfs::Off) {
  616. _saveInFoldersWithPlaceholders = true;
  617. switchToVirtualFiles();
  618. }
  619. saveToSettings();
  620. }
  621. }
  622. void Folder::setRootPinState(PinState state)
  623. {
  624. if (!_vfs->setPinState(QString(), state)) {
  625. qCWarning(lcFolder) << "Could not set root pin state of" << _definition.alias;
  626. }
  627. // We don't actually need discovery, but it's important to recurse
  628. // into all folders, so the changes can be applied.
  629. slotNextSyncFullLocalDiscovery();
  630. }
  631. void Folder::switchToVirtualFiles()
  632. {
  633. SyncEngine::switchToVirtualFiles(path(), _journal, *_vfs);
  634. _hasSwitchedToVfs = true;
  635. }
  636. void Folder::processSwitchedToVirtualFiles()
  637. {
  638. if (_hasSwitchedToVfs) {
  639. _hasSwitchedToVfs = false;
  640. saveToSettings();
  641. }
  642. }
  643. bool Folder::supportsSelectiveSync() const
  644. {
  645. return !virtualFilesEnabled() && !isVfsOnOffSwitchPending();
  646. }
  647. void Folder::saveToSettings() const
  648. {
  649. // Remove first to make sure we don't get duplicates
  650. removeFromSettings();
  651. auto settings = _accountState->settings();
  652. QString settingsGroup = QStringLiteral("Multifolders");
  653. // True if the folder path appears in only one account
  654. const auto folderMap = FolderMan::instance()->map();
  655. const auto oneAccountOnly = std::none_of(folderMap.cbegin(), folderMap.cend(), [this](const auto *other) {
  656. return other != this && other->cleanPath() == this->cleanPath();
  657. });
  658. if (virtualFilesEnabled() || _saveInFoldersWithPlaceholders) {
  659. // If virtual files are enabled or even were enabled at some point,
  660. // save the folder to a group that will not be read by older (<2.5.0) clients.
  661. // The name is from when virtual files were called placeholders.
  662. settingsGroup = QStringLiteral("FoldersWithPlaceholders");
  663. } else if (_saveBackwardsCompatible || oneAccountOnly) {
  664. // The folder is saved to backwards-compatible "Folders"
  665. // section only if it has the migrate flag set (i.e. was in
  666. // there before) or if the folder is the only one for the
  667. // given target path.
  668. // This ensures that older clients will not read a configuration
  669. // where two folders for different accounts point at the same
  670. // local folders.
  671. settingsGroup = QStringLiteral("Folders");
  672. }
  673. settings->beginGroup(settingsGroup);
  674. // Note: Each of these groups might have a "version" tag, but that's
  675. // currently unused.
  676. settings->beginGroup(FolderMan::escapeAlias(_definition.alias));
  677. FolderDefinition::save(*settings, _definition);
  678. settings->sync();
  679. qCInfo(lcFolder) << "Saved folder" << _definition.alias << "to settings, status" << settings->status();
  680. }
  681. void Folder::removeFromSettings() const
  682. {
  683. auto settings = _accountState->settings();
  684. settings->beginGroup(QLatin1String("Folders"));
  685. settings->remove(FolderMan::escapeAlias(_definition.alias));
  686. settings->endGroup();
  687. settings->beginGroup(QLatin1String("Multifolders"));
  688. settings->remove(FolderMan::escapeAlias(_definition.alias));
  689. settings->endGroup();
  690. settings->beginGroup(QLatin1String("FoldersWithPlaceholders"));
  691. settings->remove(FolderMan::escapeAlias(_definition.alias));
  692. }
  693. bool Folder::isFileExcludedAbsolute(const QString &fullPath) const
  694. {
  695. return _engine->excludedFiles().isExcluded(fullPath, path(), _definition.ignoreHiddenFiles);
  696. }
  697. bool Folder::isFileExcludedRelative(const QString &relativePath) const
  698. {
  699. return _engine->excludedFiles().isExcluded(path() + relativePath, path(), _definition.ignoreHiddenFiles);
  700. }
  701. void Folder::slotTerminateSync()
  702. {
  703. qCInfo(lcFolder) << "folder " << alias() << " Terminating!";
  704. if (_engine->isSyncRunning()) {
  705. _engine->abort();
  706. setSyncState(SyncResult::SyncAbortRequested);
  707. }
  708. }
  709. void Folder::wipeForRemoval()
  710. {
  711. // Delete files that have been partially downloaded.
  712. slotDiscardDownloadProgress();
  713. // Unregister the socket API so it does not keep the .sync_journal file open
  714. FolderMan::instance()->socketApi()->slotUnregisterPath(alias());
  715. _journal.close(); // close the sync journal
  716. // Remove db and temporaries
  717. QString stateDbFile = _engine->journal()->databaseFilePath();
  718. QFile file(stateDbFile);
  719. if (file.exists()) {
  720. if (!file.remove()) {
  721. qCWarning(lcFolder) << "Failed to remove existing csync StateDB " << stateDbFile;
  722. } else {
  723. qCInfo(lcFolder) << "wipe: Removed csync StateDB " << stateDbFile;
  724. }
  725. } else {
  726. qCWarning(lcFolder) << "statedb is empty, can not remove.";
  727. }
  728. // Also remove other db related files
  729. QFile::remove(stateDbFile + ".ctmp");
  730. QFile::remove(stateDbFile + "-shm");
  731. QFile::remove(stateDbFile + "-wal");
  732. QFile::remove(stateDbFile + "-journal");
  733. _vfs->stop();
  734. _vfs->unregisterFolder();
  735. _vfs.reset(nullptr); // warning: folder now in an invalid state
  736. }
  737. bool Folder::reloadExcludes()
  738. {
  739. return _engine->excludedFiles().reloadExcludeFiles();
  740. }
  741. void Folder::startSync(const QStringList &pathList)
  742. {
  743. Q_UNUSED(pathList);
  744. setSilenceErrorsUntilNextSync(false);
  745. const auto singleItemDiscoveryOptions = _engine->singleItemDiscoveryOptions();
  746. Q_ASSERT(!singleItemDiscoveryOptions.discoveryDirItem || singleItemDiscoveryOptions.discoveryDirItem->isDirectory());
  747. if (singleItemDiscoveryOptions.discoveryDirItem && !singleItemDiscoveryOptions.discoveryDirItem->isDirectory()) {
  748. qCCritical(lcFolder) << "startSync only accepts directory SyncFileItem, not a file.";
  749. }
  750. if (isBusy()) {
  751. qCCritical(lcFolder) << "ERROR csync is still running and new sync requested.";
  752. return;
  753. }
  754. _timeSinceLastSyncStart.start();
  755. _syncResult.setStatus(SyncResult::SyncPrepare);
  756. emit syncStateChange();
  757. qCInfo(lcFolder) << "*** Start syncing " << remoteUrl().toString() << " -" << APPLICATION_NAME << "client version"
  758. << qPrintable(Theme::instance()->version());
  759. _fileLog->start(path());
  760. if (!reloadExcludes()) {
  761. slotSyncError(tr("Could not read system exclude file"), ErrorCategory::GenericError);
  762. QMetaObject::invokeMethod(this, "slotSyncFinished", Qt::QueuedConnection, Q_ARG(bool, false));
  763. return;
  764. }
  765. setDirtyNetworkLimits();
  766. syncEngine().setSyncOptions(initializeSyncOptions());
  767. static std::chrono::milliseconds fullLocalDiscoveryInterval = []() {
  768. auto interval = ConfigFile().fullLocalDiscoveryInterval();
  769. QByteArray env = qgetenv("OWNCLOUD_FULL_LOCAL_DISCOVERY_INTERVAL");
  770. if (!env.isEmpty()) {
  771. interval = std::chrono::milliseconds(env.toLongLong());
  772. }
  773. return interval;
  774. }();
  775. bool hasDoneFullLocalDiscovery = _timeSinceLastFullLocalDiscovery.isValid();
  776. bool periodicFullLocalDiscoveryNow =
  777. fullLocalDiscoveryInterval.count() >= 0 // negative means we don't require periodic full runs
  778. && _timeSinceLastFullLocalDiscovery.hasExpired(fullLocalDiscoveryInterval.count());
  779. if (singleItemDiscoveryOptions.isValid() && singleItemDiscoveryOptions.discoveryPath != QStringLiteral("/")) {
  780. qCInfo(lcFolder) << "Going to sync just one file";
  781. _engine->setLocalDiscoveryOptions(LocalDiscoveryStyle::DatabaseAndFilesystem, {singleItemDiscoveryOptions.discoveryPath});
  782. _localDiscoveryTracker->startSyncPartialDiscovery();
  783. } else if (_folderWatcher && _folderWatcher->isReliable()
  784. && hasDoneFullLocalDiscovery
  785. && !periodicFullLocalDiscoveryNow) {
  786. qCInfo(lcFolder) << "Allowing local discovery to read from the database";
  787. _engine->setLocalDiscoveryOptions(
  788. LocalDiscoveryStyle::DatabaseAndFilesystem,
  789. _localDiscoveryTracker->localDiscoveryPaths());
  790. _localDiscoveryTracker->startSyncPartialDiscovery();
  791. } else {
  792. qCInfo(lcFolder) << "Forbidding local discovery to read from the database";
  793. _engine->setLocalDiscoveryOptions(LocalDiscoveryStyle::FilesystemOnly);
  794. _localDiscoveryTracker->startSyncFullDiscovery();
  795. }
  796. _engine->setIgnoreHiddenFiles(_definition.ignoreHiddenFiles);
  797. correctPlaceholderFiles();
  798. QMetaObject::invokeMethod(_engine.data(), "startSync", Qt::QueuedConnection);
  799. emit syncStarted();
  800. }
  801. void Folder::correctPlaceholderFiles()
  802. {
  803. if (_definition.virtualFilesMode == Vfs::Off) {
  804. return;
  805. }
  806. static const auto placeholdersCorrectedKey = QStringLiteral("placeholders_corrected");
  807. const auto placeholdersCorrected = _journal.keyValueStoreGetInt(placeholdersCorrectedKey, 0);
  808. if (!placeholdersCorrected) {
  809. qCDebug(lcFolder) << "Make sure all virtual files are placeholder files";
  810. switchToVirtualFiles();
  811. _journal.keyValueStoreSet(placeholdersCorrectedKey, true);
  812. }
  813. }
  814. SyncOptions Folder::initializeSyncOptions() const
  815. {
  816. SyncOptions opt;
  817. ConfigFile cfgFile;
  818. auto newFolderLimit = cfgFile.newBigFolderSizeLimit();
  819. opt._newBigFolderSizeLimit = newFolderLimit.first ? newFolderLimit.second * 1000LL * 1000LL : -1; // convert from MB to B
  820. opt._confirmExternalStorage = cfgFile.confirmExternalStorage();
  821. opt._moveFilesToTrash = cfgFile.moveToTrash();
  822. opt._vfs = _vfs;
  823. opt._parallelNetworkJobs = _accountState->account()->isHttp2Supported() ? 20 : 6;
  824. opt._initialChunkSize = cfgFile.chunkSize();
  825. opt._minChunkSize = cfgFile.minChunkSize();
  826. opt._maxChunkSize = cfgFile.maxChunkSize();
  827. opt._targetChunkUploadDuration = cfgFile.targetChunkUploadDuration();
  828. opt.fillFromEnvironmentVariables();
  829. opt.verifyChunkSizes();
  830. return opt;
  831. }
  832. void Folder::setDirtyNetworkLimits()
  833. {
  834. ConfigFile cfg;
  835. int downloadLimit = -75; // 75%
  836. int useDownLimit = cfg.useDownloadLimit();
  837. if (useDownLimit >= 1) {
  838. downloadLimit = cfg.downloadLimit() * 1000;
  839. } else if (useDownLimit == 0) {
  840. downloadLimit = 0;
  841. }
  842. int uploadLimit = -75; // 75%
  843. int useUpLimit = cfg.useUploadLimit();
  844. if (useUpLimit >= 1) {
  845. uploadLimit = cfg.uploadLimit() * 1000;
  846. } else if (useUpLimit == 0) {
  847. uploadLimit = 0;
  848. }
  849. _engine->setNetworkLimits(uploadLimit, downloadLimit);
  850. }
  851. void Folder::slotSyncError(const QString &message, ErrorCategory category)
  852. {
  853. if (!_silenceErrorsUntilNextSync) {
  854. _syncResult.appendErrorString(message);
  855. emit ProgressDispatcher::instance()->syncError(alias(), message, category);
  856. }
  857. }
  858. void Folder::slotAddErrorToGui(SyncFileItem::Status status, const QString &errorMessage, const QString &subject, ErrorCategory category)
  859. {
  860. emit ProgressDispatcher::instance()->addErrorToGui(alias(), status, errorMessage, subject, category);
  861. }
  862. void Folder::slotSyncStarted()
  863. {
  864. qCInfo(lcFolder) << "#### Propagation start ####################################################";
  865. _syncResult.setStatus(SyncResult::SyncRunning);
  866. emit syncStateChange();
  867. }
  868. void Folder::slotSyncFinished(bool success)
  869. {
  870. qCInfo(lcFolder) << "Client version" << qPrintable(Theme::instance()->version())
  871. << " Qt" << qVersion()
  872. << " SSL " << QSslSocket::sslLibraryVersionString().toUtf8().data()
  873. ;
  874. bool syncError = !_syncResult.errorStrings().isEmpty();
  875. if (syncError) {
  876. qCWarning(lcFolder) << "SyncEngine finished with ERROR";
  877. } else {
  878. qCInfo(lcFolder) << "SyncEngine finished without problem.";
  879. }
  880. _fileLog->finish();
  881. showSyncResultPopup();
  882. auto anotherSyncNeeded = _engine->isAnotherSyncNeeded();
  883. if (syncError) {
  884. _syncResult.setStatus(SyncResult::Error);
  885. if (_silenceErrorsUntilNextSync) {
  886. _syncResult.setStatus(SyncResult::Status::Success);
  887. }
  888. } else if (_syncResult.foundFilesNotSynced()) {
  889. _syncResult.setStatus(SyncResult::Problem);
  890. } else if (_definition.paused) {
  891. // Maybe the sync was terminated because the user paused the folder
  892. _syncResult.setStatus(SyncResult::Paused);
  893. } else {
  894. _syncResult.setStatus(SyncResult::Success);
  895. }
  896. // Count the number of syncs that have failed in a row.
  897. if (_syncResult.status() == SyncResult::Success
  898. || _syncResult.status() == SyncResult::Problem) {
  899. _consecutiveFailingSyncs = 0;
  900. } else {
  901. _consecutiveFailingSyncs++;
  902. qCInfo(lcFolder) << "the last" << _consecutiveFailingSyncs << "syncs failed";
  903. }
  904. if (_syncResult.status() == SyncResult::Success && success) {
  905. // Clear the white list as all the folders that should be on that list are sync-ed
  906. journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, QStringList());
  907. }
  908. if ((_syncResult.status() == SyncResult::Success
  909. || _syncResult.status() == SyncResult::Problem)
  910. && success) {
  911. if (_engine->lastLocalDiscoveryStyle() == LocalDiscoveryStyle::FilesystemOnly) {
  912. _timeSinceLastFullLocalDiscovery.start();
  913. }
  914. }
  915. emit syncStateChange();
  916. // The syncFinished result that is to be triggered here makes the folderman
  917. // clear the current running sync folder marker.
  918. // Lets wait a bit to do that because, as long as this marker is not cleared,
  919. // file system change notifications are ignored for that folder. And it takes
  920. // some time under certain conditions to make the file system notifications
  921. // all come in.
  922. QTimer::singleShot(200, this, &Folder::slotEmitFinishedDelayed);
  923. _lastSyncDuration = std::chrono::milliseconds(_timeSinceLastSyncStart.elapsed());
  924. _timeSinceLastSyncDone.start();
  925. // Increment the follow-up sync counter if necessary.
  926. if (anotherSyncNeeded == ImmediateFollowUp) {
  927. _consecutiveFollowUpSyncs++;
  928. qCInfo(lcFolder) << "another sync was requested by the finished sync, this has"
  929. << "happened" << _consecutiveFollowUpSyncs << "times";
  930. } else {
  931. _consecutiveFollowUpSyncs = 0;
  932. }
  933. // Maybe force a follow-up sync to take place, but only a couple of times.
  934. if (anotherSyncNeeded == ImmediateFollowUp && _consecutiveFollowUpSyncs <= 3) {
  935. // Sometimes another sync is requested because a local file is still
  936. // changing, so wait at least a small amount of time before syncing
  937. // the folder again.
  938. scheduleThisFolderSoon();
  939. }
  940. }
  941. void Folder::slotEmitFinishedDelayed()
  942. {
  943. emit syncFinished(_syncResult);
  944. // Immediately check the etag again if there was some sync activity.
  945. if ((_syncResult.status() == SyncResult::Success
  946. || _syncResult.status() == SyncResult::Problem)
  947. && (_syncResult.firstItemDeleted()
  948. || _syncResult.firstItemNew()
  949. || _syncResult.firstItemRenamed()
  950. || _syncResult.firstItemUpdated()
  951. || _syncResult.firstNewConflictItem())) {
  952. slotRunEtagJob();
  953. }
  954. }
  955. // the progress comes without a folder and the valid path set. Add that here
  956. // and hand the result over to the progress dispatcher.
  957. void Folder::slotTransmissionProgress(const ProgressInfo &pi)
  958. {
  959. emit progressInfo(pi);
  960. ProgressDispatcher::instance()->setProgressInfo(alias(), pi);
  961. }
  962. // a item is completed: count the errors and forward to the ProgressDispatcher
  963. void Folder::slotItemCompleted(const SyncFileItemPtr &item, ErrorCategory errorCategory)
  964. {
  965. if (item->_instruction == CSYNC_INSTRUCTION_NONE || item->_instruction == CSYNC_INSTRUCTION_UPDATE_METADATA) {
  966. // We only care about the updates that deserve to be shown in the UI
  967. return;
  968. }
  969. if (_silenceErrorsUntilNextSync
  970. && (item->_status != SyncFileItem::Status::Success && item->_status != SyncFileItem::Status::NoStatus)) {
  971. item->_errorString.clear();
  972. item->_status = SyncFileItem::Status::SoftError;
  973. }
  974. _syncResult.processCompletedItem(item);
  975. _fileLog->logItem(*item);
  976. emit ProgressDispatcher::instance()->itemCompleted(alias(), item, errorCategory);
  977. }
  978. void Folder::slotNewBigFolderDiscovered(const QString &newF, bool isExternal)
  979. {
  980. auto newFolder = newF;
  981. if (!newFolder.endsWith(QLatin1Char('/'))) {
  982. newFolder += QLatin1Char('/');
  983. }
  984. auto journal = journalDb();
  985. // Add the entry to the blacklist if it is neither in the blacklist or whitelist already
  986. bool ok1 = false;
  987. bool ok2 = false;
  988. auto blacklist = journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok1);
  989. auto whitelist = journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, &ok2);
  990. if (ok1 && ok2 && !blacklist.contains(newFolder) && !whitelist.contains(newFolder)) {
  991. blacklist.append(newFolder);
  992. journal->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, blacklist);
  993. }
  994. // And add the entry to the undecided list and signal the UI
  995. auto undecidedList = journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok1);
  996. if (ok1) {
  997. if (!undecidedList.contains(newFolder)) {
  998. undecidedList.append(newFolder);
  999. journal->setSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, undecidedList);
  1000. emit newBigFolderDiscovered(newFolder);
  1001. }
  1002. QString message = !isExternal ? (tr("A new folder larger than %1 MB has been added: %2.\n")
  1003. .arg(ConfigFile().newBigFolderSizeLimit().second)
  1004. .arg(newF))
  1005. : (tr("A folder from an external storage has been added.\n"));
  1006. message += tr("Please go in the settings to select it if you wish to download it.");
  1007. auto logger = Logger::instance();
  1008. logger->postOptionalGuiLog(Theme::instance()->appNameGUI(), message);
  1009. }
  1010. }
  1011. void Folder::slotLogPropagationStart()
  1012. {
  1013. _fileLog->logLap("Propagation starts");
  1014. }
  1015. void Folder::slotScheduleThisFolder()
  1016. {
  1017. FolderMan::instance()->scheduleFolder(this);
  1018. }
  1019. void Folder::slotNextSyncFullLocalDiscovery()
  1020. {
  1021. _timeSinceLastFullLocalDiscovery.invalidate();
  1022. }
  1023. void Folder::setSilenceErrorsUntilNextSync(bool silenceErrors)
  1024. {
  1025. _silenceErrorsUntilNextSync = silenceErrors;
  1026. }
  1027. void Folder::schedulePathForLocalDiscovery(const QString &relativePath)
  1028. {
  1029. _localDiscoveryTracker->addTouchedPath(relativePath.toUtf8());
  1030. }
  1031. void Folder::slotFolderConflicts(const QString &folder, const QStringList &conflictPaths)
  1032. {
  1033. if (folder != _definition.alias)
  1034. return;
  1035. auto &r = _syncResult;
  1036. // If the number of conflicts is too low, adjust it upwards
  1037. if (conflictPaths.size() > r.numNewConflictItems() + r.numOldConflictItems())
  1038. r.setNumOldConflictItems(conflictPaths.size() - r.numNewConflictItems());
  1039. }
  1040. void Folder::warnOnNewExcludedItem(const SyncJournalFileRecord &record, const QStringRef &path)
  1041. {
  1042. // Never warn for items in the database
  1043. if (record.isValid())
  1044. return;
  1045. // Don't warn for items that no longer exist.
  1046. // Note: This assumes we're getting file watcher notifications
  1047. // for folders only on creation and deletion - if we got a notification
  1048. // on content change that would create spurious warnings.
  1049. QFileInfo fi(_canonicalLocalPath + path);
  1050. if (!fi.exists())
  1051. return;
  1052. bool ok = false;
  1053. auto blacklist = _journal.getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok);
  1054. if (!ok)
  1055. return;
  1056. if (!blacklist.contains(path + "/"))
  1057. return;
  1058. const auto message = fi.isDir()
  1059. ? tr("The folder %1 was created but was excluded from synchronization previously. "
  1060. "Data inside it will not be synchronized.")
  1061. .arg(fi.filePath())
  1062. : tr("The file %1 was created but was excluded from synchronization previously. "
  1063. "It will not be synchronized.")
  1064. .arg(fi.filePath());
  1065. Logger::instance()->postOptionalGuiLog(Theme::instance()->appNameGUI(), message);
  1066. }
  1067. void Folder::slotWatcherUnreliable(const QString &message)
  1068. {
  1069. qCWarning(lcFolder) << "Folder watcher for" << path() << "became unreliable:" << message;
  1070. auto fullMessage =
  1071. tr("Changes in synchronized folders could not be tracked reliably.\n"
  1072. "\n"
  1073. "This means that the synchronization client might not upload local changes "
  1074. "immediately and will instead only scan for local changes and upload them "
  1075. "occasionally (every two hours by default).\n"
  1076. "\n"
  1077. "%1").arg(message);
  1078. Logger::instance()->postGuiLog(Theme::instance()->appNameGUI(), fullMessage);
  1079. }
  1080. void Folder::slotHydrationStarts()
  1081. {
  1082. // Abort any running full sync run and reschedule
  1083. if (_engine->isSyncRunning()) {
  1084. setSilenceErrorsUntilNextSync(true);
  1085. slotTerminateSync();
  1086. scheduleThisFolderSoon();
  1087. // TODO: This sets the sync state to AbortRequested on done, we don't want that
  1088. }
  1089. // Let everyone know we're syncing
  1090. _syncResult.reset();
  1091. _syncResult.setStatus(SyncResult::SyncRunning);
  1092. emit syncStarted();
  1093. emit syncStateChange();
  1094. }
  1095. void Folder::slotHydrationDone()
  1096. {
  1097. // emit signal to update ui and reschedule normal syncs if necessary
  1098. _syncResult.setStatus(SyncResult::Success);
  1099. emit syncFinished(_syncResult);
  1100. emit syncStateChange();
  1101. }
  1102. void Folder::slotCapabilitiesChanged()
  1103. {
  1104. if (_accountState->account()->capabilities().filesLockAvailable()) {
  1105. connect(_folderWatcher.data(), &FolderWatcher::filesLockReleased, this, &Folder::slotFilesLockReleased, Qt::UniqueConnection);
  1106. }
  1107. }
  1108. void Folder::scheduleThisFolderSoon()
  1109. {
  1110. if (!_scheduleSelfTimer.isActive()) {
  1111. _scheduleSelfTimer.start();
  1112. }
  1113. }
  1114. void Folder::acceptInvalidFileName(const QString &filePath)
  1115. {
  1116. _engine->addAcceptedInvalidFileName(filePath);
  1117. }
  1118. void Folder::acceptCaseClashConflictFileName(const QString &filePath)
  1119. {
  1120. qCInfo(lcFolder) << "going to delete case clash conflict record" << filePath;
  1121. _journal.deleteCaseClashConflictByPathRecord(filePath);
  1122. qCInfo(lcFolder) << "going to delete" << path() + filePath;
  1123. FileSystem::remove(path() + filePath);
  1124. }
  1125. void Folder::setSaveBackwardsCompatible(bool save)
  1126. {
  1127. _saveBackwardsCompatible = save;
  1128. }
  1129. void Folder::registerFolderWatcher()
  1130. {
  1131. if (_folderWatcher)
  1132. return;
  1133. if (!QDir(path()).exists())
  1134. return;
  1135. _folderWatcher.reset(new FolderWatcher(this));
  1136. connect(_folderWatcher.data(), &FolderWatcher::pathChanged,
  1137. this, [this](const QString &path) { slotWatchedPathChanged(path, Folder::ChangeReason::Other); });
  1138. connect(_folderWatcher.data(), &FolderWatcher::lostChanges,
  1139. this, &Folder::slotNextSyncFullLocalDiscovery);
  1140. connect(_folderWatcher.data(), &FolderWatcher::becameUnreliable,
  1141. this, &Folder::slotWatcherUnreliable);
  1142. if (_accountState->account()->capabilities().filesLockAvailable()) {
  1143. connect(_folderWatcher.data(), &FolderWatcher::filesLockReleased, this, &Folder::slotFilesLockReleased);
  1144. }
  1145. _folderWatcher->init(path());
  1146. _folderWatcher->startNotificatonTest(path() + QLatin1String(".nextcloudsync.log"));
  1147. }
  1148. bool Folder::virtualFilesEnabled() const
  1149. {
  1150. return _definition.virtualFilesMode != Vfs::Off && !isVfsOnOffSwitchPending();
  1151. }
  1152. void Folder::slotAboutToRemoveAllFiles(SyncFileItem::Direction dir, std::function<void(bool)> callback)
  1153. {
  1154. ConfigFile cfgFile;
  1155. if (!cfgFile.promptDeleteFiles()) {
  1156. callback(false);
  1157. return;
  1158. }
  1159. const QString msg = dir == SyncFileItem::Down ? tr("All files in the sync folder \"%1\" folder were deleted on the server.\n"
  1160. "These deletes will be synchronized to your local sync folder, making such files "
  1161. "unavailable unless you have a right to restore. \n"
  1162. "If you decide to restore the files, they will be re-synced with the server if you have rights to do so.\n"
  1163. "If you decide to delete the files, they will be unavailable to you, unless you are the owner.")
  1164. : tr("All the files in your local sync folder \"%1\" were deleted. These deletes will be "
  1165. "synchronized with your server, making such files unavailable unless restored.\n"
  1166. "Are you sure you want to sync those actions with the server?\n"
  1167. "If this was an accident and you decide to keep your files, they will be re-synced from the server.");
  1168. auto msgBox = new QMessageBox(QMessageBox::Warning, tr("Remove All Files?"),
  1169. msg.arg(shortGuiLocalPath()), QMessageBox::NoButton);
  1170. msgBox->setAttribute(Qt::WA_DeleteOnClose);
  1171. msgBox->setWindowFlags(msgBox->windowFlags() | Qt::WindowStaysOnTopHint);
  1172. msgBox->addButton(tr("Remove all files"), QMessageBox::DestructiveRole);
  1173. QPushButton *keepBtn = msgBox->addButton(tr("Keep files"), QMessageBox::AcceptRole);
  1174. bool oldPaused = syncPaused();
  1175. setSyncPaused(true);
  1176. connect(msgBox, &QMessageBox::finished, this, [msgBox, keepBtn, callback, oldPaused, this] {
  1177. const bool cancel = msgBox->clickedButton() == keepBtn;
  1178. callback(cancel);
  1179. if (cancel) {
  1180. FileSystem::setFolderMinimumPermissions(path());
  1181. journalDb()->clearFileTable();
  1182. _lastEtag.clear();
  1183. slotScheduleThisFolder();
  1184. }
  1185. setSyncPaused(oldPaused);
  1186. });
  1187. connect(this, &Folder::destroyed, msgBox, &QMessageBox::deleteLater);
  1188. msgBox->open();
  1189. }
  1190. void Folder::removeLocalE2eFiles()
  1191. {
  1192. qCDebug(lcFolder) << "Removing local E2EE files";
  1193. const QDir folderRootDir(path());
  1194. QStringList e2eFoldersToBlacklist;
  1195. const auto couldGetFiles = _journal.getFilesBelowPath("", [this, &e2eFoldersToBlacklist, &folderRootDir](const SyncJournalFileRecord &rec) {
  1196. // We only want to add the root-most encrypted folder to the blacklist
  1197. if (rec.isValid() && rec.isE2eEncrypted() && rec.isDirectory()) {
  1198. QDir pathDir(_canonicalLocalPath + rec.path());
  1199. bool parentPathEncrypted = false;
  1200. while (pathDir.cdUp() && pathDir != folderRootDir) {
  1201. SyncJournalFileRecord dirRec;
  1202. const auto currentCanonicalPath = pathDir.canonicalPath();
  1203. if (!_journal.getFileRecord(currentCanonicalPath, &dirRec)) {
  1204. qCWarning(lcFolder) << "Failed to get file record for" << currentCanonicalPath;
  1205. }
  1206. if (dirRec.isE2eEncrypted()) {
  1207. parentPathEncrypted = true;
  1208. break;
  1209. }
  1210. }
  1211. if (!parentPathEncrypted) {
  1212. const auto pathAdjusted = rec._path.endsWith('/') ? rec._path : QString(rec._path + QStringLiteral("/"));
  1213. e2eFoldersToBlacklist.append(pathAdjusted);
  1214. }
  1215. }
  1216. });
  1217. if (!couldGetFiles) {
  1218. qCWarning(lcFolder) << "Could not fetch E2EE folders to blacklist in this folder:" << path();
  1219. return;
  1220. } else if (e2eFoldersToBlacklist.isEmpty()) {
  1221. qCWarning(lcFolder) << "No E2EE folders found at path" << path();
  1222. return;
  1223. }
  1224. qCInfo(lcFolder) << "About to blacklist: " << e2eFoldersToBlacklist;
  1225. bool ok = false;
  1226. const auto existingBlacklist = _journal.getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok);
  1227. Q_ASSERT(ok);
  1228. const auto existingBlacklistSet = existingBlacklist.toSet();
  1229. auto expandedBlacklistSet = existingBlacklist.toSet();
  1230. for (const auto &path : qAsConst(e2eFoldersToBlacklist)) {
  1231. expandedBlacklistSet.insert(path);
  1232. }
  1233. // same as in void FolderStatusModel::slotApplySelectiveSync()
  1234. // only start sync if blackList has changed
  1235. // database lists will get updated during discovery
  1236. const auto changes = (existingBlacklistSet - expandedBlacklistSet) + (expandedBlacklistSet - existingBlacklistSet);
  1237. _journal.setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, expandedBlacklistSet.values());
  1238. _journal.setSelectiveSyncList(SyncJournalDb::SelectiveSyncE2eFoldersToRemoveFromBlacklist, changes.values());
  1239. if (!changes.isEmpty()) {
  1240. _journal.setSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, QStringList());
  1241. if (isBusy()) {
  1242. slotTerminateSync();
  1243. }
  1244. for (const auto &it : changes) {
  1245. _journal.schedulePathForRemoteDiscovery(it);
  1246. schedulePathForLocalDiscovery(it);
  1247. }
  1248. FolderMan::instance()->scheduleFolderForImmediateSync(this);
  1249. }
  1250. }
  1251. QString Folder::fileFromLocalPath(const QString &localPath) const
  1252. {
  1253. return localPath.mid(cleanPath().length() + 1);
  1254. }
  1255. void FolderDefinition::save(QSettings &settings, const FolderDefinition &folder)
  1256. {
  1257. settings.setValue(QLatin1String("localPath"), folder.localPath);
  1258. settings.setValue(QLatin1String("journalPath"), folder.journalPath);
  1259. settings.setValue(QLatin1String("targetPath"), folder.targetPath);
  1260. settings.setValue(QLatin1String("paused"), folder.paused);
  1261. settings.setValue(QLatin1String("ignoreHiddenFiles"), folder.ignoreHiddenFiles);
  1262. settings.setValue(QStringLiteral("virtualFilesMode"), Vfs::modeToString(folder.virtualFilesMode));
  1263. // Ensure new vfs modes won't be attempted by older clients
  1264. if (folder.virtualFilesMode == Vfs::WindowsCfApi) {
  1265. settings.setValue(QLatin1String(versionC), 3);
  1266. } else {
  1267. settings.setValue(QLatin1String(versionC), 2);
  1268. }
  1269. // Happens only on Windows when the explorer integration is enabled.
  1270. if (!folder.navigationPaneClsid.isNull())
  1271. settings.setValue(QLatin1String("navigationPaneClsid"), folder.navigationPaneClsid);
  1272. else
  1273. settings.remove(QLatin1String("navigationPaneClsid"));
  1274. }
  1275. bool FolderDefinition::load(QSettings &settings, const QString &alias,
  1276. FolderDefinition *folder)
  1277. {
  1278. folder->alias = FolderMan::unescapeAlias(alias);
  1279. folder->localPath = settings.value(QLatin1String("localPath")).toString();
  1280. folder->journalPath = settings.value(QLatin1String("journalPath")).toString();
  1281. folder->targetPath = settings.value(QLatin1String("targetPath")).toString();
  1282. folder->paused = settings.value(QLatin1String("paused")).toBool();
  1283. folder->ignoreHiddenFiles = settings.value(QLatin1String("ignoreHiddenFiles"), QVariant(true)).toBool();
  1284. folder->navigationPaneClsid = settings.value(QLatin1String("navigationPaneClsid")).toUuid();
  1285. folder->virtualFilesMode = Vfs::Off;
  1286. QString vfsModeString = settings.value(QStringLiteral("virtualFilesMode")).toString();
  1287. if (!vfsModeString.isEmpty()) {
  1288. if (auto mode = Vfs::modeFromString(vfsModeString)) {
  1289. folder->virtualFilesMode = *mode;
  1290. } else {
  1291. qCWarning(lcFolder) << "Unknown virtualFilesMode:" << vfsModeString << "assuming 'off'";
  1292. }
  1293. } else {
  1294. if (settings.value(QLatin1String("usePlaceholders")).toBool()) {
  1295. folder->virtualFilesMode = Vfs::WithSuffix;
  1296. folder->upgradeVfsMode = true; // maybe winvfs is available?
  1297. }
  1298. }
  1299. // Old settings can contain paths with native separators. In the rest of the
  1300. // code we assume /, so clean it up now.
  1301. folder->localPath = prepareLocalPath(folder->localPath);
  1302. // Target paths also have a convention
  1303. folder->targetPath = prepareTargetPath(folder->targetPath);
  1304. return true;
  1305. }
  1306. QString FolderDefinition::prepareLocalPath(const QString &path)
  1307. {
  1308. QString p = QDir::fromNativeSeparators(path);
  1309. if (!p.endsWith(QLatin1Char('/'))) {
  1310. p.append(QLatin1Char('/'));
  1311. }
  1312. return p;
  1313. }
  1314. QString FolderDefinition::prepareTargetPath(const QString &path)
  1315. {
  1316. QString p = path;
  1317. if (p.endsWith(QLatin1Char('/'))) {
  1318. p.chop(1);
  1319. }
  1320. // Doing this second ensures the empty string or "/" come
  1321. // out as "/".
  1322. if (!p.startsWith(QLatin1Char('/'))) {
  1323. p.prepend(QLatin1Char('/'));
  1324. }
  1325. return p;
  1326. }
  1327. QString FolderDefinition::absoluteJournalPath() const
  1328. {
  1329. return QDir(localPath).filePath(journalPath);
  1330. }
  1331. QString FolderDefinition::defaultJournalPath(AccountPtr account)
  1332. {
  1333. return SyncJournalDb::makeDbName(localPath, account->url(), targetPath, account->credentials()->user());
  1334. }
  1335. } // namespace OCC