[PLUGIN][WebHooks] Add hook for subscriptions

This commit is contained in:
Hugo Sales 2022-03-24 21:59:24 +00:00 committed by Diogo Peralta Cordeiro
parent e3e14c53ef
commit ca5520edbf
No known key found for this signature in database
GPG Key ID: 18D2D35001FBFAB0
3 changed files with 43 additions and 17 deletions

View File

@ -112,8 +112,9 @@ class Subscription extends Component
\is_int($subject) ? $subject : Actor::getById($subscriber_id),
$activity,
[$subscribed_id],
_m('{subject} subscribed to {object}.', ['{subject}' => $activity->getActorId(), '{object}' => $activity->getObjectId()]),
$reason = _m('{subject} subscribed to {object}.', ['{subject}' => $activity->getActorId(), '{object}' => $activity->getObjectId()]),
]);
Event::handle('NewSubscriptionEnd', [$subject, $activity, $object, $reason]);
}
return $activity;
}

View File

@ -45,7 +45,7 @@ class WebHooks extends Controller
$hooks = F\reindex(DB::findBy(E\WebHook::class, ['actor_id' => $user->getId()]), fn (E\WebHook $wh) => $wh->getEvent());
$form = Form::create([
['notifications', TextType::class, ['label' => _m('Trigger this hook when I recieve a notification'), 'data' => ($hooks['notifications'] ?? null)?->getTarget()]],
['follow', TextType::class, ['label' => _m('Trigger this hook when someone starts following me'), 'data' => ($hooks['follow'] ?? null)?->getTarget()]],
['subscriptions', TextType::class, ['label' => _m('Trigger this hook when someone subscribes to me'), 'data' => ($hooks['subscriptions'] ?? null)?->getTarget()]],
['save_webhooks', SubmitType::class, ['label' => _m('Submit')]],
], form_options: ['action' => Router::url(P\WebHooks::controller_route)]);

View File

@ -30,6 +30,8 @@ use App\Core\Queue\Queue;
use App\Core\Router\RouteLoader;
use App\Entity\Activity;
use App\Entity\Actor;
use App\Entity\LocalUser;
use App\Util\Common;
use App\Util\Exception\ServerException;
use Exception;
use Functional as F;
@ -59,21 +61,32 @@ class WebHooks extends Plugin
return Event::next;
}
private function maybeEnqueue(Actor $actor, string $event, array $args): void
{
$hook_target = DB::findOneBy(E\WebHook::class, ['actor_id' => $actor->getId(), 'event' => $event], return_null: true)?->getTarget();
if (!\is_null($hook_target)) {
Queue::enqueue([$event, $hook_target, $actor, $args], queue: 'webhook');
}
}
public function onNewNotificationEnd(Actor $sender, Activity $activity, array $effective_targets, ?string $reason)
{
foreach ($effective_targets as $actor) {
$target = DB::findOneBy(E\WebHook::class, ['actor_id' => $actor->getId(), 'event' => 'notifications'], return_null: true)?->getTarget();
if (!\is_null($target)) {
Queue::enqueue(['notifications', $target, $actor, [$sender, $activity, $effective_targets, $reason]], queue: 'webhook');
$this->maybeEnqueue($actor, 'notifications', [$sender, $activity, $effective_targets, $reason]);
}
return Event::next;
}
public function onNewSubscriptionEnd(LocalUser|Actor $subscriber, Activity $activity, Actor $hook_target, ?string $reason)
{
$this->maybeEnqueue($hook_target, 'subscriptions', [$subscriber, $activity, $hook_target, $reason]);
return Event::next;
}
/**
* @param array<Actor $sender, Activity $activity, array $effective_targets, ?string $reason> $args
*/
public function onQueueWebhook(string $type, string $target, Actor $actor, array $args)
public function onQueueWebhook(string $type, string $hook_target, Actor $actor, array $args)
{
switch ($type) {
case 'notifications':
@ -85,18 +98,30 @@ class WebHooks extends Plugin
'targets' => F\map(array_values($targets), fn (Actor $actor) => ['id' => $actor->getId(), 'nickname' => $actor->getNickname()]),
'reason' => $reason,
];
// toJson(Activity) is already JSON (hopefully that's obvious :') ), so replace it after converting the rest to JSON
$json = str_replace('"activity":"%activity%"', '"activity":' . \Plugin\ActivityPub\Util\Model\Activity::toJson($activity), json_encode($data));
Log::debug("WebHooks: POST {$target} on behalf of actor {$actor->getId()} ({$actor->getNickname()})", [$data, ['json' => $json]]);
try {
$method = Common::config('plugin_webhooks', 'method');
HTTPClient::{$method}($target, ['body' => $json, 'headers' => ['content-type' => 'application/json', 'user-agent' => 'GNU social']]);
} catch (Exception $e) {
Log::debug("WebHooks: Failed POST {$target} on behalf of actor {$actor->getId()} ({$actor->getNickname()})", [$e]);
}
return Event::stop;
break;
case 'subscriptions':
[$subscriber, $activity, $target, $reason] = $args;
$data = [
'type' => 'subscription',
'activity' => '%activity%',
'actor' => ['id' => $subscriber->getId(), 'nickname' => $subscriber->getNickname()],
'targets' => [['id' => $target->getId(), 'nickname' => $target->getNickname()]],
'reason' => $reason,
];
break;
default:
throw new ServerException("Webhook notification handler for event {$type} not implemented");
}
// toJson(Activity) is already JSON (hopefully that's obvious :') ), so replace it after converting the rest to JSON
$json = str_replace('"activity":"%activity%"', '"activity":' . \Plugin\ActivityPub\Util\Model\Activity::toJson($activity), json_encode($data));
Log::debug("WebHooks: POST {$hook_target} on behalf of actor {$actor->getId()} ({$actor->getNickname()})", [$data, ['json' => $json]]);
try {
$method = Common::config('plugin_webhooks', 'method');
HTTPClient::{$method}($hook_target, ['body' => $json, 'headers' => ['content-type' => 'application/json', 'user-agent' => 'GNU social']]);
} catch (Exception $e) {
Log::debug("WebHooks: Failed POST {$hook_target} on behalf of actor {$actor->getId()} ({$actor->getNickname()})", [$e]);
}
return Event::stop;
}
}