RemoveOldTasksBackgroundJob.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\TextToImage;
  8. use OC\TextToImage\Db\TaskMapper;
  9. use OCP\AppFramework\Utility\ITimeFactory;
  10. use OCP\BackgroundJob\TimedJob;
  11. use OCP\DB\Exception;
  12. use OCP\Files\AppData\IAppDataFactory;
  13. use OCP\Files\IAppData;
  14. use OCP\Files\NotFoundException;
  15. use OCP\Files\NotPermittedException;
  16. use Psr\Log\LoggerInterface;
  17. class RemoveOldTasksBackgroundJob extends TimedJob {
  18. public const MAX_TASK_AGE_SECONDS = 60 * 60 * 24 * 7; // 1 week
  19. private IAppData $appData;
  20. public function __construct(
  21. ITimeFactory $timeFactory,
  22. private TaskMapper $taskMapper,
  23. private LoggerInterface $logger,
  24. IAppDataFactory $appDataFactory,
  25. ) {
  26. parent::__construct($timeFactory);
  27. $this->appData = $appDataFactory->get('core');
  28. $this->setInterval(60 * 60 * 24);
  29. $this->setTimeSensitivity(self::TIME_INSENSITIVE);
  30. }
  31. /**
  32. * @param mixed $argument
  33. * @inheritDoc
  34. */
  35. protected function run($argument) {
  36. try {
  37. $deletedTasks = $this->taskMapper->deleteOlderThan(self::MAX_TASK_AGE_SECONDS);
  38. $folder = $this->appData->getFolder('text2image');
  39. foreach ($deletedTasks as $deletedTask) {
  40. try {
  41. $folder->getFolder((string)$deletedTask->getId())->delete();
  42. } catch (NotFoundException) {
  43. // noop
  44. } catch (NotPermittedException $e) {
  45. $this->logger->warning('Failed to delete stale text to image task files', ['exception' => $e]);
  46. }
  47. }
  48. } catch (Exception $e) {
  49. $this->logger->warning('Failed to delete stale text to image tasks', ['exception' => $e]);
  50. } catch (NotFoundException) {
  51. // noop
  52. }
  53. }
  54. }