UpcomingEventsService.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\CalDAV;
  8. use OCP\App\IAppManager;
  9. use OCP\AppFramework\Utility\ITimeFactory;
  10. use OCP\Calendar\IManager;
  11. use OCP\IURLGenerator;
  12. use OCP\IUserManager;
  13. use function array_map;
  14. class UpcomingEventsService {
  15. public function __construct(
  16. private IManager $calendarManager,
  17. private ITimeFactory $timeFactory,
  18. private IUserManager $userManager,
  19. private IAppManager $appManager,
  20. private IURLGenerator $urlGenerator,
  21. ) {
  22. }
  23. /**
  24. * @return UpcomingEvent[]
  25. */
  26. public function getEvents(string $userId, ?string $location = null): array {
  27. $searchQuery = $this->calendarManager->newQuery('principals/users/' . $userId);
  28. if ($location !== null) {
  29. $searchQuery->addSearchProperty('LOCATION');
  30. $searchQuery->setSearchPattern($location);
  31. }
  32. $searchQuery->addType('VEVENT');
  33. $searchQuery->setLimit(3);
  34. $now = $this->timeFactory->now();
  35. $searchQuery->setTimerangeStart($now->modify('-1 minute'));
  36. $searchQuery->setTimerangeEnd($now->modify('+1 month'));
  37. $events = $this->calendarManager->searchForPrincipal($searchQuery);
  38. $calendarAppEnabled = $this->appManager->isEnabledForUser(
  39. 'calendar',
  40. $this->userManager->get($userId),
  41. );
  42. return array_map(fn (array $event) => new UpcomingEvent(
  43. $event['uri'],
  44. ($event['objects'][0]['RECURRENCE-ID'][0] ?? null)?->getTimeStamp(),
  45. $event['calendar-uri'],
  46. $event['objects'][0]['DTSTART'][0]?->getTimestamp(),
  47. $event['objects'][0]['SUMMARY'][0] ?? null,
  48. $event['objects'][0]['LOCATION'][0] ?? null,
  49. match ($calendarAppEnabled) {
  50. // TODO: create a named, deep route in calendar
  51. // TODO: it's a code smell to just assume this route exists, find an abstraction
  52. true => $this->urlGenerator->linkToRouteAbsolute('calendar.view.index'),
  53. false => null,
  54. },
  55. ), $events);
  56. }
  57. }