1
0

StatusService.php 18 KB

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