You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Notifier.php 7.6KB

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