RemoveOldTasksBackgroundJob.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 * 50 * 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. }
  30. /**
  31. * @param mixed $argument
  32. * @inheritDoc
  33. */
  34. protected function run($argument) {
  35. try {
  36. $deletedTasks = $this->taskMapper->deleteOlderThan(self::MAX_TASK_AGE_SECONDS);
  37. $folder = $this->appData->getFolder('text2image');
  38. foreach ($deletedTasks as $deletedTask) {
  39. try {
  40. $folder->getFolder((string)$deletedTask->getId())->delete();
  41. } catch (NotFoundException) {
  42. // noop
  43. } catch (NotPermittedException $e) {
  44. $this->logger->warning('Failed to delete stale text to image task files', ['exception' => $e]);
  45. }
  46. }
  47. } catch (Exception $e) {
  48. $this->logger->warning('Failed to delete stale text to image tasks', ['exception' => $e]);
  49. } catch(NotFoundException) {
  50. // noop
  51. }
  52. }
  53. }