StatusService.php 7.6 KB

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