BuildSocialSearchIndexBackgroundJob.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\Migration;
  8. use OCA\DAV\CardDAV\CardDavBackend;
  9. use OCP\AppFramework\Utility\ITimeFactory;
  10. use OCP\BackgroundJob\IJobList;
  11. use OCP\BackgroundJob\QueuedJob;
  12. use OCP\DB\QueryBuilder\IQueryBuilder;
  13. use OCP\IDBConnection;
  14. use Psr\Log\LoggerInterface;
  15. class BuildSocialSearchIndexBackgroundJob extends QueuedJob {
  16. public function __construct(
  17. private IDBConnection $db,
  18. private CardDavBackend $davBackend,
  19. private LoggerInterface $logger,
  20. private IJobList $jobList,
  21. ITimeFactory $timeFactory,
  22. ) {
  23. parent::__construct($timeFactory);
  24. }
  25. public function run($arguments) {
  26. $offset = $arguments['offset'];
  27. $stopAt = $arguments['stopAt'];
  28. $this->logger->info('Indexing social profile data (' . $offset . '/' . $stopAt . ')');
  29. $offset = $this->buildIndex($offset, $stopAt);
  30. if ($offset >= $stopAt) {
  31. $this->logger->info('All contacts with social profiles indexed');
  32. } else {
  33. $this->jobList->add(self::class, [
  34. 'offset' => $offset,
  35. 'stopAt' => $stopAt
  36. ]);
  37. $this->logger->info('New social profile indexing job scheduled with offset ' . $offset);
  38. }
  39. }
  40. /**
  41. * @param int $offset
  42. * @param int $stopAt
  43. * @return int
  44. */
  45. private function buildIndex($offset, $stopAt) {
  46. $startTime = $this->time->getTime();
  47. // get contacts with social profiles
  48. $query = $this->db->getQueryBuilder();
  49. $query->select('id', 'addressbookid', 'uri', 'carddata')
  50. ->from('cards', 'c')
  51. ->orderBy('id', 'ASC')
  52. ->where($query->expr()->like('carddata', $query->createNamedParameter('%SOCIALPROFILE%')))
  53. ->andWhere($query->expr()->gt('id', $query->createNamedParameter((int)$offset, IQueryBuilder::PARAM_INT)))
  54. ->setMaxResults(100);
  55. $social_cards = $query->executeQuery()->fetchAll();
  56. if (empty($social_cards)) {
  57. return $stopAt;
  58. }
  59. // refresh identified contacts in order to re-index
  60. foreach ($social_cards as $contact) {
  61. $offset = $contact['id'];
  62. $cardData = $contact['carddata'];
  63. if (is_resource($cardData) && (get_resource_type($cardData) === 'stream')) {
  64. $cardData = stream_get_contents($cardData);
  65. }
  66. $this->davBackend->updateCard($contact['addressbookid'], $contact['uri'], $cardData);
  67. // stop after 15sec (to be continued with next chunk)
  68. if (($this->time->getTime() - $startTime) > 15) {
  69. break;
  70. }
  71. }
  72. return $offset;
  73. }
  74. }