Skip to content

Commit

Permalink
feat(dav): dispatch out-of-office started and ended events
Browse files Browse the repository at this point in the history
Signed-off-by: Richard Steinmetz <richard@steinmetz.cloud>
  • Loading branch information
st3iny authored and ChristophWurst committed Nov 23, 2023
1 parent 953382e commit 8191295
Show file tree
Hide file tree
Showing 20 changed files with 920 additions and 46 deletions.
4 changes: 4 additions & 0 deletions apps/dav/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
'OCA\\DAV\\BackgroundJob\\CleanupInvitationTokenJob' => $baseDir . '/../lib/BackgroundJob/CleanupInvitationTokenJob.php',
'OCA\\DAV\\BackgroundJob\\EventReminderJob' => $baseDir . '/../lib/BackgroundJob/EventReminderJob.php',
'OCA\\DAV\\BackgroundJob\\GenerateBirthdayCalendarBackgroundJob' => $baseDir . '/../lib/BackgroundJob/GenerateBirthdayCalendarBackgroundJob.php',
'OCA\\DAV\\BackgroundJob\\OutOfOfficeEventDispatcherJob' => $baseDir . '/../lib/BackgroundJob/OutOfOfficeEventDispatcherJob.php',
'OCA\\DAV\\BackgroundJob\\PruneOutdatedSyncTokensJob' => $baseDir . '/../lib/BackgroundJob/PruneOutdatedSyncTokensJob.php',
'OCA\\DAV\\BackgroundJob\\RefreshWebcalJob' => $baseDir . '/../lib/BackgroundJob/RefreshWebcalJob.php',
'OCA\\DAV\\BackgroundJob\\RegisterRegenerateBirthdayCalendars' => $baseDir . '/../lib/BackgroundJob/RegisterRegenerateBirthdayCalendars.php',
Expand Down Expand Up @@ -100,6 +101,7 @@
'OCA\\DAV\\CalDAV\\Search\\Xml\\Request\\CalendarSearchReport' => $baseDir . '/../lib/CalDAV/Search/Xml/Request/CalendarSearchReport.php',
'OCA\\DAV\\CalDAV\\Status\\Status' => $baseDir . '/../lib/CalDAV/Status/Status.php',
'OCA\\DAV\\CalDAV\\Status\\StatusService' => $baseDir . '/../lib/CalDAV/Status/StatusService.php',
'OCA\\DAV\\CalDAV\\TimezoneService' => $baseDir . '/../lib/CalDAV/TimezoneService.php',
'OCA\\DAV\\CalDAV\\Trashbin\\DeletedCalendarObject' => $baseDir . '/../lib/CalDAV/Trashbin/DeletedCalendarObject.php',
'OCA\\DAV\\CalDAV\\Trashbin\\DeletedCalendarObjectsCollection' => $baseDir . '/../lib/CalDAV/Trashbin/DeletedCalendarObjectsCollection.php',
'OCA\\DAV\\CalDAV\\Trashbin\\Plugin' => $baseDir . '/../lib/CalDAV/Trashbin/Plugin.php',
Expand Down Expand Up @@ -210,6 +212,8 @@
'OCA\\DAV\\Db\\AbsenceMapper' => $baseDir . '/../lib/Db/AbsenceMapper.php',
'OCA\\DAV\\Db\\Direct' => $baseDir . '/../lib/Db/Direct.php',
'OCA\\DAV\\Db\\DirectMapper' => $baseDir . '/../lib/Db/DirectMapper.php',
'OCA\\DAV\\Db\\Property' => $baseDir . '/../lib/Db/Property.php',
'OCA\\DAV\\Db\\PropertyMapper' => $baseDir . '/../lib/Db/PropertyMapper.php',
'OCA\\DAV\\Direct\\DirectFile' => $baseDir . '/../lib/Direct/DirectFile.php',
'OCA\\DAV\\Direct\\DirectHome' => $baseDir . '/../lib/Direct/DirectHome.php',
'OCA\\DAV\\Direct\\Server' => $baseDir . '/../lib/Direct/Server.php',
Expand Down
4 changes: 4 additions & 0 deletions apps/dav/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class ComposerStaticInitDAV
'OCA\\DAV\\BackgroundJob\\CleanupInvitationTokenJob' => __DIR__ . '/..' . '/../lib/BackgroundJob/CleanupInvitationTokenJob.php',
'OCA\\DAV\\BackgroundJob\\EventReminderJob' => __DIR__ . '/..' . '/../lib/BackgroundJob/EventReminderJob.php',
'OCA\\DAV\\BackgroundJob\\GenerateBirthdayCalendarBackgroundJob' => __DIR__ . '/..' . '/../lib/BackgroundJob/GenerateBirthdayCalendarBackgroundJob.php',
'OCA\\DAV\\BackgroundJob\\OutOfOfficeEventDispatcherJob' => __DIR__ . '/..' . '/../lib/BackgroundJob/OutOfOfficeEventDispatcherJob.php',
'OCA\\DAV\\BackgroundJob\\PruneOutdatedSyncTokensJob' => __DIR__ . '/..' . '/../lib/BackgroundJob/PruneOutdatedSyncTokensJob.php',
'OCA\\DAV\\BackgroundJob\\RefreshWebcalJob' => __DIR__ . '/..' . '/../lib/BackgroundJob/RefreshWebcalJob.php',
'OCA\\DAV\\BackgroundJob\\RegisterRegenerateBirthdayCalendars' => __DIR__ . '/..' . '/../lib/BackgroundJob/RegisterRegenerateBirthdayCalendars.php',
Expand Down Expand Up @@ -115,6 +116,7 @@ class ComposerStaticInitDAV
'OCA\\DAV\\CalDAV\\Search\\Xml\\Request\\CalendarSearchReport' => __DIR__ . '/..' . '/../lib/CalDAV/Search/Xml/Request/CalendarSearchReport.php',
'OCA\\DAV\\CalDAV\\Status\\Status' => __DIR__ . '/..' . '/../lib/CalDAV/Status/Status.php',
'OCA\\DAV\\CalDAV\\Status\\StatusService' => __DIR__ . '/..' . '/../lib/CalDAV/Status/StatusService.php',
'OCA\\DAV\\CalDAV\\TimezoneService' => __DIR__ . '/..' . '/../lib/CalDAV/TimezoneService.php',
'OCA\\DAV\\CalDAV\\Trashbin\\DeletedCalendarObject' => __DIR__ . '/..' . '/../lib/CalDAV/Trashbin/DeletedCalendarObject.php',
'OCA\\DAV\\CalDAV\\Trashbin\\DeletedCalendarObjectsCollection' => __DIR__ . '/..' . '/../lib/CalDAV/Trashbin/DeletedCalendarObjectsCollection.php',
'OCA\\DAV\\CalDAV\\Trashbin\\Plugin' => __DIR__ . '/..' . '/../lib/CalDAV/Trashbin/Plugin.php',
Expand Down Expand Up @@ -225,6 +227,8 @@ class ComposerStaticInitDAV
'OCA\\DAV\\Db\\AbsenceMapper' => __DIR__ . '/..' . '/../lib/Db/AbsenceMapper.php',
'OCA\\DAV\\Db\\Direct' => __DIR__ . '/..' . '/../lib/Db/Direct.php',
'OCA\\DAV\\Db\\DirectMapper' => __DIR__ . '/..' . '/../lib/Db/DirectMapper.php',
'OCA\\DAV\\Db\\Property' => __DIR__ . '/..' . '/../lib/Db/Property.php',
'OCA\\DAV\\Db\\PropertyMapper' => __DIR__ . '/..' . '/../lib/Db/PropertyMapper.php',
'OCA\\DAV\\Direct\\DirectFile' => __DIR__ . '/..' . '/../lib/Direct/DirectFile.php',
'OCA\\DAV\\Direct\\DirectHome' => __DIR__ . '/..' . '/../lib/Direct/DirectHome.php',
'OCA\\DAV\\Direct\\Server' => __DIR__ . '/..' . '/../lib/Direct/Server.php',
Expand Down
92 changes: 92 additions & 0 deletions apps/dav/lib/BackgroundJob/OutOfOfficeEventDispatcherJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

