CleanPreviewsBackgroundJob.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Repair\Owncloud;
  8. use OCP\AppFramework\Utility\ITimeFactory;
  9. use OCP\BackgroundJob\IJobList;
  10. use OCP\BackgroundJob\QueuedJob;
  11. use OCP\Files\Folder;
  12. use OCP\Files\IRootFolder;
  13. use OCP\Files\NotFoundException;
  14. use OCP\Files\NotPermittedException;
  15. use OCP\IUserManager;
  16. use Psr\Log\LoggerInterface;
  17. class CleanPreviewsBackgroundJob extends QueuedJob {
  18. public function __construct(
  19. private IRootFolder $rootFolder,
  20. private LoggerInterface $logger,
  21. private IJobList $jobList,
  22. ITimeFactory $timeFactory,
  23. private IUserManager $userManager,
  24. ) {
  25. parent::__construct($timeFactory);
  26. }
  27. public function run($arguments) {
  28. $uid = $arguments['uid'];
  29. if (!$this->userManager->userExists($uid)) {
  30. $this->logger->info('User no longer exists, skip user ' . $uid);
  31. return;
  32. }
  33. $this->logger->info('Started preview cleanup for ' . $uid);
  34. $empty = $this->cleanupPreviews($uid);
  35. if (!$empty) {
  36. $this->jobList->add(self::class, ['uid' => $uid]);
  37. $this->logger->info('New preview cleanup scheduled for ' . $uid);
  38. } else {
  39. $this->logger->info('Preview cleanup done for ' . $uid);
  40. }
  41. }
  42. /**
  43. * @param string $uid
  44. */
  45. private function cleanupPreviews($uid): bool {
  46. try {
  47. $userFolder = $this->rootFolder->getUserFolder($uid);
  48. } catch (NotFoundException $e) {
  49. return true;
  50. }
  51. $userRoot = $userFolder->getParent();
  52. try {
  53. /** @var Folder $thumbnailFolder */
  54. $thumbnailFolder = $userRoot->get('thumbnails');
  55. } catch (NotFoundException $e) {
  56. return true;
  57. }
  58. $thumbnails = $thumbnailFolder->getDirectoryListing();
  59. $start = $this->time->getTime();
  60. foreach ($thumbnails as $thumbnail) {
  61. try {
  62. $thumbnail->delete();
  63. } catch (NotPermittedException $e) {
  64. // Ignore
  65. }
  66. if (($this->time->getTime() - $start) > 15) {
  67. return false;
  68. }
  69. }
  70. try {
  71. $thumbnailFolder->delete();
  72. } catch (NotPermittedException $e) {
  73. // Ignore
  74. }
  75. return true;
  76. }
  77. }