Notifier.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. *
  10. * @license AGPL-3.0
  11. *
  12. * This code is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License, version 3,
  14. * as published by the Free Software Foundation.
  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, version 3,
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>
  23. *
  24. */
  25. namespace OCA\Comments\Notification;
  26. use OCP\Comments\IComment;
  27. use OCP\Comments\ICommentsManager;
  28. use OCP\Comments\NotFoundException;
  29. use OCP\Files\IRootFolder;
  30. use OCP\IURLGenerator;
  31. use OCP\IUserManager;
  32. use OCP\L10N\IFactory;
  33. use OCP\Notification\AlreadyProcessedException;
  34. use OCP\Notification\INotification;
  35. use OCP\Notification\INotifier;
  36. class Notifier implements INotifier {
  37. public function __construct(
  38. protected IFactory $l10nFactory,
  39. protected IRootFolder $rootFolder,
  40. protected ICommentsManager $commentsManager,
  41. protected IURLGenerator $url,
  42. protected IUserManager $userManager
  43. ) {
  44. }
  45. /**
  46. * Identifier of the notifier, only use [a-z0-9_]
  47. *
  48. * @return string
  49. * @since 17.0.0
  50. */
  51. public function getID(): string {
  52. return 'comments';
  53. }
  54. /**
  55. * Human readable name describing the notifier
  56. *
  57. * @return string
  58. * @since 17.0.0
  59. */
  60. public function getName(): string {
  61. return $this->l10nFactory->get('comments')->t('Comments');
  62. }
  63. /**
  64. * @param INotification $notification
  65. * @param string $languageCode The code of the language that should be used to prepare the notification
  66. * @return INotification
  67. * @throws \InvalidArgumentException When the notification was not prepared by a notifier
  68. * @throws AlreadyProcessedException When the notification is not needed anymore and should be deleted
  69. * @since 9.0.0
  70. */
  71. public function prepare(INotification $notification, string $languageCode): INotification {
  72. if ($notification->getApp() !== 'comments') {
  73. throw new \InvalidArgumentException();
  74. }
  75. try {
  76. $comment = $this->commentsManager->get($notification->getObjectId());
  77. } catch (NotFoundException $e) {
  78. // needs to be converted to InvalidArgumentException, otherwise none Notifications will be shown at all
  79. throw new \InvalidArgumentException('Comment not found', 0, $e);
  80. }
  81. $l = $this->l10nFactory->get('comments', $languageCode);
  82. $displayName = $comment->getActorId();
  83. $isDeletedActor = $comment->getActorType() === ICommentsManager::DELETED_USER;
  84. if ($comment->getActorType() === 'users') {
  85. $commenter = $this->userManager->getDisplayName($comment->getActorId());
  86. if ($commenter !== null) {
  87. $displayName = $commenter;
  88. }
  89. }
  90. switch ($notification->getSubject()) {
  91. case 'mention':
  92. $parameters = $notification->getSubjectParameters();
  93. if ($parameters[0] !== 'files') {
  94. throw new \InvalidArgumentException('Unsupported comment object');
  95. }
  96. $userFolder = $this->rootFolder->getUserFolder($notification->getUser());
  97. $nodes = $userFolder->getById((int)$parameters[1]);
  98. if (empty($nodes)) {
  99. throw new AlreadyProcessedException();
  100. }
  101. $node = $nodes[0];
  102. $path = rtrim($node->getPath(), '/');
  103. if (str_starts_with($path, '/' . $notification->getUser() . '/files/')) {
  104. // Remove /user/files/...
  105. $fullPath = $path;
  106. [,,, $path] = explode('/', $fullPath, 4);
  107. }
  108. $subjectParameters = [
  109. 'file' => [
  110. 'type' => 'file',
  111. 'id' => $comment->getObjectId(),
  112. 'name' => $node->getName(),
  113. 'path' => $path,
  114. 'link' => $this->url->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $comment->getObjectId()]),
  115. ],
  116. ];
  117. if ($isDeletedActor) {
  118. $subject = $l->t('You were mentioned on "{file}", in a comment by an account that has since been deleted');
  119. } else {
  120. $subject = $l->t('{user} mentioned you in a comment on "{file}"');
  121. $subjectParameters['user'] = [
  122. 'type' => 'user',
  123. 'id' => $comment->getActorId(),
  124. 'name' => $displayName,
  125. ];
  126. }
  127. [$message, $messageParameters] = $this->commentToRichMessage($comment);
  128. $notification->setRichSubject($subject, $subjectParameters)
  129. ->setRichMessage($message, $messageParameters)
  130. ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/comment.svg')))
  131. ->setLink($this->url->linkToRouteAbsolute(
  132. 'comments.Notifications.view',
  133. ['id' => $comment->getId()])
  134. );
  135. return $notification;
  136. break;
  137. default:
  138. throw new \InvalidArgumentException('Invalid subject');
  139. }
  140. }
  141. public function commentToRichMessage(IComment $comment): array {
  142. $message = $comment->getMessage();
  143. $messageParameters = [];
  144. $mentionTypeCount = [];
  145. $mentions = $comment->getMentions();
  146. foreach ($mentions as $mention) {
  147. if ($mention['type'] === 'user') {
  148. $userDisplayName = $this->userManager->getDisplayName($mention['id']);
  149. if ($userDisplayName === null) {
  150. continue;
  151. }
  152. }
  153. if (!array_key_exists($mention['type'], $mentionTypeCount)) {
  154. $mentionTypeCount[$mention['type']] = 0;
  155. }
  156. $mentionTypeCount[$mention['type']]++;
  157. // To keep a limited character set in parameter IDs ([a-zA-Z0-9-])
  158. // the mention parameter ID does not include the mention ID (which
  159. // could contain characters like '@' for user IDs) but a one-based
  160. // index of the mentions of that type.
  161. $mentionParameterId = 'mention-' . $mention['type'] . $mentionTypeCount[$mention['type']];
  162. $message = str_replace('@"' . $mention['id'] . '"', '{' . $mentionParameterId . '}', $message);
  163. if (!str_contains($mention['id'], ' ') && !str_starts_with($mention['id'], 'guest/')) {
  164. $message = str_replace('@' . $mention['id'], '{' . $mentionParameterId . '}', $message);
  165. }
  166. try {
  167. $displayName = $this->commentsManager->resolveDisplayName($mention['type'], $mention['id']);
  168. } catch (\OutOfBoundsException $e) {
  169. // There is no registered display name resolver for the mention
  170. // type, so the client decides what to display.
  171. $displayName = '';
  172. }
  173. $messageParameters[$mentionParameterId] = [
  174. 'type' => $mention['type'],
  175. 'id' => $mention['id'],
  176. 'name' => $displayName
  177. ];
  178. }
  179. return [$message, $messageParameters];
  180. }
  181. }