1
0

UploadCleanup.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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\IJobList;
  11. use OCP\BackgroundJob\TimedJob;
  12. use OCP\Files\File;
  13. use OCP\Files\Folder;
  14. use OCP\Files\IRootFolder;
  15. use OCP\Files\NotFoundException;
  16. use Psr\Log\LoggerInterface;
  17. class UploadCleanup extends TimedJob {
  18. public function __construct(
  19. ITimeFactory $time,
  20. private IRootFolder $rootFolder,
  21. private IJobList $jobList,
  22. private LoggerInterface $logger,
  23. ) {
  24. parent::__construct($time);
  25. // Run once a day
  26. $this->setInterval(60 * 60 * 24);
  27. $this->setTimeSensitivity(self::TIME_INSENSITIVE);
  28. }
  29. protected function run($argument) {
  30. $uid = $argument['uid'];
  31. $folder = $argument['folder'];
  32. try {
  33. $userFolder = $this->rootFolder->getUserFolder($uid);
  34. $userRoot = $userFolder->getParent();
  35. /** @var Folder $uploads */
  36. $uploads = $userRoot->get('uploads');
  37. $uploadFolder = $uploads->get($folder);
  38. } catch (NotFoundException|NoUserException $e) {
  39. $this->jobList->remove(self::class, $argument);
  40. return;
  41. }
  42. // Remove if all files have an mtime of more than a day
  43. $time = $this->time->getTime() - 60 * 60 * 24;
  44. if (!($uploadFolder instanceof Folder)) {
  45. $this->logger->error('Found a file inside the uploads folder. Uid: ' . $uid . ' folder: ' . $folder);
  46. if ($uploadFolder->getMTime() < $time) {
  47. $uploadFolder->delete();
  48. }
  49. $this->jobList->remove(self::class, $argument);
  50. return;
  51. }
  52. /** @var File[] $files */
  53. $files = $uploadFolder->getDirectoryListing();
  54. // The folder has to be more than a day old
  55. $initial = $uploadFolder->getMTime() < $time;
  56. $expire = array_reduce($files, function (bool $carry, File $file) use ($time) {
  57. return $carry && $file->getMTime() < $time;
  58. }, $initial);
  59. if ($expire) {
  60. $uploadFolder->delete();
  61. $this->jobList->remove(self::class, $argument);
  62. }
  63. }
  64. }