1
0

StatusService.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\CalDAV\Status;
  8. use DateTimeImmutable;
  9. use OC\Calendar\CalendarQuery;
  10. use OCA\DAV\CalDAV\CalendarImpl;
  11. use OCA\UserStatus\Service\StatusService as UserStatusService;
  12. use OCP\AppFramework\Db\DoesNotExistException;
  13. use OCP\AppFramework\Utility\ITimeFactory;
  14. use OCP\Calendar\IManager;
  15. use OCP\DB\Exception;
  16. use OCP\ICache;
  17. use OCP\ICacheFactory;
  18. use OCP\IUser as User;
  19. use OCP\IUserManager;
  20. use OCP\User\IAvailabilityCoordinator;
  21. use OCP\UserStatus\IUserStatus;
  22. use Psr\Log\LoggerInterface;
  23. use Sabre\CalDAV\Xml\Property\ScheduleCalendarTransp;
  24. class StatusService {
  25. private ICache $cache;
  26. public function __construct(
  27. private ITimeFactory $timeFactory,
  28. private IManager $calendarManager,
  29. private IUserManager $userManager,
  30. private UserStatusService $userStatusService,
  31. private IAvailabilityCoordinator $availabilityCoordinator,
  32. private ICacheFactory $cacheFactory,
  33. private LoggerInterface $logger,
  34. ) {
  35. $this->cache = $cacheFactory->createLocal('CalendarStatusService');
  36. }
  37. public function processCalendarStatus(string $userId): void {
  38. $user = $this->userManager->get($userId);
  39. if ($user === null) {
  40. return;
  41. }
  42. $availability = $this->availabilityCoordinator->getCurrentOutOfOfficeData($user);
  43. if ($availability !== null && $this->availabilityCoordinator->isInEffect($availability)) {
  44. $this->logger->debug('An Absence is in effect, skipping calendar status check', ['user' => $userId]);
  45. return;
  46. }
  47. $calendarEvents = $this->cache->get($userId);
  48. if ($calendarEvents === null) {
  49. $calendarEvents = $this->getCalendarEvents($user);
  50. $this->cache->set($userId, $calendarEvents, 300);
  51. }
  52. if (empty($calendarEvents)) {
  53. try {
  54. $this->userStatusService->revertUserStatus($userId, IUserStatus::MESSAGE_CALENDAR_BUSY);
  55. } catch (Exception $e) {
  56. if ($e->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  57. // A different process might have written another status
  58. // update to the DB while we're processing our stuff.
  59. // We cannot safely restore the status as we don't know which one is valid at this point
  60. // So let's silently log this one and exit
  61. $this->logger->debug('Unique constraint violation for live user status', ['exception' => $e]);
  62. return;
  63. }
  64. }
  65. $this->logger->debug('No calendar events found for status check', ['user' => $userId]);
  66. return;
  67. }
  68. try {
  69. $currentStatus = $this->userStatusService->findByUserId($userId);
  70. // Was the status set by anything other than the calendar automation?
  71. $userStatusTimestamp = $currentStatus->getIsUserDefined() && $currentStatus->getMessageId() !== IUserStatus::MESSAGE_CALENDAR_BUSY ? $currentStatus->getStatusTimestamp() : null;
  72. } catch (DoesNotExistException) {
  73. $userStatusTimestamp = null;
  74. $currentStatus = null;
  75. }
  76. if (($currentStatus !== null && $currentStatus->getMessageId() === IUserStatus::MESSAGE_CALL)
  77. || ($currentStatus !== null && $currentStatus->getStatus() === IUserStatus::DND)
  78. || ($currentStatus !== null && $currentStatus->getStatus() === IUserStatus::INVISIBLE)) {
  79. // We don't overwrite the call status, DND status or Invisible status
  80. $this->logger->debug('Higher priority status detected, skipping calendar status change', ['user' => $userId]);
  81. return;
  82. }
  83. // Filter events to see if we have any that apply to the calendar status
  84. $applicableEvents = array_filter($calendarEvents, static function (array $calendarEvent) use ($userStatusTimestamp): bool {
  85. if (empty($calendarEvent['objects'])) {
  86. return false;
  87. }
  88. $component = $calendarEvent['objects'][0];
  89. if (isset($component['X-NEXTCLOUD-OUT-OF-OFFICE'])) {
  90. return false;
  91. }
  92. if (isset($component['DTSTART']) && $userStatusTimestamp !== null) {
  93. /** @var DateTimeImmutable $dateTime */
  94. $dateTime = $component['DTSTART'][0];
  95. if ($dateTime instanceof DateTimeImmutable && $userStatusTimestamp > $dateTime->getTimestamp()) {
  96. return false;
  97. }
  98. }
  99. // Ignore events that are transparent
  100. if (isset($component['TRANSP']) && strcasecmp($component['TRANSP'][0], 'TRANSPARENT') === 0) {
  101. return false;
  102. }
  103. return true;
  104. });
  105. if (empty($applicableEvents)) {
  106. try {
  107. $this->userStatusService->revertUserStatus($userId, IUserStatus::MESSAGE_CALENDAR_BUSY);
  108. } catch (Exception $e) {
  109. if ($e->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  110. // A different process might have written another status
  111. // update to the DB while we're processing our stuff.
  112. // We cannot safely restore the status as we don't know which one is valid at this point
  113. // So let's silently log this one and exit
  114. $this->logger->debug('Unique constraint violation for live user status', ['exception' => $e]);
  115. return;
  116. }
  117. }
  118. $this->logger->debug('No status relevant events found, skipping calendar status change', ['user' => $userId]);
  119. return;
  120. }
  121. // Only update the status if it's neccesary otherwise we mess up the timestamp
  122. if ($currentStatus === null || $currentStatus->getMessageId() !== IUserStatus::MESSAGE_CALENDAR_BUSY) {
  123. // One event that fulfills all status conditions is enough
  124. // 1. Not an OOO event
  125. // 2. Current user status (that is not a calendar status) was not set after the start of this event
  126. // 3. Event is not set to be transparent
  127. $count = count($applicableEvents);
  128. $this->logger->debug("Found $count applicable event(s), changing user status", ['user' => $userId]);
  129. $this->userStatusService->setUserStatus(
  130. $userId,
  131. IUserStatus::AWAY,
  132. IUserStatus::MESSAGE_CALENDAR_BUSY,
  133. true
  134. );
  135. }
  136. }
  137. private function getCalendarEvents(User $user): array {
  138. $calendars = $this->calendarManager->getCalendarsForPrincipal('principals/users/' . $user->getUID());
  139. if (empty($calendars)) {
  140. return [];
  141. }
  142. $query = $this->calendarManager->newQuery('principals/users/' . $user->getUID());
  143. foreach ($calendars as $calendarObject) {
  144. // We can only work with a calendar if it exposes its scheduling information
  145. if (!$calendarObject instanceof CalendarImpl) {
  146. continue;
  147. }
  148. $sct = $calendarObject->getSchedulingTransparency();
  149. if ($sct !== null && strtolower($sct->getValue()) == ScheduleCalendarTransp::TRANSPARENT) {
  150. // If a calendar is marked as 'transparent', it means we must
  151. // ignore it for free-busy purposes.
  152. continue;
  153. }
  154. $query->addSearchCalendar($calendarObject->getUri());
  155. }
  156. $dtStart = DateTimeImmutable::createFromMutable($this->timeFactory->getDateTime());
  157. $dtEnd = DateTimeImmutable::createFromMutable($this->timeFactory->getDateTime('+5 minutes'));
  158. // Only query the calendars when there's any to search
  159. if ($query instanceof CalendarQuery && !empty($query->getCalendarUris())) {
  160. // Query the next hour
  161. $query->setTimerangeStart($dtStart);
  162. $query->setTimerangeEnd($dtEnd);
  163. return $this->calendarManager->searchForPrincipal($query);
  164. }
  165. return [];
  166. }
  167. }