1
0

StatusService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\UserStatus\Service;
  8. use OCA\UserStatus\Db\UserStatus;
  9. use OCA\UserStatus\Db\UserStatusMapper;
  10. use OCA\UserStatus\Exception\InvalidClearAtException;
  11. use OCA\UserStatus\Exception\InvalidMessageIdException;
  12. use OCA\UserStatus\Exception\InvalidStatusIconException;
  13. use OCA\UserStatus\Exception\InvalidStatusTypeException;
  14. use OCA\UserStatus\Exception\StatusMessageTooLongException;
  15. use OCP\AppFramework\Db\DoesNotExistException;
  16. use OCP\AppFramework\Utility\ITimeFactory;
  17. use OCP\DB\Exception;
  18. use OCP\IConfig;
  19. use OCP\IEmojiHelper;
  20. use OCP\IUserManager;
  21. use OCP\UserStatus\IUserStatus;
  22. use Psr\Log\LoggerInterface;
  23. use function in_array;
  24. /**
  25. * Class StatusService
  26. *
  27. * @package OCA\UserStatus\Service
  28. */
  29. class StatusService {
  30. private bool $shareeEnumeration;
  31. private bool $shareeEnumerationInGroupOnly;
  32. private bool $shareeEnumerationPhone;
  33. /**
  34. * List of priorities ordered by their priority
  35. */
  36. public const PRIORITY_ORDERED_STATUSES = [
  37. IUserStatus::ONLINE,
  38. IUserStatus::AWAY,
  39. IUserStatus::DND,
  40. IUserStatus::BUSY,
  41. IUserStatus::INVISIBLE,
  42. IUserStatus::OFFLINE,
  43. ];
  44. /**
  45. * List of statuses that persist the clear-up
  46. * or UserLiveStatusEvents
  47. */
  48. public const PERSISTENT_STATUSES = [
  49. IUserStatus::AWAY,
  50. IUserStatus::BUSY,
  51. IUserStatus::DND,
  52. IUserStatus::INVISIBLE,
  53. ];
  54. /** @var int */
  55. public const INVALIDATE_STATUS_THRESHOLD = 15 /* minutes */ * 60 /* seconds */;
  56. /** @var int */
  57. public const MAXIMUM_MESSAGE_LENGTH = 80;
  58. public function __construct(
  59. private UserStatusMapper $mapper,
  60. private ITimeFactory $timeFactory,
  61. private PredefinedStatusService $predefinedStatusService,
  62. private IEmojiHelper $emojiHelper,
  63. private IConfig $config,
  64. private IUserManager $userManager,
  65. private LoggerInterface $logger,
  66. ) {
  67. $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
  68. $this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
  69. $this->shareeEnumerationPhone = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
  70. }
  71. /**
  72. * @param int|null $limit
  73. * @param int|null $offset
  74. * @return UserStatus[]
  75. */
  76. public function findAll(?int $limit = null, ?int $offset = null): array {
  77. // Return empty array if user enumeration is disabled or limited to groups
  78. // TODO: find a solution that scales to get only users from common groups if user enumeration is limited to
  79. // groups. See discussion at https://github.com/nextcloud/server/pull/27879#discussion_r729715936
  80. if (!$this->shareeEnumeration || $this->shareeEnumerationInGroupOnly || $this->shareeEnumerationPhone) {
  81. return [];
  82. }
  83. return array_map(function ($status) {
  84. return $this->processStatus($status);
  85. }, $this->mapper->findAll($limit, $offset));
  86. }
  87. /**
  88. * @param int|null $limit
  89. * @param int|null $offset
  90. * @return array
  91. */
  92. public function findAllRecentStatusChanges(?int $limit = null, ?int $offset = null): array {
  93. // Return empty array if user enumeration is disabled or limited to groups
  94. // TODO: find a solution that scales to get only users from common groups if user enumeration is limited to
  95. // groups. See discussion at https://github.com/nextcloud/server/pull/27879#discussion_r729715936
  96. if (!$this->shareeEnumeration || $this->shareeEnumerationInGroupOnly || $this->shareeEnumerationPhone) {
  97. return [];
  98. }
  99. return array_map(function ($status) {
  100. return $this->processStatus($status);
  101. }, $this->mapper->findAllRecent($limit, $offset));
  102. }
  103. /**
  104. * @param string $userId
  105. * @return UserStatus
  106. * @throws DoesNotExistException
  107. */
  108. public function findByUserId(string $userId): UserStatus {
  109. return $this->processStatus($this->mapper->findByUserId($userId));
  110. }
  111. /**
  112. * @param array $userIds
  113. * @return UserStatus[]
  114. */
  115. public function findByUserIds(array $userIds):array {
  116. return array_map(function ($status) {
  117. return $this->processStatus($status);
  118. }, $this->mapper->findByUserIds($userIds));
  119. }
  120. /**
  121. * @param string $userId
  122. * @param string $status
  123. * @param int|null $statusTimestamp
  124. * @param bool $isUserDefined
  125. * @return UserStatus
  126. * @throws InvalidStatusTypeException
  127. */
  128. public function setStatus(string $userId,
  129. string $status,
  130. ?int $statusTimestamp,
  131. bool $isUserDefined): UserStatus {
  132. try {
  133. $userStatus = $this->mapper->findByUserId($userId);
  134. } catch (DoesNotExistException $ex) {
  135. $userStatus = new UserStatus();
  136. $userStatus->setUserId($userId);
  137. }
  138. // Check if status-type is valid
  139. if (!in_array($status, self::PRIORITY_ORDERED_STATUSES, true)) {
  140. throw new InvalidStatusTypeException('Status-type "' . $status . '" is not supported');
  141. }
  142. if ($statusTimestamp === null) {
  143. $statusTimestamp = $this->timeFactory->getTime();
  144. }
  145. $userStatus->setStatus($status);
  146. $userStatus->setStatusTimestamp($statusTimestamp);
  147. $userStatus->setIsUserDefined($isUserDefined);
  148. $userStatus->setIsBackup(false);
  149. if ($userStatus->getId() === null) {
  150. return $this->mapper->insert($userStatus);
  151. }
  152. return $this->mapper->update($userStatus);
  153. }
  154. /**
  155. * @param string $userId
  156. * @param string $messageId
  157. * @param int|null $clearAt
  158. * @return UserStatus
  159. * @throws InvalidMessageIdException
  160. * @throws InvalidClearAtException
  161. */
  162. public function setPredefinedMessage(string $userId,
  163. string $messageId,
  164. ?int $clearAt): UserStatus {
  165. try {
  166. $userStatus = $this->mapper->findByUserId($userId);
  167. } catch (DoesNotExistException $ex) {
  168. $userStatus = new UserStatus();
  169. $userStatus->setUserId($userId);
  170. $userStatus->setStatus(IUserStatus::OFFLINE);
  171. $userStatus->setStatusTimestamp(0);
  172. $userStatus->setIsUserDefined(false);
  173. $userStatus->setIsBackup(false);
  174. }
  175. if (!$this->predefinedStatusService->isValidId($messageId)) {
  176. throw new InvalidMessageIdException('Message-Id "' . $messageId . '" is not supported');
  177. }
  178. // Check that clearAt is in the future
  179. if ($clearAt !== null && $clearAt < $this->timeFactory->getTime()) {
  180. throw new InvalidClearAtException('ClearAt is in the past');
  181. }
  182. $userStatus->setMessageId($messageId);
  183. $userStatus->setCustomIcon(null);
  184. $userStatus->setCustomMessage(null);
  185. $userStatus->setClearAt($clearAt);
  186. $userStatus->setStatusMessageTimestamp($this->timeFactory->now()->getTimestamp());
  187. if ($userStatus->getId() === null) {
  188. return $this->mapper->insert($userStatus);
  189. }
  190. return $this->mapper->update($userStatus);
  191. }
  192. /**
  193. * @param string $userId
  194. * @param string $status
  195. * @param string $messageId
  196. * @param bool $createBackup
  197. * @param string|null $customMessage
  198. * @throws InvalidStatusTypeException
  199. * @throws InvalidMessageIdException
  200. */
  201. public function setUserStatus(string $userId,
  202. string $status,
  203. string $messageId,
  204. bool $createBackup,
  205. ?string $customMessage = null): ?UserStatus {
  206. // Check if status-type is valid
  207. if (!in_array($status, self::PRIORITY_ORDERED_STATUSES, true)) {
  208. throw new InvalidStatusTypeException('Status-type "' . $status . '" is not supported');
  209. }
  210. if (!$this->predefinedStatusService->isValidId($messageId)) {
  211. throw new InvalidMessageIdException('Message-Id "' . $messageId . '" is not supported');
  212. }
  213. try {
  214. $userStatus = $this->mapper->findByUserId($userId);
  215. } catch (DoesNotExistException $e) {
  216. // We don't need to do anything
  217. $userStatus = new UserStatus();
  218. $userStatus->setUserId($userId);
  219. }
  220. $updateStatus = false;
  221. if ($messageId === IUserStatus::MESSAGE_OUT_OF_OFFICE) {
  222. // OUT_OF_OFFICE trumps AVAILABILITY, CALL and CALENDAR status
  223. $updateStatus = $userStatus->getMessageId() === IUserStatus::MESSAGE_AVAILABILITY || $userStatus->getMessageId() === IUserStatus::MESSAGE_CALL || $userStatus->getMessageId() === IUserStatus::MESSAGE_CALENDAR_BUSY;
  224. } elseif ($messageId === IUserStatus::MESSAGE_AVAILABILITY) {
  225. // AVAILABILITY trumps CALL and CALENDAR status
  226. $updateStatus = $userStatus->getMessageId() === IUserStatus::MESSAGE_CALL || $userStatus->getMessageId() === IUserStatus::MESSAGE_CALENDAR_BUSY;
  227. } elseif ($messageId === IUserStatus::MESSAGE_CALL) {
  228. // CALL trumps CALENDAR status
  229. $updateStatus = $userStatus->getMessageId() === IUserStatus::MESSAGE_CALENDAR_BUSY;
  230. }
  231. if ($messageId === IUserStatus::MESSAGE_OUT_OF_OFFICE || $messageId === IUserStatus::MESSAGE_AVAILABILITY || $messageId === IUserStatus::MESSAGE_CALL || $messageId === IUserStatus::MESSAGE_CALENDAR_BUSY) {
  232. if ($updateStatus) {
  233. $this->logger->debug('User ' . $userId . ' is currently NOT available, overwriting status [status: ' . $userStatus->getStatus() . ', messageId: ' . json_encode($userStatus->getMessageId()) . ']', ['app' => 'dav']);
  234. } else {
  235. $this->logger->debug('User ' . $userId . ' is currently NOT available, but we are NOT overwriting status [status: ' . $userStatus->getStatus() . ', messageId: ' . json_encode($userStatus->getMessageId()) . ']', ['app' => 'dav']);
  236. }
  237. }
  238. // There should be a backup already or none is needed. So we take a shortcut.
  239. if ($updateStatus) {
  240. $userStatus->setStatus($status);
  241. $userStatus->setStatusTimestamp($this->timeFactory->getTime());
  242. $userStatus->setIsUserDefined(true);
  243. $userStatus->setIsBackup(false);
  244. $userStatus->setMessageId($messageId);
  245. $userStatus->setCustomIcon(null);
  246. $userStatus->setCustomMessage($customMessage);
  247. $userStatus->setClearAt(null);
  248. $userStatus->setStatusMessageTimestamp($this->timeFactory->now()->getTimestamp());
  249. return $this->mapper->update($userStatus);
  250. }
  251. if ($createBackup) {
  252. if ($this->backupCurrentStatus($userId) === false) {
  253. return null; // Already a status set automatically => abort.
  254. }
  255. // If we just created the backup
  256. // we need to create a new status to insert
  257. // Unfortunately there's no way to unset the DB ID on an Entity
  258. $userStatus = new UserStatus();
  259. $userStatus->setUserId($userId);
  260. }
  261. $userStatus->setStatus($status);
  262. $userStatus->setStatusTimestamp($this->timeFactory->getTime());
  263. $userStatus->setIsUserDefined(true);
  264. $userStatus->setIsBackup(false);
  265. $userStatus->setMessageId($messageId);
  266. $userStatus->setCustomIcon(null);
  267. $userStatus->setCustomMessage($customMessage);
  268. $userStatus->setClearAt(null);
  269. if ($this->predefinedStatusService->getTranslatedStatusForId($messageId) !== null
  270. || ($customMessage !== null && $customMessage !== '')) {
  271. // Only track status message ID if there is one
  272. $userStatus->setStatusMessageTimestamp($this->timeFactory->now()->getTimestamp());
  273. } else {
  274. $userStatus->setStatusMessageTimestamp(0);
  275. }
  276. if ($userStatus->getId() !== null) {
  277. return $this->mapper->update($userStatus);
  278. }
  279. return $this->mapper->insert($userStatus);
  280. }
  281. /**
  282. * @param string $userId
  283. * @param string|null $statusIcon
  284. * @param string|null $message
  285. * @param int|null $clearAt
  286. * @return UserStatus
  287. * @throws InvalidClearAtException
  288. * @throws InvalidStatusIconException
  289. * @throws StatusMessageTooLongException
  290. */
  291. public function setCustomMessage(string $userId,
  292. ?string $statusIcon,
  293. ?string $message,
  294. ?int $clearAt): UserStatus {
  295. try {
  296. $userStatus = $this->mapper->findByUserId($userId);
  297. } catch (DoesNotExistException $ex) {
  298. $userStatus = new UserStatus();
  299. $userStatus->setUserId($userId);
  300. $userStatus->setStatus(IUserStatus::OFFLINE);
  301. $userStatus->setStatusTimestamp(0);
  302. $userStatus->setIsUserDefined(false);
  303. }
  304. // Check if statusIcon contains only one character
  305. if ($statusIcon !== null && !$this->emojiHelper->isValidSingleEmoji($statusIcon)) {
  306. throw new InvalidStatusIconException('Status-Icon is longer than one character');
  307. }
  308. // Check for maximum length of custom message
  309. if ($message !== null && \mb_strlen($message) > self::MAXIMUM_MESSAGE_LENGTH) {
  310. throw new StatusMessageTooLongException('Message is longer than supported length of ' . self::MAXIMUM_MESSAGE_LENGTH . ' characters');
  311. }
  312. // Check that clearAt is in the future
  313. if ($clearAt !== null && $clearAt < $this->timeFactory->getTime()) {
  314. throw new InvalidClearAtException('ClearAt is in the past');
  315. }
  316. $userStatus->setMessageId(null);
  317. $userStatus->setCustomIcon($statusIcon);
  318. $userStatus->setCustomMessage($message);
  319. $userStatus->setClearAt($clearAt);
  320. $userStatus->setStatusMessageTimestamp($this->timeFactory->now()->getTimestamp());
  321. if ($userStatus->getId() === null) {
  322. return $this->mapper->insert($userStatus);
  323. }
  324. return $this->mapper->update($userStatus);
  325. }
  326. /**
  327. * @param string $userId
  328. * @return bool
  329. */
  330. public function clearStatus(string $userId): bool {
  331. try {
  332. $userStatus = $this->mapper->findByUserId($userId);
  333. } catch (DoesNotExistException $ex) {
  334. // if there is no status to remove, just return
  335. return false;
  336. }
  337. $userStatus->setStatus(IUserStatus::OFFLINE);
  338. $userStatus->setStatusTimestamp(0);
  339. $userStatus->setIsUserDefined(false);
  340. $this->mapper->update($userStatus);
  341. return true;
  342. }
  343. /**
  344. * @param string $userId
  345. * @return bool
  346. */
  347. public function clearMessage(string $userId): bool {
  348. try {
  349. $userStatus = $this->mapper->findByUserId($userId);
  350. } catch (DoesNotExistException $ex) {
  351. // if there is no status to remove, just return
  352. return false;
  353. }
  354. $userStatus->setMessageId(null);
  355. $userStatus->setCustomMessage(null);
  356. $userStatus->setCustomIcon(null);
  357. $userStatus->setClearAt(null);
  358. $userStatus->setStatusMessageTimestamp(0);
  359. $this->mapper->update($userStatus);
  360. return true;
  361. }
  362. /**
  363. * @param string $userId
  364. * @return bool
  365. */
  366. public function removeUserStatus(string $userId): bool {
  367. try {
  368. $userStatus = $this->mapper->findByUserId($userId, false);
  369. } catch (DoesNotExistException $ex) {
  370. // if there is no status to remove, just return
  371. return false;
  372. }
  373. $this->mapper->delete($userStatus);
  374. return true;
  375. }
  376. public function removeBackupUserStatus(string $userId): bool {
  377. try {
  378. $userStatus = $this->mapper->findByUserId($userId, true);
  379. } catch (DoesNotExistException $ex) {
  380. // if there is no status to remove, just return
  381. return false;
  382. }
  383. $this->mapper->delete($userStatus);
  384. return true;
  385. }
  386. /**
  387. * Processes a status to check if custom message is still
  388. * up to date and provides translated default status if needed
  389. *
  390. * @param UserStatus $status
  391. * @return UserStatus
  392. */
  393. private function processStatus(UserStatus $status): UserStatus {
  394. $clearAt = $status->getClearAt();
  395. if ($status->getStatusTimestamp() < $this->timeFactory->getTime() - self::INVALIDATE_STATUS_THRESHOLD
  396. && (!$status->getIsUserDefined() || $status->getStatus() === IUserStatus::ONLINE)) {
  397. $this->cleanStatus($status);
  398. }
  399. if ($clearAt !== null && $clearAt < $this->timeFactory->getTime()) {
  400. $this->cleanStatus($status);
  401. $this->cleanStatusMessage($status);
  402. }
  403. if ($status->getMessageId() !== null) {
  404. $this->addDefaultMessage($status);
  405. }
  406. return $status;
  407. }
  408. /**
  409. * @param UserStatus $status
  410. */
  411. private function cleanStatus(UserStatus $status): void {
  412. if ($status->getStatus() === IUserStatus::OFFLINE && !$status->getIsUserDefined()) {
  413. return;
  414. }
  415. $status->setStatus(IUserStatus::OFFLINE);
  416. $status->setStatusTimestamp($this->timeFactory->getTime());
  417. $status->setIsUserDefined(false);
  418. $this->mapper->update($status);
  419. }
  420. /**
  421. * @param UserStatus $status
  422. */
  423. private function cleanStatusMessage(UserStatus $status): void {
  424. $status->setMessageId(null);
  425. $status->setCustomIcon(null);
  426. $status->setCustomMessage(null);
  427. $status->setClearAt(null);
  428. $status->setStatusMessageTimestamp(0);
  429. $this->mapper->update($status);
  430. }
  431. /**
  432. * @param UserStatus $status
  433. */
  434. private function addDefaultMessage(UserStatus $status): void {
  435. // If the message is predefined, insert the translated message and icon
  436. $predefinedMessage = $this->predefinedStatusService->getDefaultStatusById($status->getMessageId());
  437. if ($predefinedMessage === null) {
  438. return;
  439. }
  440. // If there is a custom message, don't overwrite it
  441. if (empty($status->getCustomMessage())) {
  442. $status->setCustomMessage($predefinedMessage['message']);
  443. }
  444. if (empty($status->getCustomIcon())) {
  445. $status->setCustomIcon($predefinedMessage['icon']);
  446. }
  447. }
  448. /**
  449. * @return bool false if there is already a backup. In this case abort the procedure.
  450. */
  451. public function backupCurrentStatus(string $userId): bool {
  452. try {
  453. $this->mapper->createBackupStatus($userId);
  454. return true;
  455. } catch (Exception $ex) {
  456. if ($ex->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  457. return false;
  458. }
  459. throw $ex;
  460. }
  461. }
  462. public function revertUserStatus(string $userId, string $messageId, bool $revertedManually = false): ?UserStatus {
  463. try {
  464. /** @var UserStatus $userStatus */
  465. $backupUserStatus = $this->mapper->findByUserId($userId, true);
  466. } catch (DoesNotExistException $ex) {
  467. // No user status to revert, do nothing
  468. return null;
  469. }
  470. $deleted = $this->mapper->deleteCurrentStatusToRestoreBackup($userId, $messageId);
  471. if (!$deleted) {
  472. // Another status is set automatically or no status, do nothing
  473. return null;
  474. }
  475. if ($revertedManually) {
  476. if ($backupUserStatus->getStatus() === IUserStatus::OFFLINE) {
  477. // When the user reverts the status manually they are online
  478. $backupUserStatus->setStatus(IUserStatus::ONLINE);
  479. }
  480. $backupUserStatus->setStatusTimestamp($this->timeFactory->getTime());
  481. }
  482. $backupUserStatus->setIsBackup(false);
  483. // Remove the underscore prefix added when creating the backup
  484. $backupUserStatus->setUserId(substr($backupUserStatus->getUserId(), 1));
  485. $this->mapper->update($backupUserStatus);
  486. return $backupUserStatus;
  487. }
  488. public function revertMultipleUserStatus(array $userIds, string $messageId): void {
  489. // Get all user statuses and the backups
  490. $findById = $userIds;
  491. foreach ($userIds as $userId) {
  492. $findById[] = '_' . $userId;
  493. }
  494. $userStatuses = $this->mapper->findByUserIds($findById);
  495. $backups = $restoreIds = $statuesToDelete = [];
  496. foreach ($userStatuses as $userStatus) {
  497. if (!$userStatus->getIsBackup()
  498. && $userStatus->getMessageId() === $messageId) {
  499. $statuesToDelete[$userStatus->getUserId()] = $userStatus->getId();
  500. } elseif ($userStatus->getIsBackup()) {
  501. $backups[$userStatus->getUserId()] = $userStatus->getId();
  502. }
  503. }
  504. // For users with both (normal and backup) delete the status when matching
  505. foreach ($statuesToDelete as $userId => $statusId) {
  506. $backupUserId = '_' . $userId;
  507. if (isset($backups[$backupUserId])) {
  508. $restoreIds[] = $backups[$backupUserId];
  509. }
  510. }
  511. $this->mapper->deleteByIds(array_values($statuesToDelete));
  512. // For users that matched restore the previous status
  513. $this->mapper->restoreBackupStatuses($restoreIds);
  514. }
  515. }