refactor: simplify Watchlist triggers

This commit is contained in:
Maël Gangloff
2025-10-15 19:52:44 +02:00
parent a193338664
commit 0c2148d889
16 changed files with 136 additions and 349 deletions

View File

@@ -1,9 +0,0 @@
<?php
namespace App\Config;
enum TriggerAction: string
{
case SendEmail = 'email';
case SendChat = 'chat';
}

View File

@@ -17,6 +17,7 @@ use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Attribute\SerializedName;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Entity(repositoryClass: WatchListRepository::class)]
#[ApiResource(
@@ -166,14 +167,6 @@ class WatchList
#[Groups(['watchlist:create', 'watchlist:list', 'watchlist:item', 'watchlist:update'])]
private Collection $domains;
/**
* @var Collection<int, WatchListTrigger>
*/
#[ORM\OneToMany(targetEntity: WatchListTrigger::class, mappedBy: 'watchList', cascade: ['persist'], orphanRemoval: true)]
#[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create'])]
#[SerializedName('triggers')]
private Collection $watchListTriggers;
#[ORM\ManyToOne(inversedBy: 'watchLists')]
#[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create', 'watchlist:update'])]
private ?Connector $connector = null;
@@ -189,13 +182,27 @@ class WatchList
#[SerializedName('dsn')]
#[ORM\Column(type: Types::SIMPLE_ARRAY, nullable: true)]
#[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create', 'watchlist:update'])]
#[Assert\Unique]
#[Assert\All([
new Assert\Type('string'),
new Assert\NotBlank(),
])]
private ?array $webhookDsn = null;
#[ORM\Column(type: Types::JSON)]
#[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create', 'watchlist:update'])]
#[Assert\Unique]
#[Assert\NotBlank]
#[Assert\All([
new Assert\Type('string'),
new Assert\NotBlank(),
])]
private array $trackedEvents = [];
public function __construct()
{
$this->token = Uuid::v4();
$this->domains = new ArrayCollection();
$this->watchListTriggers = new ArrayCollection();
$this->createdAt = new \DateTimeImmutable('now');
}
@@ -245,36 +252,6 @@ class WatchList
return $this;
}
/**
* @return Collection<int, WatchListTrigger>
*/
public function getWatchListTriggers(): Collection
{
return $this->watchListTriggers;
}
public function addWatchListTrigger(WatchListTrigger $watchListTrigger): static
{
if (!$this->watchListTriggers->contains($watchListTrigger)) {
$this->watchListTriggers->add($watchListTrigger);
$watchListTrigger->setWatchList($this);
}
return $this;
}
public function removeWatchListTrigger(WatchListTrigger $watchListTrigger): static
{
if ($this->watchListTriggers->removeElement($watchListTrigger)) {
// set the owning side to null (unless already changed)
if ($watchListTrigger->getWatchList() === $this) {
$watchListTrigger->setWatchList(null);
}
}
return $this;
}
public function getConnector(): ?Connector
{
return $this->connector;
@@ -322,4 +299,16 @@ class WatchList
return $this;
}
public function getTrackedEvents(): array
{
return $this->trackedEvents;
}
public function setTrackedEvents(array $trackedEvents): static
{
$this->trackedEvents = $trackedEvents;
return $this;
}
}

View File

@@ -1,94 +0,0 @@
<?php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Link;
use ApiPlatform\Metadata\Post;
use App\Config\TriggerAction;
use App\Repository\EventTriggerRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
#[ORM\Entity(repositoryClass: EventTriggerRepository::class)]
#[ApiResource(
uriTemplate: '/watchlists/{watchListId}/triggers/{action}/{event}',
shortName: 'Watchlist Trigger',
operations: [
new Get(),
new GetCollection(
uriTemplate: '/watchlists/{watchListId}/triggers',
uriVariables: [
'watchListId' => new Link(fromProperty: 'token', toProperty: 'watchList', fromClass: WatchList::class),
],
),
new Post(
uriTemplate: '/watchlist-triggers',
uriVariables: [],
security: 'true'
),
new Delete(),
],
uriVariables: [
'watchListId' => new Link(fromProperty: 'token', toProperty: 'watchList', fromClass: WatchList::class),
'action' => 'action',
'event' => 'event',
],
security: 'object.getWatchList().user == user',
)]
class WatchListTrigger
{
#[ORM\Id]
#[ORM\Column(length: 255, nullable: false)]
#[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create'])]
private ?string $event;
#[ORM\Id]
#[ORM\ManyToOne(targetEntity: WatchList::class, inversedBy: 'watchListTriggers')]
#[ORM\JoinColumn(referencedColumnName: 'token', nullable: false, onDelete: 'CASCADE')]
private ?WatchList $watchList;
#[ORM\Id]
#[ORM\Column(nullable: false, enumType: TriggerAction::class)]
#[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create'])]
private ?TriggerAction $action;
public function getEvent(): ?string
{
return $this->event;
}
public function setEvent(string $event): static
{
$this->event = $event;
return $this;
}
public function getWatchList(): ?WatchList
{
return $this->watchList;
}
public function setWatchList(?WatchList $watchList): static
{
$this->watchList = $watchList;
return $this;
}
public function getAction(): ?TriggerAction
{
return $this->action;
}
public function setAction(TriggerAction $action): static
{
$this->action = $action;
return $this;
}
}

