StatusService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. if ($userStatus->getId() === null) {
  210. return $this->mapper->insert($userStatus);
  211. }
  212. return $this->mapper->update($userStatus);
  213. }
  214. /**
  215. * @param string $userId
  216. * @param string $status
  217. * @param string $messageId
  218. * @param bool $createBackup
  219. * @throws InvalidStatusTypeException
  220. * @throws InvalidMessageIdException
  221. */
  222. public function setUserStatus(string $userId,
  223. string $status,
  224. string $messageId,
  225. bool $createBackup): void {
  226. // Check if status-type is valid
  227. if (!\in_array($status, self::PRIORITY_ORDERED_STATUSES, true)) {
  228. throw new InvalidStatusTypeException('Status-type "' . $status . '" is not supported');
  229. }
  230. if (!$this->predefinedStatusService->isValidId($messageId)) {
  231. throw new InvalidMessageIdException('Message-Id "' . $messageId . '" is not supported');
  232. }
  233. if ($createBackup) {
  234. if ($this->backupCurrentStatus($userId) === false) {
  235. return; // Already a status set automatically => abort.
  236. }
  237. // If we just created the backup
  238. $userStatus = new UserStatus();
  239. $userStatus->setUserId($userId);
  240. } else {
  241. try {
  242. $userStatus = $this->mapper->findByUserId($userId);
  243. } catch (DoesNotExistException $ex) {
  244. $userStatus = new UserStatus();
  245. $userStatus->setUserId($userId);
  246. }
  247. }
  248. $userStatus->setStatus($status);
  249. $userStatus->setStatusTimestamp($this->timeFactory->getTime());
  250. $userStatus->setIsUserDefined(true);
  251. $userStatus->setIsBackup(false);
  252. $userStatus->setMessageId($messageId);
  253. $userStatus->setCustomIcon(null);
  254. $userStatus->setCustomMessage(null);
  255. $userStatus->setClearAt(null);
  256. if ($userStatus->getId() !== null) {
  257. $this->mapper->update($userStatus);
  258. return;
  259. }
  260. $this->mapper->insert($userStatus);
  261. }
  262. /**
  263. * @param string $userId
  264. * @param string|null $statusIcon
  265. * @param string|null $message
  266. * @param int|null $clearAt
  267. * @return UserStatus
  268. * @throws InvalidClearAtException
  269. * @throws InvalidStatusIconException
  270. * @throws StatusMessageTooLongException
  271. */
  272. public function setCustomMessage(string $userId,
  273. ?string $statusIcon,
  274. ?string $message,
  275. ?int $clearAt): UserStatus {
  276. try {
  277. $userStatus = $this->mapper->findByUserId($userId);
  278. } catch (DoesNotExistException $ex) {
  279. $userStatus = new UserStatus();
  280. $userStatus->setUserId($userId);
  281. $userStatus->setStatus(IUserStatus::OFFLINE);
  282. $userStatus->setStatusTimestamp(0);
  283. $userStatus->setIsUserDefined(false);
  284. }
  285. // Check if statusIcon contains only one character
  286. if ($statusIcon !== null && !$this->emojiHelper->isValidSingleEmoji($statusIcon)) {
  287. throw new InvalidStatusIconException('Status-Icon is longer than one character');
  288. }
  289. // Check for maximum length of custom message
  290. if ($message !== null && \mb_strlen($message) > self::MAXIMUM_MESSAGE_LENGTH) {
  291. throw new StatusMessageTooLongException('Message is longer than supported length of ' . self::MAXIMUM_MESSAGE_LENGTH . ' characters');
  292. }
  293. // Check that clearAt is in the future
  294. if ($clearAt !== null && $clearAt < $this->timeFactory->getTime()) {
  295. throw new InvalidClearAtException('ClearAt is in the past');
  296. }
  297. $userStatus->setMessageId(null);
  298. $userStatus->setCustomIcon($statusIcon);
  299. $userStatus->setCustomMessage($message);
  300. $userStatus->setClearAt($clearAt);
  301. if ($userStatus->getId() === null) {
  302. return $this->mapper->insert($userStatus);
  303. }
  304. return $this->mapper->update($userStatus);
  305. }
  306. /**
  307. * @param string $userId
  308. * @return bool
  309. */
  310. public function clearStatus(string $userId): bool {
  311. try {
  312. $userStatus = $this->mapper->findByUserId($userId);
  313. } catch (DoesNotExistException $ex) {
  314. // if there is no status to remove, just return
  315. return false;
  316. }
  317. $userStatus->setStatus(IUserStatus::OFFLINE);
  318. $userStatus->setStatusTimestamp(0);
  319. $userStatus->setIsUserDefined(false);
  320. $this->mapper->update($userStatus);
  321. return true;
  322. }
  323. /**
  324. * @param string $userId
  325. * @return bool
  326. */
  327. public function clearMessage(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->setMessageId(null);
  335. $userStatus->setCustomMessage(null);
  336. $userStatus->setCustomIcon(null);
  337. $userStatus->setClearAt(null);
  338. $this->mapper->update($userStatus);
  339. return true;
  340. }
  341. /**
  342. * @param string $userId
  343. * @return bool
  344. */
  345. public function removeUserStatus(string $userId): bool {
  346. try {
  347. $userStatus = $this->mapper->findByUserId($userId, false);
  348. } catch (DoesNotExistException $ex) {
  349. // if there is no status to remove, just return
  350. return false;
  351. }
  352. $this->mapper->delete($userStatus);
  353. return true;
  354. }
  355. public function removeBackupUserStatus(string $userId): bool {
  356. try {
  357. $userStatus = $this->mapper->findByUserId($userId, true);
  358. } catch (DoesNotExistException $ex) {
  359. // if there is no status to remove, just return
  360. return false;
  361. }
  362. $this->mapper->delete($userStatus);
  363. return true;
  364. }
  365. /**
  366. * Processes a status to check if custom message is still
  367. * up to date and provides translated default status if needed
  368. *
  369. * @param UserStatus $status
  370. * @return UserStatus
  371. */
  372. private function processStatus(UserStatus $status): UserStatus {
  373. $clearAt = $status->getClearAt();
  374. if ($status->getStatusTimestamp() < $this->timeFactory->getTime() - self::INVALIDATE_STATUS_THRESHOLD
  375. && (!$status->getIsUserDefined() || $status->getStatus() === IUserStatus::ONLINE)) {
  376. $this->cleanStatus($status);
  377. }
  378. if ($clearAt !== null && $clearAt < $this->timeFactory->getTime()) {
  379. $this->cleanStatus($status);
  380. $this->cleanStatusMessage($status);
  381. }
  382. if ($status->getMessageId() !== null) {
  383. $this->addDefaultMessage($status);
  384. }
  385. return $status;
  386. }
  387. /**
  388. * @param UserStatus $status
  389. */
  390. private function cleanStatus(UserStatus $status): void {
  391. if ($status->getStatus() === IUserStatus::OFFLINE && !$status->getIsUserDefined()) {
  392. return;
  393. }
  394. $status->setStatus(IUserStatus::OFFLINE);
  395. $status->setStatusTimestamp($this->timeFactory->getTime());
  396. $status->setIsUserDefined(false);
  397. $this->mapper->update($status);
  398. }
  399. /**
  400. * @param UserStatus $status
  401. */
  402. private function cleanStatusMessage(UserStatus $status): void {
  403. $status->setMessageId(null);
  404. $status->setCustomIcon(null);
  405. $status->setCustomMessage(null);
  406. $status->setClearAt(null);
  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. $status->setCustomMessage($predefinedMessage['message']);
  417. $status->setCustomIcon($predefinedMessage['icon']);
  418. }
  419. }
  420. /**
  421. * @return bool false if there is already a backup. In this case abort the procedure.
  422. */
  423. public function backupCurrentStatus(string $userId): bool {
  424. try {
  425. $this->mapper->createBackupStatus($userId);
  426. return true;
  427. } catch (Exception $ex) {
  428. if ($ex->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  429. return false;
  430. }
  431. throw $ex;
  432. }
  433. }
  434. public function revertUserStatus(string $userId, string $messageId): void {
  435. try {
  436. /** @var UserStatus $userStatus */
  437. $backupUserStatus = $this->mapper->findByUserId($userId, true);
  438. } catch (DoesNotExistException $ex) {
  439. // No user status to revert, do nothing
  440. return;
  441. }
  442. $deleted = $this->mapper->deleteCurrentStatusToRestoreBackup($userId, $messageId);
  443. if (!$deleted) {
  444. // Another status is set automatically or no status, do nothing
  445. return;
  446. }
  447. $backupUserStatus->setIsBackup(false);
  448. // Remove the underscore prefix added when creating the backup
  449. $backupUserStatus->setUserId(substr($backupUserStatus->getUserId(), 1));
  450. $this->mapper->update($backupUserStatus);
  451. }
  452. public function revertMultipleUserStatus(array $userIds, string $messageId): void {
  453. // Get all user statuses and the backups
  454. $findById = $userIds;
  455. foreach ($userIds as $userId) {
  456. $findById[] = '_' . $userId;
  457. }
  458. $userStatuses = $this->mapper->findByUserIds($findById);
  459. $backups = $restoreIds = $statuesToDelete = [];
  460. foreach ($userStatuses as $userStatus) {
  461. if (!$userStatus->getIsBackup()
  462. && $userStatus->getMessageId() === $messageId) {
  463. $statuesToDelete[$userStatus->getUserId()] = $userStatus->getId();
  464. } else if ($userStatus->getIsBackup()) {
  465. $backups[$userStatus->getUserId()] = $userStatus->getId();
  466. }
  467. }
  468. // For users with both (normal and backup) delete the status when matching
  469. foreach ($statuesToDelete as $userId => $statusId) {
  470. $backupUserId = '_' . $userId;
  471. if (isset($backups[$backupUserId])) {
  472. $restoreIds[] = $backups[$backupUserId];
  473. }
  474. }
  475. $this->mapper->deleteByIds(array_values($statuesToDelete));
  476. // For users that matched restore the previous status
  477. $this->mapper->restoreBackupStatuses($restoreIds);
  478. }
  479. }