StatusService.php 17 KB

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