UploadCleanup.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\BackgroundJob;
  8. use OC\User\NoUserException;
  9. use OCP\AppFramework\Utility\ITimeFactory;
  10. use OCP\BackgroundJob\IJob;
  11. use OCP\BackgroundJob\IJobList;
  12. use OCP\BackgroundJob\TimedJob;
  13. use OCP\Files\File;
  14. use OCP\Files\Folder;
  15. use OCP\Files\IRootFolder;
  16. use OCP\Files\NotFoundException;
  17. use Psr\Log\LoggerInterface;
  18. class UploadCleanup extends TimedJob {
  19. private IRootFolder $rootFolder;
  20. private IJobList $jobList;
  21. private LoggerInterface $logger;
  22. public function __construct(ITimeFactory $time, IRootFolder $rootFolder, IJobList $jobList, LoggerInterface $logger) {
  23. parent::__construct($time);
  24. $this->rootFolder = $rootFolder;
  25. $this->jobList = $jobList;
  26. $this->logger = $logger;
  27. // Run once a day
  28. $this->setInterval(60 * 60 * 24);
  29. $this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
  30. }
  31. protected function run($argument) {
  32. $uid = $argument['uid'];
  33. $folder = $argument['folder'];
  34. try {
  35. $userFolder = $this->rootFolder->getUserFolder($uid);
  36. $userRoot = $userFolder->getParent();
  37. /** @var Folder $uploads */
  38. $uploads = $userRoot->get('uploads');
  39. $uploadFolder = $uploads->get($folder);
  40. } catch (NotFoundException|NoUserException $e) {
  41. $this->jobList->remove(self::class, $argument);
  42. return;
  43. }
  44. // Remove if all files have an mtime of more than a day
  45. $time = $this->time->getTime() - 60 * 60 * 24;
  46. if (!($uploadFolder instanceof Folder)) {
  47. $this->logger->error('Found a file inside the uploads folder. Uid: ' . $uid . ' folder: ' . $folder);
  48. if ($uploadFolder->getMTime() < $time) {
  49. $uploadFolder->delete();
  50. }
  51. $this->jobList->remove(self::class, $argument);
  52. return;
  53. }
  54. /** @var File[] $files */
  55. $files = $uploadFolder->getDirectoryListing();
  56. // The folder has to be more than a day old
  57. $initial = $uploadFolder->getMTime() < $time;
  58. $expire = array_reduce($files, function (bool $carry, File $file) use ($time) {
  59. return $carry && $file->getMTime() < $time;
  60. }, $initial);
  61. if ($expire) {
  62. $uploadFolder->delete();
  63. $this->jobList->remove(self::class, $argument);
  64. }
  65. }
  66. }