Notifier.php 6.9 KB

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