View File

@@ -2,11 +2,9 @@
namespace App\MessageHandler;
use App\Config\TriggerAction;
use App\Entity\Domain;
use App\Entity\DomainEvent;
use App\Entity\WatchList;
use App\Entity\WatchListTrigger;
use App\Message\SendDomainEventNotif;
use App\Notifier\DomainUpdateNotification;
use App\Repository\DomainRepository;
@@ -19,7 +17,6 @@ use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\ExceptionInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Notifier\Recipient\Recipient;
@@ -47,7 +44,6 @@ final readonly class SendDomainEventNotifHandler
/**
* @throws TransportExceptionInterface
* @throws \Exception
* @throws ExceptionInterface
*/
public function __invoke(SendDomainEventNotif $message): void
{
@@ -64,46 +60,36 @@ final readonly class SendDomainEventNotifHandler
foreach ($domain->getEvents()->filter(
fn ($event) => $message->updatedAt < $event->getDate() && $event->getDate() < new \DateTimeImmutable()) as $event
) {
$watchListTriggers = $watchList->getWatchListTriggers()
->filter(fn ($trigger) => $trigger->getEvent() === $event->getAction());
/*
* For each trigger, we perform the appropriate action: send email or send push notification (for now)
*/
/** @var WatchListTrigger $watchListTrigger */
foreach ($watchListTriggers->getIterator() as $watchListTrigger) {
$recipient = new Recipient($watchList->getUser()->getEmail());
$notification = new DomainUpdateNotification($this->sender, $event);
if (TriggerAction::SendEmail == $watchListTrigger->getAction()) {
$this->logger->info('New action has been detected on this domain name : an email is sent to user', [
'event' => $event->getAction(),
'ldhName' => $message->ldhName,
'username' => $watchList->getUser()->getUserIdentifier(),
]);
$this->mailer->send($notification->asEmailMessage($recipient)->getMessage());
} elseif (TriggerAction::SendChat == $watchListTrigger->getAction()) {
$webhookDsn = $watchList->getWebhookDsn();
if (null === $webhookDsn || 0 === count($webhookDsn)) {
continue;
}
$this->logger->info('New action has been detected on this domain name : a notification is sent to user', [
'event' => $event->getAction(),
'ldhName' => $message->ldhName,
'username' => $watchList->getUser()->getUserIdentifier(),
]);
$this->chatNotificationService->sendChatNotification($watchList, $notification);
}
if ($this->influxdbEnabled) {
$this->influxdbService->addDomainNotificationPoint($domain, TriggerAction::SendChat, true);
}
$this->statService->incrementStat('stats.alert.sent');
if (!in_array($event->getAction(), $watchList->getTrackedEvents())) {
continue;
}
$recipient = new Recipient($watchList->getUser()->getEmail());
$notification = new DomainUpdateNotification($this->sender, $event);
$this->logger->info('New action has been detected on this domain name : an email is sent to user', [
'event' => $event->getAction(),
'ldhName' => $message->ldhName,
'username' => $watchList->getUser()->getUserIdentifier(),
]);
$this->mailer->send($notification->asEmailMessage($recipient)->getMessage());
$webhookDsn = $watchList->getWebhookDsn();
if (null !== $webhookDsn && 0 !== count($webhookDsn)) {
$this->logger->info('New action has been detected on this domain name : a notification is sent to user', [
'event' => $event->getAction(),
'ldhName' => $message->ldhName,
'username' => $watchList->getUser()->getUserIdentifier(),
]);
$this->chatNotificationService->sendChatNotification($watchList, $notification);
}
if ($this->influxdbEnabled) {
$this->influxdbService->addDomainNotificationPoint($domain, 'chat', true);
}
$this->statService->incrementStat('stats.alert.sent');
}
}
}

View File

@@ -1,43 +0,0 @@
<?php
namespace App\Repository;
use App\Entity\WatchListTrigger;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<WatchListTrigger>
*/
class EventTriggerRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, WatchListTrigger::class);
}
// /**
// * @return WatchListTrigger[] Returns an array of WatchListTrigger objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('e')
// ->andWhere('e.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('e.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?WatchListTrigger
// {
// return $this->createQueryBuilder('e')
// ->andWhere('e.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}

View File

@@ -2,7 +2,6 @@
namespace App\Service;
use App\Config\TriggerAction;
use App\Entity\Connector;
use App\Entity\Domain;
use App\Entity\RdapServer;
@@ -68,12 +67,12 @@ readonly class InfluxdbService
$this->client->close();
}
public function addDomainNotificationPoint(Domain $domain, TriggerAction $triggerAction, bool $success): void
public function addDomainNotificationPoint(Domain $domain, string $triggerAction, bool $success): void
{
$this->writePoints(new Point('domain_notification', [
'domain' => $domain->getLdhName(),
'tld' => $domain->getTld()->getTld(),
'medium' => $triggerAction->value,
'medium' => $triggerAction,
], [
'success' => $success,
]));