-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathBirthdayService.php
More file actions
362 lines (295 loc) · 12.1 KB
/
BirthdayService.php
File metadata and controls
362 lines (295 loc) · 12.1 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
<?php
declare(strict_types=1);
/**
* Largely inspired by https://github.com/nextcloud/server/blob/master/apps/dav/lib/CalDAV/BirthdayService.php which is licensed in these terms:
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
namespace App\Services;
use App\Constants;
use App\Entity\AddressBook;
use App\Entity\Calendar;
use App\Entity\CalendarInstance;
use App\Entity\CalendarObject;
use App\Entity\Card;
use App\Entity\Principal;
use Doctrine\Persistence\ManagerRegistry;
use Sabre\CalDAV\Backend\PDO as CalendarBackend;
use Sabre\DAV\Sharing\Plugin as SharingPlugin;
use Sabre\VObject\Component\VCalendar;
use Sabre\VObject\Component\VCard;
use Sabre\VObject\DateTimeParser;
use Sabre\VObject\Document;
use Sabre\VObject\InvalidDataException;
use Sabre\VObject\Property\VCard\DateAndOrTime;
use Sabre\VObject\Reader;
class BirthdayService
{
/**
* @var CalendarBackend
*/
private $calendarBackend;
public function __construct(
private ManagerRegistry $doctrine,
private string $birthdayReminderOffset,
) {
}
public function setBackend(CalendarBackend $calendarBackend)
{
$this->calendarBackend = $calendarBackend;
}
public function onCardChanged(int $addressBookId, string $cardUri, string $cardData): void
{
$book = $this->doctrine->getRepository(AddressBook::class)->findOneById($addressBookId);
if (!$book->isIncludedInBirthdayCalendar()) {
return;
}
$principalUri = $book->getPrincipalUri();
$calendarInstance = $this->ensureBirthdayCalendarExists($principalUri);
$this->updateCalendar($cardUri, $cardData, $book, $calendarInstance);
}
public function onCardDeleted(int $addressBookId, string $cardUri): void
{
$book = $this->doctrine->getRepository(AddressBook::class)->findOneById($addressBookId);
if (!$book->isIncludedInBirthdayCalendar()) {
return;
}
$principalUri = $book->getPrincipalUri();
$calendarInstance = $this->ensureBirthdayCalendarExists($principalUri);
$objectUri = $book->getUri().'-'.$cardUri.'.ics';
$calendar = $calendarInstance->getCalendar();
// This is the structure that needs to be passed to the backend methods
$calendarId = [$calendar->getId(), $calendarInstance->getId()];
$this->calendarBackend->deleteCalendarObject(
$calendarId,
$objectUri
);
}
public function shouldBirthdayCalendarExist(string $principalUri): bool
{
$addressbooks = $this->doctrine->getRepository(AddressBook::class)->findByPrincipalUri($principalUri);
return array_reduce($addressbooks, function ($carry, $addressbook) {
return $carry || $addressbook->isIncludedInBirthdayCalendar();
}, false);
}
public function ensureBirthdayCalendarExists(string $principalUri): CalendarInstance
{
$instance = $this->doctrine->getRepository(CalendarInstance::class)->findOneBy(['principalUri' => $principalUri, 'uri' => Constants::BIRTHDAY_CALENDAR_URI]);
if ($instance) {
return $instance;
}
$em = $this->doctrine->getManager();
$calendar = new Calendar();
$em->persist($calendar);
$instance = (new CalendarInstance())
->setPrincipalUri($principalUri)
->setDisplayName('🎁 Birthdays')
->setDescription('Birthdays')
->setAccess(SharingPlugin::ACCESS_READ)
->setCalendarOrder(0)
->setCalendar($calendar)
->setTransparent(1)
->setShareInviteStatus(SharingPlugin::INVITE_ACCEPTED)
->setUri(Constants::BIRTHDAY_CALENDAR_URI);
$em->persist($instance);
$em->flush();
return $instance;
}
public function deleteBirthdayCalendar(string $principalUri): void
{
$instance = $this->doctrine->getRepository(CalendarInstance::class)->findOneBy(['principalUri' => $principalUri, 'uri' => Constants::BIRTHDAY_CALENDAR_URI]);
if (!$instance) {
return;
}
$em = $this->doctrine->getManager();
$em->remove($instance);
$em->remove($instance->getCalendar());
$em->flush();
}
/**
* @throws InvalidDataException
*/
public function buildDataFromContact(string $cardData): ?VCalendar
{
if (empty($cardData)) {
return null;
}
try {
$doc = Reader::read($cardData);
// We're always converting to vCard 4.0 so we can rely on the
// VCardConverter handling the X-APPLE-OMIT-YEAR property for us.
if (!$doc instanceof VCard) {
return null;
}
$doc = $doc->convert(Document::VCARD40);
} catch (\Exception $e) {
return null;
}
if (!isset($doc->BDAY) || !isset($doc->FN)) {
return null;
}
$birthday = $doc->BDAY;
if (!(string) $birthday) {
return null;
}
// Skip if the BDAY property is not of the right type.
if (!$birthday instanceof DateAndOrTime) {
return null;
}
// Skip if we can't parse the BDAY value.
try {
$dateParts = DateTimeParser::parseVCardDateTime($birthday->getValue());
} catch (InvalidDataException $e) {
return null;
}
if (null !== $dateParts['year']) {
$parameters = $birthday->parameters();
$omitYear = (isset($parameters['X-APPLE-OMIT-YEAR']) && $parameters['X-APPLE-OMIT-YEAR'] === $dateParts['year']);
// 'X-APPLE-OMIT-YEAR' is not always present, at least iOS 12.4 uses the hard coded date of 1604 (the start of the gregorian calendar) when the year is unknown
if ($omitYear || 1604 === (int) $dateParts['year']) {
$dateParts['year'] = null;
}
}
$originalYear = null;
if (null !== $dateParts['year']) {
$originalYear = (int) $dateParts['year'];
}
try {
if ($birthday instanceof DateAndOrTime) {
$date = $birthday->getDateTime();
} else {
$date = new \DateTimeImmutable($birthday);
}
} catch (\Exception $e) {
return null;
}
$summary = '🎂 '.$doc->FN->getValue().($originalYear ? (' ('.$originalYear.')') : '');
$vCal = new VCalendar();
$vCal->VERSION = '2.0';
$vCal->PRODID = '-//IDN davis//Birthday calendar//EN';
$vEvent = $vCal->createComponent('VEVENT');
$vEvent->add('DTSTART');
$vEvent->DTSTART->setDateTime(
$date
);
$vEvent->DTSTART['VALUE'] = 'DATE';
$vEvent->add('DTEND');
$dtEndDate = (new \DateTime())->setTimestamp($date->getTimeStamp());
$dtEndDate->add(new \DateInterval('P1D'));
$vEvent->DTEND->setDateTime(
$dtEndDate
);
$vEvent->DTEND['VALUE'] = 'DATE';
$vEvent->{'UID'} = $doc->UID;
$leapDay = (2 === (int) $dateParts['month']
&& 29 === (int) $dateParts['date']);
if (null === $dateParts['year'] || $originalYear < 1970) {
$birthday = ($leapDay ? '1972-' : '1970-')
.$dateParts['month'].'-'.$dateParts['date'];
}
if ($leapDay) {
/* Sabre\VObject supports BYMONTHDAY only if BYMONTH
* is also set */
$vEvent->{'RRULE'} = 'FREQ=YEARLY;BYMONTH=2;BYMONTHDAY=-1';
} else {
$vEvent->{'RRULE'} = 'FREQ=YEARLY';
}
$vEvent->{'SUMMARY'} = $summary;
$vEvent->{'TRANSP'} = 'TRANSPARENT';
// Set a reminder, if needed
if ('false' !== strtolower($this->birthdayReminderOffset)) {
$alarm = $vCal->createComponent('VALARM');
$alarm->add($vCal->createProperty('TRIGGER', $this->birthdayReminderOffset, ['VALUE' => 'DURATION']));
$alarm->add($vCal->createProperty('ACTION', 'DISPLAY'));
$alarm->add($vCal->createProperty('DESCRIPTION', $vEvent->{'SUMMARY'}));
$vEvent->add($alarm);
}
$vCal->add($vEvent);
return $vCal;
}
public function resetForPrincipal(string $principal): void
{
$calendarInstance = $this->doctrine->getRepository(CalendarInstance::class)->findOneBy(['principalUri' => $principal, 'uri' => Constants::BIRTHDAY_CALENDAR_URI]);
if (!$calendarInstance) {
return; // The user's birthday calendar doesn't exist, no need to purge it
}
$calendarObjects = $this->doctrine->getRepository(CalendarObject::class)->findByCalendar($calendarInstance->getCalendar());
$em = $this->doctrine->getManager();
foreach ($calendarObjects as $calendarObject) {
$em->remove($calendarObject);
}
$em->flush();
}
public function syncUser(string $username): void
{
$this->syncPrincipal(Principal::PREFIX.$username);
}
public function syncPrincipal(string $principal): void
{
if (!$this->shouldBirthdayCalendarExist($principal)) {
$this->deleteBirthdayCalendar($principal);
return;
}
$calendarInstance = $this->ensureBirthdayCalendarExists($principal);
// Reset the calendar
$this->resetForPrincipal($principal);
// Get all address books that should be included and iterate
$addressbooks = $this->doctrine->getRepository(AddressBook::class)->findBy(['principalUri' => $principal, 'includedInBirthdayCalendar' => true]);
foreach ($addressbooks as $book) {
$cards = $this->doctrine->getRepository(Card::class)->findByAddressBook($book);
foreach ($cards as $card) {
$this->onCardChanged($book->getId(), $card->getUri(), $card->getCardData());
}
}
}
public function birthdayEventChanged(string $existingCalendarData, VCalendar $newCalendarData): bool
{
try {
$existingBirthday = Reader::read($existingCalendarData);
} catch (\Exception $ex) {
return true;
}
return
$newCalendarData->VEVENT->DTSTART->getValue() !== $existingBirthday->VEVENT->DTSTART->getValue()
|| $newCalendarData->VEVENT->SUMMARY->getValue() !== $existingBirthday->VEVENT->SUMMARY->getValue()
;
}
/**
* @throws InvalidDataException
*/
private function updateCalendar(string $cardUri, string $cardData, AddressBook $book, CalendarInstance $calendarInstance): void
{
$objectUid = $book->getUri().'-'.$cardUri;
$objectUri = $objectUid.'.ics';
$calendarData = $this->buildDataFromContact($cardData);
$calendar = $calendarInstance->getCalendar();
// This is the structure that needs to be passed to the backend methods
$calendarId = [$calendar->getId(), $calendarInstance->getId()];
$existing = $this->doctrine->getRepository(CalendarObject::class)->findOneBy(['calendar' => $calendar, 'uri' => $objectUri]);
if (null === $calendarData) {
if (null !== $existing) {
$this->calendarBackend->deleteCalendarObject(
[$calendar->getId(), $calendarInstance->getId()],
$objectUri
);
}
} else {
if (null === $existing) {
$this->calendarBackend->createCalendarObject(
[$calendar->getId(), $calendarInstance->getId()],
$objectUri,
$calendarData->serialize()
);
} else {
if ($this->birthdayEventChanged($existing->getCalendarData(), $calendarData)) {
$this->calendarBackend->updateCalendarObject(
[$calendar->getId(), $calendarInstance->getId()],
$objectUri,
$calendarData->serialize()
);
}
}
}
}
}