StatusService.php 17 KB

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