UserStatusAutomation.php 10 KB

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