declare(strict_types=1);

/**
* @copyright Copyright (c) 2023 Richard Steinmetz <richard@steinmetz.cloud>
*
* @author Richard Steinmetz <richard@steinmetz.cloud>
*
* @license AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/

namespace OCA\DAV\BackgroundJob;

use OCA\DAV\CalDAV\TimezoneService;
use OCA\DAV\Db\AbsenceMapper;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\QueuedJob;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IUserManager;
use OCP\User\Events\OutOfOfficeEndedEvent;
use OCP\User\Events\OutOfOfficeStartedEvent;
use Psr\Log\LoggerInterface;

class OutOfOfficeEventDispatcherJob extends QueuedJob {
public const EVENT_START = 'start';
public const EVENT_END = 'end';

public function __construct(
ITimeFactory $time,
private AbsenceMapper $absenceMapper,
private LoggerInterface $logger,
private IEventDispatcher $eventDispatcher,
private IUserManager $userManager,
private TimezoneService $timezoneService,
) {
parent::__construct($time);
}

public function run($argument): void {
$id = $argument['id'];
$event = $argument['event'];

try {
$absence = $this->absenceMapper->findById($id);
} catch (DoesNotExistException | \OCP\DB\Exception $e) {
$this->logger->error('Failed to dispatch out-of-office event: ' . $e->getMessage(), [
'exception' => $e,
'argument' => $argument,
]);
return;
}

$userId = $absence->getUserId();
$user = $this->userManager->get($userId);
if ($user === null) {
$this->logger->error("Failed to dispatch out-of-office event: User $userId does not exist", [
'argument' => $argument,
]);
return;
}

$data = $absence->toOutOufOfficeData(
$user,
$this->timezoneService->getUserTimezone($userId) ?? $this->timezoneService->getDefaultTimezone(),
);
if ($event === self::EVENT_START) {
$this->eventDispatcher->dispatchTyped(new OutOfOfficeStartedEvent($data));
} elseif ($event === self::EVENT_END) {
$this->eventDispatcher->dispatchTyped(new OutOfOfficeEndedEvent($data));
} else {
$this->logger->error("Invalid out-of-office event: $event", [
'argument' => $argument,
]);
}
}
}
98 changes: 98 additions & 0 deletions apps/dav/lib/CalDAV/TimezoneService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

declare(strict_types=1);

/*
* @copyright 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

namespace OCA\DAV\CalDAV;

use OCA\DAV\Db\PropertyMapper;
use OCP\Calendar\ICalendar;
use OCP\Calendar\IManager;
use OCP\IConfig;
use Sabre\VObject\Component\VCalendar;
use Sabre\VObject\Component\VTimeZone;
use Sabre\VObject\Reader;
use function array_reduce;

class TimezoneService {

public function __construct(private IConfig $config,
private PropertyMapper $propertyMapper,
private IManager $calendarManager) {
}

public function getUserTimezone(string $userId): ?string {
$availabilityPropPath = 'calendars/' . $userId . '/inbox';
$availabilityProp = '{' . Plugin::NS_CALDAV . '}calendar-availability';
$availabilities = $this->propertyMapper->findPropertyByPathAndName($userId, $availabilityPropPath, $availabilityProp);
if (!empty($availabilities)) {
$availability = $availabilities[0]->getPropertyvalue();
/** @var VCalendar $vCalendar */
$vCalendar = Reader::read($availability);
/** @var VTimeZone $vTimezone */
$vTimezone = $vCalendar->VTIMEZONE;
// Sabre has a fallback to date_default_timezone_get
return $vTimezone->getTimeZone()->getName();
}

