aboutsummaryrefslogtreecommitdiffstats
path: root/apps/dav/lib/CalDAV/UpcomingEventsService.php
blob: 9c054deb4e01441b69b07df16f69ac799139639a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OCA\DAV\CalDAV;

use OCP\App\IAppManager;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Calendar\IManager;
use OCP\IURLGenerator;
use OCP\IUserManager;
use function array_map;

class UpcomingEventsService {
	public function __construct(
		private IManager $calendarManager,
		private ITimeFactory $timeFactory,
		private IUserManager $userManager,
		private IAppManager $appManager,
		private IURLGenerator $urlGenerator,
	) {
	}

	/**
	 * @return UpcomingEvent[]
	 */
	public function getEvents(string $userId, ?string $location = null): array {
		$searchQuery = $this->calendarManager->newQuery('principals/users/' . $userId);
		if ($location !== null) {
			$searchQuery->addSearchProperty('LOCATION');
			$searchQuery->setSearchPattern($location);
		}
		$searchQuery->addType('VEVENT');
		$searchQuery->setLimit(3);
		$now = $this->timeFactory->now();
		$searchQuery->setTimerangeStart($now->modify('-1 minute'));
		$searchQuery->setTimerangeEnd($now->modify('+1 month'));

		$events = $this->calendarManager->searchForPrincipal($searchQuery);
		$calendarAppEnabled = $this->appManager->isEnabledForUser(
			'calendar',
			$this->userManager->get($userId),
		);

		return array_map(fn (array $event) => new UpcomingEvent(
			$event['uri'],
			($event['objects'][0]['RECURRENCE-ID'][0] ?? null)?->getTimeStamp(),
			$event['calendar-uri'],
			$event['objects'][0]['DTSTART'][0]?->getTimestamp(),
			$event['objects'][0]['SUMMARY'][0] ?? null,
			$event['objects'][0]['LOCATION'][0] ?? null,
			match ($calendarAppEnabled) {
				// TODO: create a named, deep route in calendar
				// TODO: it's a code smell to just assume this route exists, find an abstraction
				true => $this->urlGenerator->linkToRouteAbsolute('calendar.view.index'),
				false => null,
			},
		), $events);
	}

}