domain-watchdog/src/Service/ChatNotificationService.php

77 lines
2.8 KiB
PHP
Raw Normal View History

2024-08-27 00:09:25 +02:00
<?php
namespace App\Service;
use App\Config\WebhookScheme;
use App\Entity\WatchList;
use App\Notifier\DomainWatchdogNotification;
2024-08-27 00:09:25 +02:00
use Psr\Log\LoggerInterface;
2024-08-27 21:44:42 +02:00
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Notifier\Exception\InvalidArgumentException;
use Symfony\Component\Notifier\Recipient\NoRecipient;
2024-08-27 00:09:25 +02:00
use Symfony\Component\Notifier\Transport\AbstractTransportFactory;
use Symfony\Component\Notifier\Transport\Dsn;
readonly class ChatNotificationService
{
public function __construct(
private LoggerInterface $logger,
2024-08-27 00:09:25 +02:00
) {
}
public function sendChatNotification(WatchList $watchList, DomainWatchdogNotification $notification): void
2024-08-27 00:09:25 +02:00
{
$webhookDsn = $watchList->getWebhookDsn();
if (null === $webhookDsn || 0 === count($webhookDsn)) {
return;
}
2024-08-27 00:09:25 +02:00
foreach ($webhookDsn as $dsnString) {
try {
$dsn = new Dsn($dsnString);
} catch (InvalidArgumentException $exception) {
throw new BadRequestHttpException($exception->getMessage());
}
2024-08-27 00:09:25 +02:00
$scheme = $dsn->getScheme();
$webhookScheme = WebhookScheme::tryFrom($scheme);
2024-08-27 21:44:42 +02:00
if (null === $webhookScheme) {
throw new BadRequestHttpException("The DSN scheme ($scheme) is not supported");
}
2024-08-27 21:44:42 +02:00
$transportFactoryClass = $webhookScheme->getChatTransportFactory();
/** @var AbstractTransportFactory $transportFactory */
$transportFactory = new $transportFactoryClass();
2024-08-27 21:44:42 +02:00
$push = $notification->asPushMessage(new NoRecipient());
$chat = $notification->asChatMessage(new NoRecipient(), $webhookScheme->value);
2024-08-27 21:44:42 +02:00
try {
$factory = $transportFactory->create($dsn);
if ($factory->supports($push)) {
$factory->send($push);
} elseif ($factory->supports($chat)) {
$factory->send($chat);
} else {
throw new BadRequestHttpException('Unsupported message type');
2024-08-27 00:09:25 +02:00
}
$this->logger->info('Chat message sent with {schema} for Watchlist {token}',
[
'scheme' => $webhookScheme->name,
'token' => $watchList->getToken(),
]);
} catch (\Throwable $exception) {
$this->logger->error('Unable to send a chat message to {scheme} for Watchlist {token}',
[
'scheme' => $webhookScheme->name,
'token' => $watchList->getToken(),
]);
throw new BadRequestHttpException($exception->getMessage());
2024-08-27 00:09:25 +02:00
}
}
}
}