Scanner.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Files\Cache;
  8. use Doctrine\DBAL\Exception;
  9. use OC\Files\Storage\Wrapper\Encryption;
  10. use OC\Files\Storage\Wrapper\Jail;
  11. use OC\Hooks\BasicEmitter;
  12. use OC\SystemConfig;
  13. use OCP\Files\Cache\IScanner;
  14. use OCP\Files\ForbiddenException;
  15. use OCP\Files\NotFoundException;
  16. use OCP\Files\Storage\ILockingStorage;
  17. use OCP\Files\Storage\IReliableEtagStorage;
  18. use OCP\IDBConnection;
  19. use OCP\Lock\ILockingProvider;
  20. use Psr\Log\LoggerInterface;
  21. /**
  22. * Class Scanner
  23. *
  24. * Hooks available in scope \OC\Files\Cache\Scanner:
  25. * - scanFile(string $path, string $storageId)
  26. * - scanFolder(string $path, string $storageId)
  27. * - postScanFile(string $path, string $storageId)
  28. * - postScanFolder(string $path, string $storageId)
  29. *
  30. * @package OC\Files\Cache
  31. */
  32. class Scanner extends BasicEmitter implements IScanner {
  33. /**
  34. * @var \OC\Files\Storage\Storage $storage
  35. */
  36. protected $storage;
  37. /**
  38. * @var string $storageId
  39. */
  40. protected $storageId;
  41. /**
  42. * @var \OC\Files\Cache\Cache $cache
  43. */
  44. protected $cache;
  45. /**
  46. * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache
  47. */
  48. protected $cacheActive;
  49. /**
  50. * @var bool $useTransactions whether to use transactions
  51. */
  52. protected $useTransactions = true;
  53. /**
  54. * @var \OCP\Lock\ILockingProvider
  55. */
  56. protected $lockingProvider;
  57. protected IDBConnection $connection;
  58. public function __construct(\OC\Files\Storage\Storage $storage) {
  59. $this->storage = $storage;
  60. $this->storageId = $this->storage->getId();
  61. $this->cache = $storage->getCache();
  62. /** @var SystemConfig $config */
  63. $config = \OC::$server->get(SystemConfig::class);
  64. $this->cacheActive = !$config->getValue('filesystem_cache_readonly', false);
  65. $this->useTransactions = !$config->getValue('filescanner_no_transactions', false);
  66. $this->lockingProvider = \OC::$server->get(ILockingProvider::class);
  67. $this->connection = \OC::$server->get(IDBConnection::class);
  68. }
  69. /**
  70. * Whether to wrap the scanning of a folder in a database transaction
  71. * On default transactions are used
  72. *
  73. * @param bool $useTransactions
  74. */
  75. public function setUseTransactions($useTransactions) {
  76. $this->useTransactions = $useTransactions;
  77. }
  78. /**
  79. * get all the metadata of a file or folder
  80. * *
  81. *
  82. * @param string $path
  83. * @return array|null an array of metadata of the file
  84. */
  85. protected function getData($path) {
  86. $data = $this->storage->getMetaData($path);
  87. if (is_null($data)) {
  88. \OC::$server->get(LoggerInterface::class)->debug("!!! Path '$path' is not accessible or present !!!", ['app' => 'core']);
  89. }
  90. return $data;
  91. }
  92. /**
  93. * scan a single file and store it in the cache
  94. *
  95. * @param string $file
  96. * @param int $reuseExisting
  97. * @param int $parentId
  98. * @param array|null|false $cacheData existing data in the cache for the file to be scanned
  99. * @param bool $lock set to false to disable getting an additional read lock during scanning
  100. * @param null $data the metadata for the file, as returned by the storage
  101. * @return array|null an array of metadata of the scanned file
  102. * @throws \OCP\Lock\LockedException
  103. */
  104. public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true, $data = null) {
  105. if ($file !== '') {
  106. try {
  107. $this->storage->verifyPath(dirname($file), basename($file));
  108. } catch (\Exception $e) {
  109. return null;
  110. }
  111. }
  112. // only proceed if $file is not a partial file, blacklist is handled by the storage
  113. if (!self::isPartialFile($file)) {
  114. // acquire a lock
  115. if ($lock) {
  116. if ($this->storage->instanceOfStorage(ILockingStorage::class)) {
  117. $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  118. }
  119. }
  120. try {
  121. $data = $data ?? $this->getData($file);
  122. } catch (ForbiddenException $e) {
  123. if ($lock) {
  124. if ($this->storage->instanceOfStorage(ILockingStorage::class)) {
  125. $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  126. }
  127. }
  128. return null;
  129. }
  130. try {
  131. if ($data) {
  132. // pre-emit only if it was a file. By that we avoid counting/treating folders as files
  133. if ($data['mimetype'] !== 'httpd/unix-directory') {
  134. $this->emit('\OC\Files\Cache\Scanner', 'scanFile', [$file, $this->storageId]);
  135. \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', ['path' => $file, 'storage' => $this->storageId]);
  136. }
  137. $parent = dirname($file);
  138. if ($parent === '.' || $parent === '/') {
  139. $parent = '';
  140. }
  141. if ($parentId === -1) {
  142. $parentId = $this->cache->getParentId($file);
  143. }
  144. // scan the parent if it's not in the cache (id -1) and the current file is not the root folder
  145. if ($file && $parentId === -1) {
  146. $parentData = $this->scanFile($parent);
  147. if (!$parentData) {
  148. return null;
  149. }
  150. $parentId = $parentData['fileid'];
  151. }
  152. if ($parent) {
  153. $data['parent'] = $parentId;
  154. }
  155. if (is_null($cacheData)) {
  156. /** @var CacheEntry $cacheData */
  157. $cacheData = $this->cache->get($file);
  158. }
  159. if ($cacheData && $reuseExisting && isset($cacheData['fileid'])) {
  160. // prevent empty etag
  161. $etag = empty($cacheData['etag']) ? $data['etag'] : $cacheData['etag'];
  162. $fileId = $cacheData['fileid'];
  163. $data['fileid'] = $fileId;
  164. // only reuse data if the file hasn't explicitly changed
  165. $mtimeUnchanged = isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime'];
  166. // if the folder is marked as unscanned, never reuse etags
  167. if ($mtimeUnchanged && $cacheData['size'] !== -1) {
  168. $data['mtime'] = $cacheData['mtime'];
  169. if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) {
  170. $data['size'] = $cacheData['size'];
  171. }
  172. if ($reuseExisting & self::REUSE_ETAG && !$this->storage->instanceOfStorage(IReliableEtagStorage::class)) {
  173. $data['etag'] = $etag;
  174. }
  175. }
  176. // we only updated unencrypted_size if it's already set
  177. if ($cacheData['unencrypted_size'] === 0) {
  178. unset($data['unencrypted_size']);
  179. }
  180. // Only update metadata that has changed
  181. // i.e. get all the values in $data that are not present in the cache already
  182. $newData = $this->array_diff_assoc_multi($data, $cacheData->getData());
  183. // make it known to the caller that etag has been changed and needs propagation
  184. if (isset($newData['etag'])) {
  185. $data['etag_changed'] = true;
  186. }
  187. } else {
  188. // we only updated unencrypted_size if it's already set
  189. unset($data['unencrypted_size']);
  190. $newData = $data;
  191. $fileId = -1;
  192. }
  193. if (!empty($newData)) {
  194. // Reset the checksum if the data has changed
  195. $newData['checksum'] = '';
  196. $newData['parent'] = $parentId;
  197. $data['fileid'] = $this->addToCache($file, $newData, $fileId);
  198. }
  199. $data['oldSize'] = ($cacheData && isset($cacheData['size'])) ? $cacheData['size'] : 0;
  200. if ($cacheData && isset($cacheData['encrypted'])) {
  201. $data['encrypted'] = $cacheData['encrypted'];
  202. }
  203. // post-emit only if it was a file. By that we avoid counting/treating folders as files
  204. if ($data['mimetype'] !== 'httpd/unix-directory') {
  205. $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', [$file, $this->storageId]);
  206. \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', ['path' => $file, 'storage' => $this->storageId]);
  207. }
  208. } else {
  209. $this->removeFromCache($file);
  210. }
  211. } catch (\Exception $e) {
  212. if ($lock) {
  213. if ($this->storage->instanceOfStorage(ILockingStorage::class)) {
  214. $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  215. }
  216. }
  217. throw $e;
  218. }
  219. // release the acquired lock
  220. if ($lock) {
  221. if ($this->storage->instanceOfStorage(ILockingStorage::class)) {
  222. $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  223. }
  224. }
  225. if ($data && !isset($data['encrypted'])) {
  226. $data['encrypted'] = false;
  227. }
  228. return $data;
  229. }
  230. return null;
  231. }
  232. protected function removeFromCache($path) {
  233. \OC_Hook::emit('Scanner', 'removeFromCache', ['file' => $path]);
  234. $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', [$path]);
  235. if ($this->cacheActive) {
  236. $this->cache->remove($path);
  237. }
  238. }
  239. /**
  240. * @param string $path
  241. * @param array $data
  242. * @param int $fileId
  243. * @return int the id of the added file
  244. */
  245. protected function addToCache($path, $data, $fileId = -1) {
  246. if (isset($data['scan_permissions'])) {
  247. $data['permissions'] = $data['scan_permissions'];
  248. }
  249. \OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]);
  250. $this->emit('\OC\Files\Cache\Scanner', 'addToCache', [$path, $this->storageId, $data, $fileId]);
  251. if ($this->cacheActive) {
  252. if ($fileId !== -1) {
  253. $this->cache->update($fileId, $data);
  254. return $fileId;
  255. } else {
  256. return $this->cache->insert($path, $data);
  257. }
  258. } else {
  259. return -1;
  260. }
  261. }
  262. /**
  263. * @param string $path
  264. * @param array $data
  265. * @param int $fileId
  266. */
  267. protected function updateCache($path, $data, $fileId = -1) {
  268. \OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]);
  269. $this->emit('\OC\Files\Cache\Scanner', 'updateCache', [$path, $this->storageId, $data]);
  270. if ($this->cacheActive) {
  271. if ($fileId !== -1) {
  272. $this->cache->update($fileId, $data);
  273. } else {
  274. $this->cache->put($path, $data);
  275. }
  276. }
  277. }
  278. /**
  279. * scan a folder and all it's children
  280. *
  281. * @param string $path
  282. * @param bool $recursive
  283. * @param int $reuse
  284. * @param bool $lock set to false to disable getting an additional read lock during scanning
  285. * @return array|null an array of the meta data of the scanned file or folder
  286. */
  287. public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
  288. if ($reuse === -1) {
  289. $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
  290. }
  291. if ($lock) {
  292. if ($this->storage->instanceOfStorage(ILockingStorage::class)) {
  293. $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
  294. $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  295. }
  296. }
  297. try {
  298. try {
  299. $data = $this->scanFile($path, $reuse, -1, null, $lock);
  300. if ($data && $data['mimetype'] === 'httpd/unix-directory') {
  301. $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock, $data['size']);
  302. $data['size'] = $size;
  303. }
  304. } catch (NotFoundException $e) {
  305. $this->removeFromCache($path);
  306. return null;
  307. }
  308. } finally {
  309. if ($lock) {
  310. if ($this->storage->instanceOfStorage(ILockingStorage::class)) {
  311. $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  312. $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
  313. }
  314. }
  315. }
  316. return $data;
  317. }
  318. /**
  319. * Compares $array1 against $array2 and returns all the values in $array1 that are not in $array2
  320. * Note this is a one-way check - i.e. we don't care about things that are in $array2 that aren't in $array1
  321. *
  322. * Supports multi-dimensional arrays
  323. * Also checks keys/indexes
  324. * Comparisons are strict just like array_diff_assoc
  325. * Order of keys/values does not matter
  326. *
  327. * @param array $array1
  328. * @param array $array2
  329. * @return array with the differences between $array1 and $array1
  330. * @throws \InvalidArgumentException if $array1 isn't an actual array
  331. *
  332. */
  333. protected function array_diff_assoc_multi(array $array1, array $array2) {
  334. $result = [];
  335. foreach ($array1 as $key => $value) {
  336. // if $array2 doesn't have the same key, that's a result
  337. if (!array_key_exists($key, $array2)) {
  338. $result[$key] = $value;
  339. continue;
  340. }
  341. // if $array2's value for the same key is different, that's a result
  342. if ($array2[$key] !== $value && !is_array($value)) {
  343. $result[$key] = $value;
  344. continue;
  345. }
  346. if (is_array($value)) {
  347. $nestedDiff = $this->array_diff_assoc_multi($value, $array2[$key]);
  348. if (!empty($nestedDiff)) {
  349. $result[$key] = $nestedDiff;
  350. continue;
  351. }
  352. }
  353. }
  354. return $result;
  355. }
  356. /**
  357. * Get the children currently in the cache
  358. *
  359. * @param int $folderId
  360. * @return array[]
  361. */
  362. protected function getExistingChildren($folderId) {
  363. $existingChildren = [];
  364. $children = $this->cache->getFolderContentsById($folderId);
  365. foreach ($children as $child) {
  366. $existingChildren[$child['name']] = $child;
  367. }
  368. return $existingChildren;
  369. }
  370. /**
  371. * scan all the files and folders in a folder
  372. *
  373. * @param string $path
  374. * @param bool|IScanner::SCAN_RECURSIVE_INCOMPLETE $recursive
  375. * @param int $reuse a combination of self::REUSE_*
  376. * @param int $folderId id for the folder to be scanned
  377. * @param bool $lock set to false to disable getting an additional read lock during scanning
  378. * @param int|float $oldSize the size of the folder before (re)scanning the children
  379. * @return int|float the size of the scanned folder or -1 if the size is unknown at this stage
  380. */
  381. protected function scanChildren(string $path, $recursive, int $reuse, int $folderId, bool $lock, int|float $oldSize, &$etagChanged = false) {
  382. if ($reuse === -1) {
  383. $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
  384. }
  385. $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', [$path, $this->storageId]);
  386. $size = 0;
  387. $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size, $etagChanged);
  388. foreach ($childQueue as $child => [$childId, $childSize]) {
  389. // "etag changed" propagates up, but not down, so we pass `false` to the children even if we already know that the etag of the current folder changed
  390. $childEtagChanged = false;
  391. $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock, $childSize, $childEtagChanged);
  392. $etagChanged |= $childEtagChanged;
  393. if ($childSize === -1) {
  394. $size = -1;
  395. } elseif ($size !== -1) {
  396. $size += $childSize;
  397. }
  398. }
  399. // for encrypted storages, we trigger a regular folder size calculation instead of using the calculated size
  400. // to make sure we also updated the unencrypted-size where applicable
  401. if ($this->storage->instanceOfStorage(Encryption::class)) {
  402. $this->cache->calculateFolderSize($path);
  403. } else {
  404. if ($this->cacheActive) {
  405. $updatedData = [];
  406. if ($oldSize !== $size) {
  407. $updatedData['size'] = $size;
  408. }
  409. if ($etagChanged) {
  410. $updatedData['etag'] = uniqid();
  411. }
  412. if ($updatedData) {
  413. $this->cache->update($folderId, $updatedData);
  414. }
  415. }
  416. }
  417. $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', [$path, $this->storageId]);
  418. return $size;
  419. }
  420. /**
  421. * @param bool|IScanner::SCAN_RECURSIVE_INCOMPLETE $recursive
  422. */
  423. private function handleChildren(string $path, $recursive, int $reuse, int $folderId, bool $lock, int|float &$size, bool &$etagChanged): array {
  424. // we put this in it's own function so it cleans up the memory before we start recursing
  425. $existingChildren = $this->getExistingChildren($folderId);
  426. $newChildren = iterator_to_array($this->storage->getDirectoryContent($path));
  427. if (count($existingChildren) === 0 && count($newChildren) === 0) {
  428. // no need to do a transaction
  429. return [];
  430. }
  431. if ($this->useTransactions) {
  432. $this->connection->beginTransaction();
  433. }
  434. $exceptionOccurred = false;
  435. $childQueue = [];
  436. $newChildNames = [];
  437. foreach ($newChildren as $fileMeta) {
  438. $permissions = $fileMeta['scan_permissions'] ?? $fileMeta['permissions'];
  439. if ($permissions === 0) {
  440. continue;
  441. }
  442. $originalFile = $fileMeta['name'];
  443. $file = trim(\OC\Files\Filesystem::normalizePath($originalFile), '/');
  444. if (trim($originalFile, '/') !== $file) {
  445. // encoding mismatch, might require compatibility wrapper
  446. \OC::$server->get(LoggerInterface::class)->debug('Scanner: Skipping non-normalized file name "' . $originalFile . '" in path "' . $path . '".', ['app' => 'core']);
  447. $this->emit('\OC\Files\Cache\Scanner', 'normalizedNameMismatch', [$path ? $path . '/' . $originalFile : $originalFile]);
  448. // skip this entry
  449. continue;
  450. }
  451. $newChildNames[] = $file;
  452. $child = $path ? $path . '/' . $file : $file;
  453. try {
  454. $existingData = $existingChildren[$file] ?? false;
  455. $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock, $fileMeta);
  456. if ($data) {
  457. if ($data['mimetype'] === 'httpd/unix-directory' && $recursive === self::SCAN_RECURSIVE) {
  458. $childQueue[$child] = [$data['fileid'], $data['size']];
  459. } elseif ($data['mimetype'] === 'httpd/unix-directory' && $recursive === self::SCAN_RECURSIVE_INCOMPLETE && $data['size'] === -1) {
  460. // only recurse into folders which aren't fully scanned
  461. $childQueue[$child] = [$data['fileid'], $data['size']];
  462. } elseif ($data['size'] === -1) {
  463. $size = -1;
  464. } elseif ($size !== -1) {
  465. $size += $data['size'];
  466. }
  467. if (isset($data['etag_changed']) && $data['etag_changed']) {
  468. $etagChanged = true;
  469. }
  470. }
  471. } catch (Exception $ex) {
  472. // might happen if inserting duplicate while a scanning
  473. // process is running in parallel
  474. // log and ignore
  475. if ($this->useTransactions) {
  476. $this->connection->rollback();
  477. $this->connection->beginTransaction();
  478. }
  479. \OC::$server->get(LoggerInterface::class)->debug('Exception while scanning file "' . $child . '"', [
  480. 'app' => 'core',
  481. 'exception' => $ex,
  482. ]);
  483. $exceptionOccurred = true;
  484. } catch (\OCP\Lock\LockedException $e) {
  485. if ($this->useTransactions) {
  486. $this->connection->rollback();
  487. }
  488. throw $e;
  489. }
  490. }
  491. $removedChildren = \array_diff(array_keys($existingChildren), $newChildNames);
  492. foreach ($removedChildren as $childName) {
  493. $child = $path ? $path . '/' . $childName : $childName;
  494. $this->removeFromCache($child);
  495. }
  496. if ($this->useTransactions) {
  497. $this->connection->commit();
  498. }
  499. if ($exceptionOccurred) {
  500. // It might happen that the parallel scan process has already
  501. // inserted mimetypes but those weren't available yet inside the transaction
  502. // To make sure to have the updated mime types in such cases,
  503. // we reload them here
  504. \OC::$server->getMimeTypeLoader()->reset();
  505. }
  506. return $childQueue;
  507. }
  508. /**
  509. * check if the file should be ignored when scanning
  510. * NOTE: files with a '.part' extension are ignored as well!
  511. * prevents unfinished put requests to be scanned
  512. *
  513. * @param string $file
  514. * @return boolean
  515. */
  516. public static function isPartialFile($file) {
  517. if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
  518. return true;
  519. }
  520. if (str_contains($file, '.part/')) {
  521. return true;
  522. }
  523. return false;
  524. }
  525. /**
  526. * walk over any folders that are not fully scanned yet and scan them
  527. */
  528. public function backgroundScan() {
  529. if ($this->storage->instanceOfStorage(Jail::class)) {
  530. // for jail storage wrappers (shares, groupfolders) we run the background scan on the source storage
  531. // this is mainly done because the jail wrapper doesn't implement `getIncomplete` (because it would be inefficient).
  532. //
  533. // Running the scan on the source storage might scan more than "needed", but the unscanned files outside the jail will
  534. // have to be scanned at some point anyway.
  535. $unJailedScanner = $this->storage->getUnjailedStorage()->getScanner();
  536. $unJailedScanner->backgroundScan();
  537. } else {
  538. if (!$this->cache->inCache('')) {
  539. // if the storage isn't in the cache yet, just scan the root completely
  540. $this->runBackgroundScanJob(function () {
  541. $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
  542. }, '');
  543. } else {
  544. $lastPath = null;
  545. // find any path marked as unscanned and run the scanner until no more paths are unscanned (or we get stuck)
  546. while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
  547. $this->runBackgroundScanJob(function () use ($path) {
  548. $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
  549. }, $path);
  550. // FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
  551. // to make this possible
  552. $lastPath = $path;
  553. }
  554. }
  555. }
  556. }
  557. protected function runBackgroundScanJob(callable $callback, $path) {
  558. try {
  559. $callback();
  560. \OC_Hook::emit('Scanner', 'correctFolderSize', ['path' => $path]);
  561. if ($this->cacheActive && $this->cache instanceof Cache) {
  562. $this->cache->correctFolderSize($path, null, true);
  563. }
  564. } catch (\OCP\Files\StorageInvalidException $e) {
  565. // skip unavailable storages
  566. } catch (\OCP\Files\StorageNotAvailableException $e) {
  567. // skip unavailable storages
  568. } catch (\OCP\Files\ForbiddenException $e) {
  569. // skip forbidden storages
  570. } catch (\OCP\Lock\LockedException $e) {
  571. // skip unavailable storages
  572. }
  573. }
  574. /**
  575. * Set whether the cache is affected by scan operations
  576. *
  577. * @param boolean $active The active state of the cache
  578. */
  579. public function setCacheActive($active) {
  580. $this->cacheActive = $active;
  581. }
  582. }