BuildCalendarSearchIndexBackgroundJob.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\Migration;
  8. use OCA\DAV\CalDAV\CalDavBackend;
  9. use OCP\AppFramework\Utility\ITimeFactory;
  10. use OCP\BackgroundJob\IJobList;
  11. use OCP\BackgroundJob\QueuedJob;
  12. use OCP\IDBConnection;
  13. use Psr\Log\LoggerInterface;
  14. class BuildCalendarSearchIndexBackgroundJob extends QueuedJob {
  15. public function __construct(
  16. private IDBConnection $db,
  17. private CalDavBackend $calDavBackend,
  18. private LoggerInterface $logger,
  19. private IJobList $jobList,
  20. ITimeFactory $timeFactory
  21. ) {
  22. parent::__construct($timeFactory);
  23. }
  24. public function run($arguments) {
  25. $offset = (int) $arguments['offset'];
  26. $stopAt = (int) $arguments['stopAt'];
  27. $this->logger->info('Building calendar index (' . $offset .'/' . $stopAt . ')');
  28. $startTime = $this->time->getTime();
  29. while (($this->time->getTime() - $startTime) < 15) {
  30. $offset = $this->buildIndex($offset, $stopAt);
  31. if ($offset >= $stopAt) {
  32. break;
  33. }
  34. }
  35. if ($offset >= $stopAt) {
  36. $this->logger->info('Building calendar index done');
  37. } else {
  38. $this->jobList->add(self::class, [
  39. 'offset' => $offset,
  40. 'stopAt' => $stopAt
  41. ]);
  42. $this->logger->info('New building calendar index job scheduled with offset ' . $offset);
  43. }
  44. }
  45. /**
  46. * @param int $offset
  47. * @param int $stopAt
  48. * @return int
  49. */
  50. private function buildIndex(int $offset, int $stopAt): int {
  51. $query = $this->db->getQueryBuilder();
  52. $query->select(['id', 'calendarid', 'uri', 'calendardata'])
  53. ->from('calendarobjects')
  54. ->where($query->expr()->lte('id', $query->createNamedParameter($stopAt)))
  55. ->andWhere($query->expr()->gt('id', $query->createNamedParameter($offset)))
  56. ->orderBy('id', 'ASC')
  57. ->setMaxResults(500);
  58. $result = $query->executeQuery();
  59. while ($row = $result->fetch(\PDO::FETCH_ASSOC)) {
  60. $offset = $row['id'];
  61. $calendarData = $row['calendardata'];
  62. if (is_resource($calendarData)) {
  63. $calendarData = stream_get_contents($calendarData);
  64. }
  65. $this->calDavBackend->updateProperties($row['calendarid'], $row['uri'], $calendarData);
  66. }
  67. return $offset;
  68. }
  69. }