$principal = 'principals/users/' . $userId;
$uri = $this->config->getUserValue($userId, 'dav', 'defaultCalendar', CalDavBackend::PERSONAL_CALENDAR_URI);
$calendars = $this->calendarManager->getCalendarsForPrincipal($principal);

/** @var ?VTimeZone $personalCalendarTimezone */
$personalCalendarTimezone = array_reduce($calendars, function (?VTimeZone $acc, ICalendar $calendar) use ($uri) {
if ($acc !== null) {
return $acc;
}
if ($calendar->getUri() === $uri && !$calendar->isDeleted() && $calendar instanceof CalendarImpl) {
return $calendar->getSchedulingTimezone();
}
return null;
});
if ($personalCalendarTimezone !== null) {
return $personalCalendarTimezone->getTimeZone()->getName();
}

// No timezone in the personalCalendarTimezone calendar or no personalCalendarTimezone calendar
// Loop through all calendars until we find a timezone.
/** @var ?VTimeZone $firstTimezone */
$firstTimezone = array_reduce($calendars, function (?VTimeZone $acc, ICalendar $calendar) {
if ($acc !== null) {
return $acc;
}
if (!$calendar->isDeleted() && $calendar instanceof CalendarImpl) {
return $calendar->getSchedulingTimezone();
}
return null;
});
if ($firstTimezone !== null) {
return $firstTimezone->getTimeZone()->getName();
}
return null;
}

