1
0

UserStatusAutomation.php 9.0 KB

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