aboutsummaryrefslogtreecommitdiffstats
path: root/apps/dav/lib/Listener/OutOfOfficeListener.php
blob: 45728aa35d31ddf7b065c526f3a24646caea621e (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
<?php

declare(strict_types=1);

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

namespace OCA\DAV\Listener;

use DateTimeImmutable;
use DateTimeZone;
use OCA\DAV\CalDAV\CalDavBackend;
use OCA\DAV\CalDAV\Calendar;
use OCA\DAV\CalDAV\CalendarHome;
use OCA\DAV\CalDAV\TimezoneService;
use OCA\DAV\ServerFactory;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\IConfig;
use OCP\User\Events\OutOfOfficeChangedEvent;
use OCP\User\Events\OutOfOfficeClearedEvent;
use OCP\User\Events\OutOfOfficeScheduledEvent;
use OCP\User\IOutOfOfficeData;
use Psr\Log\LoggerInterface;
use Sabre\DAV\Exception\NotFound;
use Sabre\VObject\Component\VCalendar;
use function fclose;
use function fopen;
use function fwrite;
use function rewind;

/**
 * @template-implements IEventListener<OutOfOfficeScheduledEvent|OutOfOfficeChangedEvent|OutOfOfficeClearedEvent>
 */
class OutOfOfficeListener implements IEventListener {
	public function __construct(
		private ServerFactory $serverFactory,
		private IConfig $appConfig,
		private TimezoneService $timezoneService,
		private LoggerInterface $logger,
	) {
	}

	public function handle(Event $event): void {
		if ($event instanceof OutOfOfficeScheduledEvent) {
			$userId = $event->getData()->getUser()->getUID();
			$principal = "principals/users/$userId";
			$calendarNode = $this->getCalendarNode($principal, $userId);
			if ($calendarNode === null) {
				return;
			}
			$tzId = $this->timezoneService->getUserTimezone($userId) ?? $this->timezoneService->getDefaultTimezone();
			$vCalendarEvent = $this->createVCalendarEvent($event->getData(), $tzId);
			$stream = fopen('php://memory', 'rb+');
			try {
				fwrite($stream, $vCalendarEvent->serialize());
				rewind($stream);
				$calendarNode->createFile(
					$this->getEventFileName($event->getData()->getId()),
					$stream,
				);
			} finally {
				fclose($stream);
			}
		} elseif ($event instanceof OutOfOfficeChangedEvent) {
			$userId = $event->getData()->getUser()->getUID();
			$principal = "principals/users/$userId";
			$calendarNode = $this->getCalendarNode($principal, $userId);
			if ($calendarNode === null) {
				return;
			}
			$tzId = $this->timezoneService->getUserTimezone($userId) ?? $this->timezoneService->getDefaultTimezone();
			$vCalendarEvent = $this->createVCalendarEvent($event->getData(), $tzId);
			try {
				$oldEvent = $calendarNode->getChild($this->getEventFileName($event->getData()->getId()));
				$oldEvent->put($vCalendarEvent->serialize());
				return;
			} catch (NotFound) {
				$stream = fopen('php://memory', 'rb+');
				try {
					fwrite($stream, $vCalendarEvent->serialize());
					rewind($stream);
					$calendarNode->createFile(
						$this->getEventFileName($event->getData()->getId()),
						$stream,
					);
				} finally {
					fclose($stream);
				}
			}
		} elseif ($event instanceof OutOfOfficeClearedEvent) {
			$userId = $event->getData()->getUser()->getUID();
			$principal = "principals/users/$userId";
			$calendarNode = $this->getCalendarNode($principal, $userId);
			if ($calendarNode === null) {
				return;
			}
			try {
				$oldEvent = $calendarNode->getChild($this->getEventFileName($event->getData()->getId()));
				$oldEvent->delete();
			} catch (NotFound) {
				// The user must have deleted it or the default calendar changed -> ignore
				return;
			}
		}
	}

	private function getCalendarNode(string $principal, string $userId): ?Calendar {
		$invitationServer = $this->serverFactory->createInviationResponseServer(false);
		$server = $invitationServer->getServer();

		/** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
		$caldavPlugin = $server->getPlugin('caldav');
		$calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principal);
		if ($calendarHomePath === null) {
			$this->logger->debug('Principal has no calendar home path');
			return null;
		}
		try {
			/** @var CalendarHome $calendarHome */
			$calendarHome = $server->tree->getNodeForPath($calendarHomePath);
		} catch (NotFound $e) {
			$this->logger->debug('Calendar home not found', [
				'exception' => $e,
			]);
			return null;
		}
		$uri = $this->appConfig->getUserValue($userId, 'dav', 'defaultCalendar', CalDavBackend::PERSONAL_CALENDAR_URI);
		try {
			$calendarNode = $calendarHome->getChild($uri);
		} catch (NotFound $e) {
			$this->logger->debug('Personal calendar does not exist', [
				'exception' => $e,
				'uri' => $uri,
			]);
			return null;
		}
		if (!($calendarNode instanceof Calendar)) {
			$this->logger->warning('Personal calendar node is not a calendar');
			return null;
		}
		if ($calendarNode->isDeleted()) {
			$this->logger->warning('Personal calendar has been deleted');
			return null;
		}

		return $calendarNode;
	}

	private function getEventFileName(string $id): string {
		return "out_of_office_$id.ics";
	}

	private function createVCalendarEvent(IOutOfOfficeData $data, string $tzId): VCalendar {
		$shortMessage = $data->getShortMessage();
		$longMessage = $data->getMessage();
		$start = (new DateTimeImmutable)
			->setTimezone(new DateTimeZone($tzId))
			->setTimestamp($data->getStartDate())
			->setTime(0, 0);
		$end = (new DateTimeImmutable())
			->setTimezone(new DateTimeZone($tzId))
			->setTimestamp($data->getEndDate())
			->modify('+ 1 days')
			->setTime(0, 0);
		$vCalendar = new VCalendar();
		$vCalendar->add('VEVENT', [
			'SUMMARY' => $shortMessage,
			'DESCRIPTION' => $longMessage,
			'STATUS' => 'CONFIRMED',
			'DTSTART' => $start,
			'DTEND' => $end,
			'X-NEXTCLOUD-OUT-OF-OFFICE' => $data->getId(),
		]);
		return $vCalendar;
	}
}