public function getDefaultTimezone(): string {
return $this->config->getSystemValueString('default_timezone', 'UTC');
}

}
15 changes: 8 additions & 7 deletions apps/dav/lib/Controller/AvailabilitySettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,12 @@
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\Response;
use OCP\IRequest;
use OCP\IUserSession;

class AvailabilitySettingsController extends Controller {
public function __construct(
IRequest $request,
private ?string $userId,
private ?IUserSession $userSession,
private AbsenceService $absenceService,
) {
parent::__construct(Application::APP_ID, $request);
Expand All @@ -56,8 +57,8 @@ public function updateAbsence(
string $status,
string $message,
): Response {
$userId = $this->userId;
if ($userId === null) {
$user = $this->userSession?->getUser();
if ($user === null) {
return new JSONResponse([], Http::STATUS_FORBIDDEN);
}

Expand All @@ -68,7 +69,7 @@ public function updateAbsence(
}

$absence = $this->absenceService->createOrUpdateAbsence(
$userId,
$user,
$firstDay,
$lastDay,
$status,
Expand All @@ -82,12 +83,12 @@ public function updateAbsence(
*/
#[NoAdminRequired]
public function clearAbsence(): Response {
$userId = $this->userId;
if ($userId === null) {
$user = $this->userSession?->getUser();
if ($user === null) {
return new JSONResponse([], Http::STATUS_FORBIDDEN);
}

$this->absenceService->clearAbsence($userId);
$this->absenceService->clearAbsence($user);
return new JSONResponse([]);
}

Expand Down
11 changes: 7 additions & 4 deletions apps/dav/lib/Db/Absence.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@

namespace OCA\DAV\Db;

use DateTimeImmutable;
use DateTime;
use DateTimeZone;
use Exception;
use InvalidArgumentException;
use JsonSerializable;
Expand Down Expand Up @@ -67,16 +68,18 @@ public function __construct() {
$this->addType('message', 'string');
}

public function toOutOufOfficeData(IUser $user): IOutOfOfficeData {
public function toOutOufOfficeData(IUser $user, string $timezone): IOutOfOfficeData {
if ($user->getUID() !== $this->getUserId()) {
throw new InvalidArgumentException("The user doesn't match the user id of this absence! Expected " . $this->getUserId() . ", got " . $user->getUID());
}
if ($this->getId() === null) {
throw new Exception('Creating out-of-office data without ID');
}

$startDate = new DateTimeImmutable($this->getFirstDay());
$endDate = new DateTimeImmutable($this->getLastDay());
$tz = new DateTimeZone($timezone);
$startDate = new DateTime($this->getFirstDay(), $tz);
$endDate = new DateTime($this->getLastDay(), $tz);
$endDate->setTime(23, 59);
return new OutOfOfficeData(
(string)$this->getId(),
$user,
Expand Down
25 changes: 25 additions & 0 deletions apps/dav/lib/Db/AbsenceMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,31 @@ public function __construct(IDBConnection $db) {
parent::__construct($db, 'dav_absence', Absence::class);
}

/**
* @throws DoesNotExistException
* @throws \OCP\DB\Exception
*/
public function findById(int $id): Absence {
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from($this->getTableName())
->where($qb->expr()->eq(
'id',
$qb->createNamedParameter($id, IQueryBuilder::PARAM_INT),
IQueryBuilder::PARAM_INT),
);
try {
return $this->findEntity($qb);
} catch (MultipleObjectsReturnedException $e) {
// Won't happen as id is the primary key
throw new \RuntimeException(
'The impossible has happened! The query returned multiple absence settings for one user.',
0,
$e,
);
}
}

/**
* @throws DoesNotExistException
* @throws \OCP\DB\Exception
Expand Down
Loading

0 comments on commit 8191295

Please sign in to comment.