Notifier.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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\IUser;
  32. use OCP\IUserManager;
  33. use OCP\L10N\IFactory;
  34. use OCP\Notification\AlreadyProcessedException;
  35. use OCP\Notification\INotification;
  36. use OCP\Notification\INotifier;
  37. class Notifier implements INotifier {
  38. protected IFactory $l10nFactory;
  39. protected IRootFolder $rootFolder;
  40. protected ICommentsManager $commentsManager;
  41. protected IURLGenerator $url;
  42. protected IUserManager $userManager;
  43. public function __construct(
  44. IFactory $l10nFactory,
  45. IRootFolder $rootFolder,
  46. ICommentsManager $commentsManager,
  47. IURLGenerator $url,
  48. IUserManager $userManager
  49. ) {
  50. $this->l10nFactory = $l10nFactory;
  51. $this->rootFolder = $rootFolder;
  52. $this->commentsManager = $commentsManager;
  53. $this->url = $url;
  54. $this->userManager = $userManager;
  55. }
  56. /**
  57. * Identifier of the notifier, only use [a-z0-9_]
  58. *
  59. * @return string
  60. * @since 17.0.0
  61. */
  62. public function getID(): string {
  63. return 'comments';
  64. }
  65. /**
  66. * Human readable name describing the notifier
  67. *
  68. * @return string
  69. * @since 17.0.0
  70. */
  71. public function getName(): string {
  72. return $this->l10nFactory->get('comments')->t('Comments');
  73. }
  74. /**
  75. * @param INotification $notification
  76. * @param string $languageCode The code of the language that should be used to prepare the notification
  77. * @return INotification
  78. * @throws \InvalidArgumentException When the notification was not prepared by a notifier
  79. * @throws AlreadyProcessedException When the notification is not needed anymore and should be deleted
  80. * @since 9.0.0
  81. */
  82. public function prepare(INotification $notification, string $languageCode): INotification {
  83. if ($notification->getApp() !== 'comments') {
  84. throw new \InvalidArgumentException();
  85. }
  86. try {
  87. $comment = $this->commentsManager->get($notification->getObjectId());
  88. } catch (NotFoundException $e) {
  89. // needs to be converted to InvalidArgumentException, otherwise none Notifications will be shown at all
  90. throw new \InvalidArgumentException('Comment not found', 0, $e);
  91. }
  92. $l = $this->l10nFactory->get('comments', $languageCode);
  93. $displayName = $comment->getActorId();
  94. $isDeletedActor = $comment->getActorType() === ICommentsManager::DELETED_USER;
  95. if ($comment->getActorType() === 'users') {
  96. $commenter = $this->userManager->getDisplayName($comment->getActorId());
  97. if ($commenter !== null) {
  98. $displayName = $commenter;
  99. }
  100. }
  101. switch ($notification->getSubject()) {
  102. case 'mention':
  103. $parameters = $notification->getSubjectParameters();
  104. if ($parameters[0] !== 'files') {
  105. throw new \InvalidArgumentException('Unsupported comment object');
  106. }
  107. $userFolder = $this->rootFolder->getUserFolder($notification->getUser());
  108. $nodes = $userFolder->getById((int)$parameters[1]);
  109. if (empty($nodes)) {
  110. throw new AlreadyProcessedException();
  111. }
  112. $node = $nodes[0];
  113. $path = rtrim($node->getPath(), '/');
  114. if (strpos($path, '/' . $notification->getUser() . '/files/') === 0) {
  115. // Remove /user/files/...
  116. $fullPath = $path;
  117. [,,, $path] = explode('/', $fullPath, 4);
  118. }
  119. $subjectParameters = [
  120. 'file' => [
  121. 'type' => 'file',
  122. 'id' => $comment->getObjectId(),
  123. 'name' => $node->getName(),
  124. 'path' => $path,
  125. 'link' => $this->url->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $comment->getObjectId()]),
  126. ],
  127. ];
  128. if ($isDeletedActor) {
  129. $subject = $l->t('You were mentioned on "{file}", in a comment by a user that has since been deleted');
  130. } else {
  131. $subject = $l->t('{user} mentioned you in a comment on "{file}"');
  132. $subjectParameters['user'] = [
  133. 'type' => 'user',
  134. 'id' => $comment->getActorId(),
  135. 'name' => $displayName,
  136. ];
  137. }
  138. [$message, $messageParameters] = $this->commentToRichMessage($comment);
  139. $notification->setRichSubject($subject, $subjectParameters)
  140. ->setParsedSubject($this->richToParsed($subject, $subjectParameters))
  141. ->setRichMessage($message, $messageParameters)
  142. ->setParsedMessage($this->richToParsed($message, $messageParameters))
  143. ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/comment.svg')))
  144. ->setLink($this->url->linkToRouteAbsolute(
  145. 'comments.Notifications.view',
  146. ['id' => $comment->getId()])
  147. );
  148. return $notification;
  149. break;
  150. default:
  151. throw new \InvalidArgumentException('Invalid subject');
  152. }
  153. }
  154. public function commentToRichMessage(IComment $comment): array {
  155. $message = $comment->getMessage();
  156. $messageParameters = [];
  157. $mentionTypeCount = [];
  158. $mentions = $comment->getMentions();
  159. foreach ($mentions as $mention) {
  160. if ($mention['type'] === 'user') {
  161. $userDisplayName = $this->userManager->getDisplayName($mention['id']);
  162. if ($userDisplayName === null) {
  163. continue;
  164. }
  165. }
  166. if (!array_key_exists($mention['type'], $mentionTypeCount)) {
  167. $mentionTypeCount[$mention['type']] = 0;
  168. }
  169. $mentionTypeCount[$mention['type']]++;
  170. // To keep a limited character set in parameter IDs ([a-zA-Z0-9-])
  171. // the mention parameter ID does not include the mention ID (which
  172. // could contain characters like '@' for user IDs) but a one-based
  173. // index of the mentions of that type.
  174. $mentionParameterId = 'mention-' . $mention['type'] . $mentionTypeCount[$mention['type']];
  175. $message = str_replace('@"' . $mention['id'] . '"', '{' . $mentionParameterId . '}', $message);
  176. if (strpos($mention['id'], ' ') === false && strpos($mention['id'], 'guest/') !== 0) {
  177. $message = str_replace('@' . $mention['id'], '{' . $mentionParameterId . '}', $message);
  178. }
  179. try {
  180. $displayName = $this->commentsManager->resolveDisplayName($mention['type'], $mention['id']);
  181. } catch (\OutOfBoundsException $e) {
  182. // There is no registered display name resolver for the mention
  183. // type, so the client decides what to display.
  184. $displayName = '';
  185. }
  186. $messageParameters[$mentionParameterId] = [
  187. 'type' => $mention['type'],
  188. 'id' => $mention['id'],
  189. 'name' => $displayName
  190. ];
  191. }
  192. return [$message, $messageParameters];
  193. }
  194. public function richToParsed(string $message, array $parameters): string {
  195. $placeholders = $replacements = [];
  196. foreach ($parameters as $placeholder => $parameter) {
  197. $placeholders[] = '{' . $placeholder . '}';
  198. if ($parameter['type'] === 'user') {
  199. $replacements[] = '@' . $parameter['name'];
  200. } elseif ($parameter['type'] === 'file') {
  201. $replacements[] = $parameter['path'];
  202. } else {
  203. $replacements[] = $parameter['name'];
  204. }
  205. }
  206. return str_replace($placeholders, $replacements, $message);
  207. }
  208. }