UserStatusAutomation.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\BackgroundJob;
  8. use OCA\DAV\CalDAV\Schedule\Plugin;
  9. use OCP\AppFramework\Utility\ITimeFactory;
  10. use OCP\BackgroundJob\IJobList;
  11. use OCP\BackgroundJob\TimedJob;
  12. use OCP\DB\QueryBuilder\IQueryBuilder;
  13. use OCP\IConfig;
  14. use OCP\IDBConnection;
  15. use OCP\IUser;
  16. use OCP\IUserManager;
  17. use OCP\User\IAvailabilityCoordinator;
  18. use OCP\User\IOutOfOfficeData;
  19. use OCP\UserStatus\IManager;
  20. use OCP\UserStatus\IUserStatus;
  21. use Psr\Log\LoggerInterface;
  22. use Sabre\VObject\Component\Available;
  23. use Sabre\VObject\Component\VAvailability;
  24. use Sabre\VObject\Reader;
  25. use Sabre\VObject\Recur\RRuleIterator;
  26. class UserStatusAutomation extends TimedJob {
  27. public function __construct(private ITimeFactory $timeFactory,
  28. private IDBConnection $connection,
  29. private IJobList $jobList,
  30. private LoggerInterface $logger,
  31. private IManager $manager,
  32. private IConfig $config,
  33. private IAvailabilityCoordinator $coordinator,
  34. private IUserManager $userManager) {
  35. parent::__construct($timeFactory);
  36. // Interval 0 might look weird, but the last_checked is always moved
  37. // to the next time we need this and then it's 0 seconds ago.
  38. $this->setInterval(0);
  39. }
  40. /**
  41. * @inheritDoc
  42. */
  43. protected function run($argument) {
  44. if (!isset($argument['userId'])) {
  45. $this->jobList->remove(self::class, $argument);
  46. $this->logger->info('Removing invalid ' . self::class . ' background job');
  47. return;
  48. }
  49. $userId = $argument['userId'];
  50. $user = $this->userManager->get($userId);
  51. if($user === null) {
  52. return;
  53. }
  54. $ooo = $this->coordinator->getCurrentOutOfOfficeData($user);
  55. $continue = $this->processOutOfOfficeData($user, $ooo);
  56. if($continue === false) {
  57. return;
  58. }
  59. $property = $this->getAvailabilityFromPropertiesTable($userId);
  60. $hasDndForOfficeHours = $this->config->getUserValue($userId, 'dav', 'user_status_automation', 'no') === 'yes';
  61. if (!$property) {
  62. // We found no ooo data and no availability settings, so we need to delete the job because there is no next runtime
  63. $this->logger->info('Removing ' . self::class . ' background job for user "' . $userId . '" because the user has no valid availability rules and no OOO data set');
  64. $this->jobList->remove(self::class, $argument);
  65. $this->manager->revertUserStatus($user->getUID(), IUserStatus::MESSAGE_AVAILABILITY, IUserStatus::DND);
  66. $this->manager->revertUserStatus($user->getUID(), IUserStatus::MESSAGE_OUT_OF_OFFICE, IUserStatus::DND);
  67. return;
  68. }
  69. $this->processAvailability($property, $user->getUID(), $hasDndForOfficeHours);
  70. }
  71. protected function setLastRunToNextToggleTime(string $userId, int $timestamp): void {
  72. $query = $this->connection->getQueryBuilder();
  73. $query->update('jobs')
  74. ->set('last_run', $query->createNamedParameter($timestamp, IQueryBuilder::PARAM_INT))
  75. ->where($query->expr()->eq('id', $query->createNamedParameter($this->getId(), IQueryBuilder::PARAM_INT)));
  76. $query->executeStatement();
  77. $this->logger->debug('Updated user status automation last_run to ' . $timestamp . ' for user ' . $userId);
  78. }
  79. /**
  80. * @param string $userId
  81. * @return false|string
  82. */
  83. protected function getAvailabilityFromPropertiesTable(string $userId) {
  84. $propertyPath = 'calendars/' . $userId . '/inbox';
  85. $propertyName = '{' . Plugin::NS_CALDAV . '}calendar-availability';
  86. $query = $this->connection->getQueryBuilder();
  87. $query->select('propertyvalue')
  88. ->from('properties')
  89. ->where($query->expr()->eq('userid', $query->createNamedParameter($userId)))
  90. ->andWhere($query->expr()->eq('propertypath', $query->createNamedParameter($propertyPath)))
  91. ->andWhere($query->expr()->eq('propertyname', $query->createNamedParameter($propertyName)))
  92. ->setMaxResults(1);
  93. $result = $query->executeQuery();
  94. $property = $result->fetchOne();
  95. $result->closeCursor();
  96. return $property;
  97. }
  98. /**
  99. * @param string $property
  100. * @param $userId
  101. * @param $argument
  102. * @return void
  103. */
  104. private function processAvailability(string $property, string $userId, bool $hasDndForOfficeHours): void {
  105. $isCurrentlyAvailable = false;
  106. $nextPotentialToggles = [];
  107. $now = $this->time->getDateTime();
  108. $lastMidnight = (clone $now)->setTime(0, 0);
  109. $vObject = Reader::read($property);
  110. foreach ($vObject->getComponents() as $component) {
  111. if ($component->name !== 'VAVAILABILITY') {
  112. continue;
  113. }
  114. /** @var VAvailability $component */
  115. $availables = $component->getComponents();
  116. foreach ($availables as $available) {
  117. /** @var Available $available */
  118. if ($available->name === 'AVAILABLE') {
  119. /** @var \DateTimeImmutable $originalStart */
  120. /** @var \DateTimeImmutable $originalEnd */
  121. [$originalStart, $originalEnd] = $available->getEffectiveStartEnd();
  122. // Little shenanigans to fix the automation on the day the rules were adjusted
  123. // Otherwise the $originalStart would match rules for Thursdays on a Friday, etc.
  124. // So we simply wind back a week and then fastForward to the next occurrence
  125. // since today's midnight, which then also accounts for the week days.
  126. $effectiveStart = \DateTime::createFromImmutable($originalStart)->sub(new \DateInterval('P7D'));
  127. $effectiveEnd = \DateTime::createFromImmutable($originalEnd)->sub(new \DateInterval('P7D'));
  128. try {
  129. $it = new RRuleIterator((string)$available->RRULE, $effectiveStart);
  130. $it->fastForward($lastMidnight);
  131. $startToday = $it->current();
  132. if ($startToday && $startToday <= $now) {
  133. $duration = $effectiveStart->diff($effectiveEnd);
  134. $endToday = $startToday->add($duration);
  135. if ($endToday > $now) {
  136. // User is currently available
  137. // Also queuing the end time as next status toggle
  138. $isCurrentlyAvailable = true;
  139. $nextPotentialToggles[] = $endToday->getTimestamp();
  140. }
  141. // Availability enabling already done for today,
  142. // so jump to the next recurrence to find the next status toggle
  143. $it->next();
  144. }
  145. if ($it->current()) {
  146. $nextPotentialToggles[] = $it->current()->getTimestamp();
  147. }
  148. } catch (\Exception $e) {
  149. $this->logger->error($e->getMessage(), ['exception' => $e]);
  150. }
  151. }
  152. }
  153. }
  154. if (empty($nextPotentialToggles)) {
  155. $this->logger->info('Removing ' . self::class . ' background job for user "' . $userId . '" because the user has no valid availability rules set');
  156. $this->jobList->remove(self::class, ['userId' => $userId]);
  157. $this->manager->revertUserStatus($userId, IUserStatus::MESSAGE_AVAILABILITY, IUserStatus::DND);
  158. return;
  159. }
  160. $nextAutomaticToggle = min($nextPotentialToggles);
  161. $this->setLastRunToNextToggleTime($userId, $nextAutomaticToggle - 1);
  162. if ($isCurrentlyAvailable) {
  163. $this->logger->debug('User is currently available, reverting DND status if applicable');
  164. $this->manager->revertUserStatus($userId, IUserStatus::MESSAGE_AVAILABILITY, IUserStatus::DND);
  165. $this->logger->debug('User status automation ran');
  166. return;
  167. }
  168. if(!$hasDndForOfficeHours) {
  169. // Office hours are not set to DND, so there is nothing to do.
  170. return;
  171. }
  172. $this->logger->debug('User is currently NOT available, reverting call and meeting status if applicable and then setting DND');
  173. $this->manager->setUserStatus($userId, IUserStatus::MESSAGE_AVAILABILITY, IUserStatus::DND, true);
  174. $this->logger->debug('User status automation ran');
  175. }
  176. private function processOutOfOfficeData(IUser $user, ?IOutOfOfficeData $ooo): bool {
  177. if(empty($ooo)) {
  178. // Reset the user status if the absence doesn't exist
  179. $this->logger->debug('User has no OOO period in effect, reverting DND status if applicable');
  180. $this->manager->revertUserStatus($user->getUID(), IUserStatus::MESSAGE_OUT_OF_OFFICE, IUserStatus::DND);
  181. // We need to also run the availability automation
  182. return true;
  183. }
  184. if(!$this->coordinator->isInEffect($ooo)) {
  185. // Reset the user status if the absence is (no longer) in effect
  186. $this->logger->debug('User has no OOO period in effect, reverting DND status if applicable');
  187. $this->manager->revertUserStatus($user->getUID(), IUserStatus::MESSAGE_OUT_OF_OFFICE, IUserStatus::DND);
  188. if($ooo->getStartDate() > $this->time->getTime()) {
  189. // Set the next run to take place at the start of the ooo period if it is in the future
  190. // This might be overwritten if there is an availability setting, but we can't determine
  191. // if this is the case here
  192. $this->setLastRunToNextToggleTime($user->getUID(), $ooo->getStartDate());
  193. }
  194. return true;
  195. }
  196. $this->logger->debug('User is currently in an OOO period, reverting other automated status and setting OOO DND status');
  197. $this->manager->setUserStatus($user->getUID(), IUserStatus::MESSAGE_OUT_OF_OFFICE, IUserStatus::DND, true, $ooo->getShortMessage());
  198. // Run at the end of an ooo period to return to availability / regular user status
  199. // If it's overwritten by a custom status in the meantime, there's nothing we can do about it
  200. $this->setLastRunToNextToggleTime($user->getUID(), $ooo->getEndDate());
  201. return false;
  202. }
  203. }