Notifier.php 7.4 KB

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