UserStatusAutomation.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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\UserStatus\IManager;
  31. use OCP\UserStatus\IUserStatus;
  32. use Psr\Log\LoggerInterface;
  33. use Sabre\VObject\Component\Available;
  34. use Sabre\VObject\Component\VAvailability;
  35. use Sabre\VObject\Reader;
  36. use Sabre\VObject\Recur\RRuleIterator;
  37. class UserStatusAutomation extends TimedJob {
  38. protected IDBConnection $connection;
  39. protected IJobList $jobList;
  40. protected LoggerInterface $logger;
  41. protected IManager $manager;
  42. protected IConfig $config;
  43. public function __construct(ITimeFactory $timeFactory,
  44. IDBConnection $connection,
  45. IJobList $jobList,
  46. LoggerInterface $logger,
  47. IManager $manager,
  48. IConfig $config) {
  49. parent::__construct($timeFactory);
  50. $this->connection = $connection;
  51. $this->jobList = $jobList;
  52. $this->logger = $logger;
  53. $this->manager = $manager;
  54. $this->config = $config;
  55. // Interval 0 might look weird, but the last_checked is always moved
  56. // to the next time we need this and then it's 0 seconds ago.
  57. $this->setInterval(0);
  58. }
  59. /**
  60. * @inheritDoc
  61. */
  62. protected function run($argument) {
  63. if (!isset($argument['userId'])) {
  64. $this->jobList->remove(self::class, $argument);
  65. $this->logger->info('Removing invalid ' . self::class . ' background job');
  66. return;
  67. }
  68. $userId = $argument['userId'];
  69. $automationEnabled = $this->config->getUserValue($userId, 'dav', 'user_status_automation', 'no') === 'yes';
  70. if (!$automationEnabled) {
  71. $this->logger->info('Removing ' . self::class . ' background job for user "' . $userId . '" because the setting is disabled');
  72. $this->jobList->remove(self::class, $argument);
  73. return;
  74. }
  75. $property = $this->getAvailabilityFromPropertiesTable($userId);
  76. if (!$property) {
  77. $this->logger->info('Removing ' . self::class . ' background job for user "' . $userId . '" because the user has no availability settings');
  78. $this->jobList->remove(self::class, $argument);
  79. return;
  80. }
  81. $isCurrentlyAvailable = false;
  82. $nextPotentialToggles = [];
  83. $now = $this->time->getDateTime();
  84. $lastMidnight = (clone $now)->setTime(0, 0);
  85. $vObject = Reader::read($property);
  86. foreach ($vObject->getComponents() as $component) {
  87. if ($component->name !== 'VAVAILABILITY') {
  88. continue;
  89. }
  90. /** @var VAvailability $component */
  91. $availables = $component->getComponents();
  92. foreach ($availables as $available) {
  93. /** @var Available $available */
  94. if ($available->name === 'AVAILABLE') {
  95. /** @var \DateTimeImmutable $originalStart */
  96. /** @var \DateTimeImmutable $originalEnd */
  97. [$originalStart, $originalEnd] = $available->getEffectiveStartEnd();
  98. // Little shenanigans to fix the automation on the day the rules were adjusted
  99. // Otherwise the $originalStart would match rules for Thursdays on a Friday, etc.
  100. // So we simply wind back a week and then fastForward to the next occurrence
  101. // since today's midnight, which then also accounts for the week days.
  102. $effectiveStart = \DateTime::createFromImmutable($originalStart)->sub(new \DateInterval('P7D'));
  103. $effectiveEnd = \DateTime::createFromImmutable($originalEnd)->sub(new \DateInterval('P7D'));
  104. try {
  105. $it = new RRuleIterator((string) $available->RRULE, $effectiveStart);
  106. $it->fastForward($lastMidnight);
  107. $startToday = $it->current();
  108. if ($startToday && $startToday <= $now) {
  109. $duration = $effectiveStart->diff($effectiveEnd);
  110. $endToday = $startToday->add($duration);
  111. if ($endToday > $now) {
  112. // User is currently available
  113. // Also queuing the end time as next status toggle
  114. $isCurrentlyAvailable = true;
  115. $nextPotentialToggles[] = $endToday->getTimestamp();
  116. }
  117. // Availability enabling already done for today,
  118. // so jump to the next recurrence to find the next status toggle
  119. $it->next();
  120. }
  121. if ($it->current()) {
  122. $nextPotentialToggles[] = $it->current()->getTimestamp();
  123. }
  124. } catch (\Exception $e) {
  125. $this->logger->error($e->getMessage(), ['exception' => $e]);
  126. }
  127. }
  128. }
  129. }
  130. if (empty($nextPotentialToggles)) {
  131. $this->logger->info('Removing ' . self::class . ' background job for user "' . $userId . '" because the user has no valid availability rules set');
  132. $this->jobList->remove(self::class, $argument);
  133. $this->manager->revertUserStatus($userId, IUserStatus::MESSAGE_AVAILABILITY, IUserStatus::DND);
  134. return;
  135. }
  136. $nextAutomaticToggle = min($nextPotentialToggles);
  137. $this->setLastRunToNextToggleTime($userId, $nextAutomaticToggle - 1);
  138. if ($isCurrentlyAvailable) {
  139. $this->logger->debug('User is currently available, reverting DND status if applicable');
  140. $this->manager->revertUserStatus($userId, IUserStatus::MESSAGE_AVAILABILITY, IUserStatus::DND);
  141. } else {
  142. $this->logger->debug('User is currently NOT available, reverting call status if applicable and then setting DND');
  143. // The DND status automation is more important than the "Away - In call" so we also restore that one if it exists.
  144. $this->manager->revertUserStatus($userId, IUserStatus::MESSAGE_CALL, IUserStatus::AWAY);
  145. $this->manager->setUserStatus($userId, IUserStatus::MESSAGE_AVAILABILITY, IUserStatus::DND, true);
  146. }
  147. $this->logger->debug('User status automation ran');
  148. }
  149. protected function setLastRunToNextToggleTime(string $userId, int $timestamp): void {
  150. $query = $this->connection->getQueryBuilder();
  151. $query->update('jobs')
  152. ->set('last_run', $query->createNamedParameter($timestamp, IQueryBuilder::PARAM_INT))
  153. ->where($query->expr()->eq('id', $query->createNamedParameter($this->getId(), IQueryBuilder::PARAM_INT)));
  154. $query->executeStatement();
  155. $this->logger->debug('Updated user status automation last_run to ' . $timestamp . ' for user ' . $userId);
  156. }
  157. /**
  158. * @param string $userId
  159. * @return false|string
  160. */
  161. protected function getAvailabilityFromPropertiesTable(string $userId) {
  162. $propertyPath = 'calendars/' . $userId . '/inbox';
  163. $propertyName = '{' . Plugin::NS_CALDAV . '}calendar-availability';
  164. $query = $this->connection->getQueryBuilder();
  165. $query->select('propertyvalue')
  166. ->from('properties')
  167. ->where($query->expr()->eq('userid', $query->createNamedParameter($userId)))
  168. ->andWhere($query->expr()->eq('propertypath', $query->createNamedParameter($propertyPath)))
  169. ->andWhere($query->expr()->eq('propertyname', $query->createNamedParameter($propertyName)))
  170. ->setMaxResults(1);
  171. $result = $query->executeQuery();
  172. $property = $result->fetchOne();
  173. $result->closeCursor();
  174. return $property;
  175. }
  176. }