Notification.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. <?php
  2. declare(strict_types = 1);
  3. // {{{ License
  4. // This file is part of GNU social - https://www.gnu.org/software/social
  5. //
  6. // GNU social is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // GNU social is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  18. // }}}
  19. namespace Component\Notification;
  20. use App\Core\DB;
  21. use App\Core\Event;
  22. use function App\Core\I18n\_m;
  23. use App\Core\Log;
  24. use App\Core\Modules\Component;
  25. use App\Core\Queue;
  26. use App\Core\Router;
  27. use App\Entity\Activity;
  28. use App\Entity\Actor;
  29. use App\Entity\LocalUser;
  30. use App\Util\Exception\ServerException;
  31. use Component\FreeNetwork\FreeNetwork;
  32. use Component\Notification\Controller\Feed;
  33. use EventResult;
  34. use Exception;
  35. use Throwable;
  36. class Notification extends Component
  37. {
  38. public function onAddRoute(Router $m): EventResult
  39. {
  40. $m->connect('feed_notifications', '/feed/notifications', [Feed::class, 'notifications']);
  41. return Event::next;
  42. }
  43. /**
  44. * @throws ServerException
  45. */
  46. public function onCreateDefaultFeeds(int $actor_id, LocalUser $user, int &$ordering): EventResult
  47. {
  48. DB::persist(\App\Entity\Feed::create([
  49. 'actor_id' => $actor_id,
  50. 'url' => Router::url($route = 'feed_notifications'),
  51. 'route' => $route,
  52. 'title' => _m('Notifications'),
  53. 'ordering' => $ordering++,
  54. ]));
  55. return Event::next;
  56. }
  57. /**
  58. * Enqueues a notification for an Actor (such as person or group) which means
  59. * it shows up in their home feed and such.
  60. * WARNING: It's highly advisable to have flushed any relevant objects before triggering this event.
  61. *
  62. * $targets should be of the shape:
  63. * (int|Actor)[] // Prefer Actor whenever possible
  64. * Example of $targets:
  65. * [42, $actor_alice, $actor_bob] // Avoid repeating actors or ids
  66. *
  67. * @param Actor $sender The one responsible for this activity, take care not to include it in targets
  68. * @param Activity $activity The activity responsible for the object being given to known to targets
  69. * @param non-empty-array<Actor|int> $targets Attentions, Mentions, any other source. Should never be empty, you usually want to register an attention to every $sender->getSubscribers()
  70. * @param null|string $reason An optional reason explaining why this notification exists
  71. */
  72. public function onNewNotification(Actor $sender, Activity $activity, array $targets, ?string $reason = null): EventResult
  73. {
  74. // Ensure targets are all actor objects and unique
  75. $effective_targets = [];
  76. foreach ($targets as $target) {
  77. if (\is_int($target)) {
  78. $target_id = $target;
  79. $target_object = null;
  80. } else {
  81. $target_id = $target->getId();
  82. $target_object = $target;
  83. }
  84. if (!\array_key_exists(key: $target_id, array: $effective_targets)) {
  85. $target_object ??= Actor::getById($target_id);
  86. $effective_targets[$target_id] = $target_object;
  87. }
  88. }
  89. unset($targets);
  90. if (Event::handle('NewNotificationStart', [$sender, $activity, $effective_targets, $reason]) === Event::next) {
  91. self::notify($sender, $activity, $effective_targets, $reason);
  92. }
  93. Event::handle('NewNotificationEnd', [$sender, $activity, $effective_targets, $reason]);
  94. return Event::next;
  95. }
  96. /**
  97. * @param mixed[] $retry_args
  98. */
  99. public function onQueueNotificationLocal(Actor $sender, Activity $activity, Actor $target, ?string $reason, array &$retry_args): EventResult
  100. {
  101. // TODO: use https://symfony.com/doc/current/notifier.html
  102. return Event::stop;
  103. }
  104. /**
  105. * @param Actor[] $targets
  106. * @param mixed[] $retry_args
  107. */
  108. public function onQueueNotificationRemote(Actor $sender, Activity $activity, array $targets, ?string $reason, array &$retry_args): EventResult
  109. {
  110. if (FreeNetwork::notify($sender, $activity, $targets, $reason)) {
  111. return Event::stop;
  112. } else {
  113. return Event::next;
  114. }
  115. }
  116. /**
  117. * Bring given Activity to Targets' knowledge.
  118. * This will flush a Notification to DB.
  119. *
  120. * @param Actor[] $targets
  121. *
  122. * @return bool true if successful, false otherwise
  123. */
  124. public static function notify(Actor $sender, Activity $activity, array $targets, ?string $reason = null): bool
  125. {
  126. $remote_targets = [];
  127. foreach ($targets as $target) {
  128. if ($target->getIsLocal()) {
  129. if ($target->hasBlocked($author = $activity->getActor())) {
  130. Log::info("Not saving notification to actor {$target->getId()} from sender {$sender->getId()} because receiver blocked author {$author->getId()}.");
  131. continue;
  132. }
  133. if (Event::handle('NewNotificationShould', [$activity, $target]) === Event::next) {
  134. if ($sender->getId() === $target->getId()
  135. || $activity->getActorId() === $target->getId()) {
  136. // The target already knows about this, no need to bother with a notification
  137. continue;
  138. }
  139. }
  140. Queue::enqueue(
  141. payload: [$sender, $activity, $target, $reason],
  142. queue: 'NotificationLocal',
  143. priority: true,
  144. );
  145. } else {
  146. // We have no authority nor responsibility of notifying remote actors of a remote actor's doing
  147. if ($sender->getIsLocal()) {
  148. $remote_targets[] = $target;
  149. }
  150. }
  151. // XXX: Unideal as in failures the rollback will leave behind a false notification,
  152. // but most notifications (all) require flushing the objects first
  153. // Should be okay as long as implementations bear this in mind
  154. try {
  155. DB::wrapInTransaction(fn () => DB::persist(Entity\Notification::create([
  156. 'activity_id' => $activity->getId(),
  157. 'target_id' => $target->getId(),
  158. 'reason' => $reason,
  159. ])));
  160. } catch (Exception|Throwable $e) {
  161. // We do our best not to record duplicate notifications, but it's not insane that can happen
  162. Log::error('It was attempted to record an invalid notification!', [$e]);
  163. }
  164. }
  165. if ($remote_targets !== []) {
  166. Queue::enqueue(
  167. payload: [$sender, $activity, $remote_targets, $reason],
  168. queue: 'NotificationRemote',
  169. priority: false,
  170. );
  171. }
  172. return true;
  173. }
  174. }