StatusService.php 6.9 KB

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