UserStatusAutomation.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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 = new \DateTime('now');
  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 \DateTimeInterface $effectiveStart */
  96. /** @var \DateTimeInterface $effectiveEnd */
  97. [$effectiveStart, $effectiveEnd] = $available->getEffectiveStartEnd();
  98. try {
  99. $it = new RRuleIterator((string) $available->RRULE, $effectiveStart);
  100. $it->fastForward($lastMidnight);
  101. $startToday = $it->current();
  102. if ($startToday && $startToday <= $now) {
  103. $duration = $effectiveStart->diff($effectiveEnd);
  104. $endToday = $startToday->add($duration);
  105. if ($endToday > $now) {
  106. // User is currently available
  107. // Also queuing the end time as next status toggle
  108. $isCurrentlyAvailable = true;
  109. $nextPotentialToggles[] = $endToday->getTimestamp();
  110. }
  111. // Availability enabling already done for today,
  112. // so jump to the next recurrence to find the next status toggle
  113. $it->next();
  114. }
  115. if ($it->current()) {
  116. $nextPotentialToggles[] = $it->current()->getTimestamp();
  117. }
  118. } catch (\Exception $e) {
  119. $this->logger->error($e->getMessage(), ['exception' => $e]);
  120. }
  121. }
  122. }
  123. }
  124. $nextAutomaticToggle = min($nextPotentialToggles);
  125. $this->setLastRunToNextToggleTime($userId, $nextAutomaticToggle - 1);
  126. if ($isCurrentlyAvailable) {
  127. $this->manager->revertUserStatus($userId, IUserStatus::MESSAGE_AVAILABILITY, IUserStatus::DND);
  128. } else {
  129. // The DND status automation is more important than the "Away - In call" so we also restore that one if it exists.
  130. $this->manager->revertUserStatus($userId, IUserStatus::MESSAGE_CALL, IUserStatus::AWAY);
  131. $this->manager->setUserStatus($userId, IUserStatus::MESSAGE_AVAILABILITY, IUserStatus::DND, true);
  132. }
  133. $this->logger->debug('User status automation ran');
  134. }
  135. protected function setLastRunToNextToggleTime(string $userId, int $timestamp): void {
  136. $query = $this->connection->getQueryBuilder();
  137. $query->update('jobs')
  138. ->set('last_run', $query->createNamedParameter($timestamp, IQueryBuilder::PARAM_INT))
  139. ->where($query->expr()->eq('id', $query->createNamedParameter($this->getId(), IQueryBuilder::PARAM_INT)));
  140. $query->executeStatement();
  141. $this->logger->debug('Updated user status automation last_run to ' . $timestamp . ' for user ' . $userId);
  142. }
  143. /**
  144. * @param string $userId
  145. * @return false|string
  146. */
  147. protected function getAvailabilityFromPropertiesTable(string $userId) {
  148. $propertyPath = 'calendars/' . $userId . '/inbox';
  149. $propertyName = '{' . Plugin::NS_CALDAV . '}calendar-availability';
  150. $query = $this->connection->getQueryBuilder();
  151. $query->select('propertyvalue')
  152. ->from('properties')
  153. ->where($query->expr()->eq('userid', $query->createNamedParameter($userId)))
  154. ->andWhere($query->expr()->eq('propertypath', $query->createNamedParameter($propertyPath)))
  155. ->where($query->expr()->eq('propertyname', $query->createNamedParameter($propertyName)))
  156. ->setMaxResults(1);
  157. $result = $query->executeQuery();
  158. $property = $result->fetchOne();
  159. $result->closeCursor();
  160. return $property;
  161. }
  162. }