refactor: simplify Watchlist triggers

This commit is contained in:
Maël Gangloff 2025-10-15 19:52:44 +02:00
parent a193338664
commit 0c2148d889
No known key found for this signature in database
GPG Key ID: 11FDC81C24A7F629
16 changed files with 136 additions and 349 deletions

View File

@ -8,7 +8,7 @@ import type {Watchlist} from '../../../utils/api'
export function UpdateWatchlistButton({watchlist, onUpdateWatchlist, connectors}: { export function UpdateWatchlistButton({watchlist, onUpdateWatchlist, connectors}: {
watchlist: Watchlist watchlist: Watchlist
onUpdateWatchlist: (values: { domains: string[], triggers: string[], token: string }) => Promise<void> onUpdateWatchlist: (values: { domains: string[], trackedEvents: string[], token: string }) => Promise<void>
connectors: Array<Connector & { id: string }> connectors: Array<Connector & { id: string }>
}) { }) {
const [form] = Form.useForm() const [form] = Form.useForm()
@ -35,7 +35,7 @@ export function UpdateWatchlistButton({watchlist, onUpdateWatchlist, connectors}
{name: 'name', value: watchlist.name}, {name: 'name', value: watchlist.name},
{name: 'connector', value: watchlist.connector?.id}, {name: 'connector', value: watchlist.connector?.id},
{name: 'domains', value: watchlist.domains.map(d => d.ldhName)}, {name: 'domains', value: watchlist.domains.map(d => d.ldhName)},
{name: 'triggers', value: [...new Set(watchlist.triggers?.map(t => t.event))]}, {name: 'trackedEvents', value: watchlist.trackedEvents},
{name: 'dsn', value: watchlist.dsn} {name: 'dsn', value: watchlist.dsn}
]) ])
}} }}

View File

@ -15,7 +15,7 @@ import type {Watchlist} from '../../../utils/api'
export function WatchlistCard({watchlist, onUpdateWatchlist, connectors, onDelete}: { export function WatchlistCard({watchlist, onUpdateWatchlist, connectors, onDelete}: {
watchlist: Watchlist watchlist: Watchlist
onUpdateWatchlist: (values: { domains: string[], triggers: string[], token: string }) => Promise<void> onUpdateWatchlist: (values: { domains: string[], trackedEvents: string[], token: string }) => Promise<void>
connectors: Array<Connector & { id: string }> connectors: Array<Connector & { id: string }>
onDelete: () => void onDelete: () => void
}) { }) {
@ -64,13 +64,12 @@ export function WatchlistCard({watchlist, onUpdateWatchlist, connectors, onDelet
{watchlist.domains.map(d => <DomainToTag key={d.ldhName} domain={d}/>)} {watchlist.domains.map(d => <DomainToTag key={d.ldhName} domain={d}/>)}
</Col> </Col>
<Col span={8}> <Col span={8}>
{watchlist.triggers?.filter(t => t.action === 'email') {watchlist.trackedEvents?.map(t => <Tooltip
.map(t => <Tooltip key={t}
key={t.event} title={rdapEventDetailTranslated[t as keyof typeof rdapEventDetailTranslated] || undefined}
title={rdapEventDetailTranslated[t.event as keyof typeof rdapEventDetailTranslated] || undefined}
> >
<Tag color={actionToColor(t.event)}> <Tag color={actionToColor(t)}>
{rdapEventNameTranslated[t.event as keyof typeof rdapEventNameTranslated]} {rdapEventNameTranslated[t as keyof typeof rdapEventNameTranslated]}
</Tag> </Tag>
</Tooltip> </Tooltip>
)} )}

View File

@ -2,13 +2,12 @@ import type { FormInstance, SelectProps} from 'antd'
import {Button, Form, Input, Select, Space, Tag, Tooltip, Typography} from 'antd' import {Button, Form, Input, Select, Space, Tag, Tooltip, Typography} from 'antd'
import {t} from 'ttag' import {t} from 'ttag'
import {ApiOutlined, MinusCircleOutlined, PlusOutlined} from '@ant-design/icons' import {ApiOutlined, MinusCircleOutlined, PlusOutlined} from '@ant-design/icons'
import React, {useState} from 'react' import React from 'react'
import type {Connector} from '../../../utils/api/connectors' import type {Connector} from '../../../utils/api/connectors'
import {rdapEventDetailTranslation, rdapEventNameTranslation} from '../../../utils/functions/rdapTranslation' import {rdapEventDetailTranslation, rdapEventNameTranslation} from '../../../utils/functions/rdapTranslation'
import {actionToColor} from '../../../utils/functions/actionToColor' import {actionToColor} from '../../../utils/functions/actionToColor'
import {actionToIcon} from '../../../utils/functions/actionToIcon' import {actionToIcon} from '../../../utils/functions/actionToIcon'
import type {EventAction, Watchlist} from '../../../utils/api' import type {EventAction, Watchlist} from '../../../utils/api'
import { createWatchlistTrigger, deleteWatchlistTrigger} from '../../../utils/api'
import {formItemLayoutWithOutLabel} from "../../../utils/providers" import {formItemLayoutWithOutLabel} from "../../../utils/providers"
type TagRender = SelectProps['tagRender'] type TagRender = SelectProps['tagRender']
@ -24,10 +23,10 @@ const formItemLayout = {
} }
} }
export function WatchlistForm({form, connectors, onFinish, isCreation, watchList}: { export function WatchlistForm({form, connectors, onFinish, isCreation}: {
form: FormInstance form: FormInstance
connectors: Array<Connector & { id: string }> connectors: Array<Connector & { id: string }>
onFinish: (values: { domains: string[], triggers: string[], token: string }) => void onFinish: (values: { domains: string[], trackedEvents: string[], token: string }) => void
isCreation: boolean, isCreation: boolean,
watchList?: Watchlist, watchList?: Watchlist,
}) { }) {
@ -61,48 +60,12 @@ export function WatchlistForm({form, connectors, onFinish, isCreation, watchList
) )
} }
const [triggersLoading, setTriggersLoading] = useState(false)
const createTrigger = async (event: string) => {
if (isCreation) return
setTriggersLoading(true)
await createWatchlistTrigger(watchList!.token, {
watchList: watchList!['@id'],
event,
action: 'email',
})
await createWatchlistTrigger(watchList!.token, {
watchList: watchList!['@id'],
event,
action: 'chat',
})
setTriggersLoading(false)
}
const removeTrigger = async (event: string) => {
if (isCreation) return
setTriggersLoading(true)
await deleteWatchlistTrigger(watchList!.token, {
watchList: watchList!['@id'],
event,
action: 'email',
})
await deleteWatchlistTrigger(watchList!.token, {
watchList: watchList!['@id'],
event,
action: 'chat',
})
setTriggersLoading(false)
}
return ( return (
<Form <Form
{...formItemLayoutWithOutLabel} {...formItemLayoutWithOutLabel}
form={form} form={form}
onFinish={onFinish} onFinish={onFinish}
initialValues={{triggers: ['last changed', 'transfer', 'expiration', 'deletion']}} initialValues={{trackedEvents: ['last changed', 'transfer', 'expiration', 'deletion']}}
> >
<Form.Item name='token' hidden> <Form.Item name='token' hidden>
@ -191,7 +154,7 @@ export function WatchlistForm({form, connectors, onFinish, isCreation, watchList
</Form.List> </Form.List>
<Form.Item <Form.Item
label={t`Tracked events`} label={t`Tracked events`}
name='triggers' name='trackedEvents'
rules={[{required: true, message: t`At least one trigger`, type: 'array'}]} rules={[{required: true, message: t`At least one trigger`, type: 'array'}]}
labelCol={{ labelCol={{
xs: {span: 24}, xs: {span: 24},
@ -207,9 +170,6 @@ export function WatchlistForm({form, connectors, onFinish, isCreation, watchList
mode='multiple' mode='multiple'
tagRender={triggerTagRenderer} tagRender={triggerTagRenderer}
style={{width: '100%'}} style={{width: '100%'}}
onSelect={createTrigger}
onDeselect={removeTrigger}
loading={triggersLoading}
options={Object.keys(rdapEventNameTranslated).map(e => ({ options={Object.keys(rdapEventNameTranslated).map(e => ({
value: e, value: e,
title: rdapEventDetailTranslated[e as keyof typeof rdapEventDetailTranslated] || undefined, title: rdapEventDetailTranslated[e as keyof typeof rdapEventDetailTranslated] || undefined,

View File

@ -6,7 +6,7 @@ import type {Watchlist} from '../../../utils/api'
export function WatchlistsList({watchlists, onDelete, onUpdateWatchlist, connectors}: { export function WatchlistsList({watchlists, onDelete, onUpdateWatchlist, connectors}: {
watchlists: Watchlist[] watchlists: Watchlist[]
onDelete: () => void onDelete: () => void
onUpdateWatchlist: (values: { domains: string[], triggers: string[], token: string }) => Promise<void> onUpdateWatchlist: (values: { domains: string[], trackedEvents: string[], token: string }) => Promise<void>
connectors: Array<Connector & { id: string }> connectors: Array<Connector & { id: string }>
}) { }) {
return ( return (

View File

@ -1,6 +1,6 @@
import React, {useEffect, useState} from 'react' import React, {useEffect, useState} from 'react'
import {Card, Divider, Flex, Form, message} from 'antd' import {Card, Divider, Flex, Form, message} from 'antd'
import type {Watchlist, WatchlistTrigger} from '../../utils/api' import type {Watchlist} from '../../utils/api'
import {getWatchlists, postWatchlist, putWatchlist} from '../../utils/api' import {getWatchlists, postWatchlist, putWatchlist} from '../../utils/api'
import type {AxiosError} from 'axios' import type {AxiosError} from 'axios'
import {t} from 'ttag' import {t} from 'ttag'
@ -14,37 +14,17 @@ import {showErrorAPI} from '../../utils/functions/showErrorAPI'
interface FormValuesType { interface FormValuesType {
name?: string name?: string
domains: string[] domains: string[]
triggers: string[] trackedEvents: string[]
connector?: string connector?: string
dsn?: string[] dsn?: string[]
} }
const getRequestDataFromFormCreation = (values: FormValuesType) => { const getRequestDataFromFormCreation = (values: FormValuesType) => {
const domainsURI = values.domains.map(d => '/api/domains/' + d.toLowerCase()) const domainsURI = values.domains.map(d => '/api/domains/' + d.toLowerCase())
let triggers: WatchlistTrigger[] = values.triggers.map(t => ({event: t, action: 'email'}))
if (values.dsn !== undefined) {
triggers = [...triggers, ...values.triggers.map((t): WatchlistTrigger => ({
event: t,
action: 'chat'
}))]
}
return {
name: values.name,
domains: domainsURI,
triggers,
connector: values.connector !== undefined ? ('/api/connectors/' + values.connector) : undefined,
dsn: values.dsn
}
}
const getRequestDataFromFormUpdate = (values: FormValuesType) => {
const domainsURI = values.domains.map(d => '/api/domains/' + d.toLowerCase())
return { return {
name: values.name, name: values.name,
domains: domainsURI, domains: domainsURI,
trackedEvents: values.trackedEvents,
connector: values.connector !== undefined ? ('/api/connectors/' + values.connector) : undefined, connector: values.connector !== undefined ? ('/api/connectors/' + values.connector) : undefined,
dsn: values.dsn dsn: values.dsn
} }
@ -68,7 +48,7 @@ export default function WatchlistPage() {
const onUpdateWatchlist = async (values: FormValuesType & { token: string }) => await putWatchlist({ const onUpdateWatchlist = async (values: FormValuesType & { token: string }) => await putWatchlist({
token: values.token, token: values.token,
...getRequestDataFromFormUpdate(values) ...getRequestDataFromFormCreation(values)
} }
).then(() => { ).then(() => {
refreshWatchlists() refreshWatchlists()

View File

@ -16,8 +16,6 @@ export type EventAction =
| 'enum validation expiration' | 'enum validation expiration'
| string | string
export type TriggerAction = 'email' | 'chat'
export interface Event { export interface Event {
action: EventAction action: EventAction
date: string date: string
@ -79,16 +77,10 @@ export interface User {
roles: string[] roles: string[]
} }
export interface WatchlistTrigger {
event: EventAction
action: TriggerAction
watchList?: string
}
export interface WatchlistRequest { export interface WatchlistRequest {
name?: string name?: string
domains: string[] domains: string[]
triggers?: Array<WatchlistTrigger> trackedEvents?: string[]
connector?: string connector?: string
dsn?: string[] dsn?: string[]
} }
@ -98,7 +90,7 @@ export interface Watchlist {
name?: string name?: string
token: string token: string
domains: Domain[] domains: Domain[]
triggers?: Array<WatchlistTrigger> trackedEvents?: string[]
dsn?: string[] dsn?: string[]
connector?: { connector?: {
id: string id: string

View File

@ -1,4 +1,4 @@
import type {TrackedDomains, Watchlist, WatchlistRequest, WatchlistTrigger} from './index' import type {TrackedDomains, Watchlist, WatchlistRequest} from './index'
import {request} from './index' import {request} from './index'
interface WatchlistList { interface WatchlistList {
@ -56,20 +56,3 @@ export async function getTrackedDomainList(params: { page: number, itemsPerPage:
}) })
return response.data return response.data
} }
export async function createWatchlistTrigger(watchListToken: string, watchListTrigger: WatchlistTrigger): Promise<WatchlistTrigger> {
const response = await request<WatchlistTrigger>({
method: 'POST',
url: `watchlist-triggers`,
data: watchListTrigger,
})
return response.data
}
export async function deleteWatchlistTrigger(watchListToken: string, watchListTrigger: WatchlistTrigger): Promise<void> {
await request<void>({
method: 'DELETE',
url: `watchlists/${watchListToken}/triggers/${watchListTrigger.action}/${watchListTrigger.event}`,
data: watchListTrigger
})
}

View File

@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20251015165917 extends AbstractMigration
{
public function getDescription(): string
{
return 'Remove watchlist_trigger and add tracked_events';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE watch_list ADD tracked_events JSONB');
$this->addSql("
UPDATE watch_list wl
SET tracked_events = sub.events::jsonb
FROM (
SELECT watch_list_id, json_agg(event) AS events
FROM watch_list_trigger
WHERE action = 'email'
GROUP BY watch_list_id
) AS sub
WHERE wl.token = sub.watch_list_id
");
$this->addSql("UPDATE watch_list SET tracked_events = '[]' WHERE tracked_events IS NULL");
$this->addSql('ALTER TABLE watch_list ALTER tracked_events SET NOT NULL');
$this->addSql('ALTER TABLE watch_list_trigger DROP CONSTRAINT fk_cf857a4cc4508918');
$this->addSql('DROP TABLE watch_list_trigger');
}
public function down(Schema $schema): void
{
$this->addSql('CREATE TABLE watch_list_trigger (event VARCHAR(255) NOT NULL, action VARCHAR(255) NOT NULL, watch_list_id UUID NOT NULL, PRIMARY KEY(event, watch_list_id, action))');
$this->addSql('CREATE INDEX idx_cf857a4cc4508918 ON watch_list_trigger (watch_list_id)');
$this->addSql('COMMENT ON COLUMN watch_list_trigger.watch_list_id IS \'(DC2Type:uuid)\'');
$this->addSql('ALTER TABLE watch_list_trigger ADD CONSTRAINT fk_cf857a4cc4508918 FOREIGN KEY (watch_list_id) REFERENCES watch_list (token) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE watch_list DROP tracked_events');
}
}

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\Groups;
use Symfony\Component\Serializer\Attribute\SerializedName; use Symfony\Component\Serializer\Attribute\SerializedName;
use Symfony\Component\Uid\Uuid; use Symfony\Component\Uid\Uuid;
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Entity(repositoryClass: WatchListRepository::class)] #[ORM\Entity(repositoryClass: WatchListRepository::class)]
#[ApiResource( #[ApiResource(
@ -166,14 +167,6 @@ class WatchList
#[Groups(['watchlist:create', 'watchlist:list', 'watchlist:item', 'watchlist:update'])] #[Groups(['watchlist:create', 'watchlist:list', 'watchlist:item', 'watchlist:update'])]
private Collection $domains; 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')] #[ORM\ManyToOne(inversedBy: 'watchLists')]
#[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create', 'watchlist:update'])] #[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create', 'watchlist:update'])]
private ?Connector $connector = null; private ?Connector $connector = null;
@ -189,13 +182,27 @@ class WatchList
#[SerializedName('dsn')] #[SerializedName('dsn')]
#[ORM\Column(type: Types::SIMPLE_ARRAY, nullable: true)] #[ORM\Column(type: Types::SIMPLE_ARRAY, nullable: true)]
#[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create', 'watchlist:update'])] #[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create', 'watchlist:update'])]
#[Assert\Unique]
#[Assert\All([
new Assert\Type('string'),
new Assert\NotBlank(),
])]
private ?array $webhookDsn = null; 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() public function __construct()
{ {
$this->token = Uuid::v4(); $this->token = Uuid::v4();
$this->domains = new ArrayCollection(); $this->domains = new ArrayCollection();
$this->watchListTriggers = new ArrayCollection();
$this->createdAt = new \DateTimeImmutable('now'); $this->createdAt = new \DateTimeImmutable('now');
} }
@ -245,36 +252,6 @@ class WatchList
return $this; 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 public function getConnector(): ?Connector
{ {
return $this->connector; return $this->connector;
@ -322,4 +299,16 @@ class WatchList
return $this; 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; namespace App\MessageHandler;
use App\Config\TriggerAction;
use App\Entity\Domain; use App\Entity\Domain;
use App\Entity\DomainEvent; use App\Entity\DomainEvent;
use App\Entity\WatchList; use App\Entity\WatchList;
use App\Entity\WatchListTrigger;
use App\Message\SendDomainEventNotif; use App\Message\SendDomainEventNotif;
use App\Notifier\DomainUpdateNotification; use App\Notifier\DomainUpdateNotification;
use App\Repository\DomainRepository; use App\Repository\DomainRepository;
@ -19,7 +17,6 @@ use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface; use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler; use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\ExceptionInterface;
use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Address;
use Symfony\Component\Notifier\Recipient\Recipient; use Symfony\Component\Notifier\Recipient\Recipient;
@ -47,7 +44,6 @@ final readonly class SendDomainEventNotifHandler
/** /**
* @throws TransportExceptionInterface * @throws TransportExceptionInterface
* @throws \Exception * @throws \Exception
* @throws ExceptionInterface
*/ */
public function __invoke(SendDomainEventNotif $message): void public function __invoke(SendDomainEventNotif $message): void
{ {
@ -64,19 +60,13 @@ final readonly class SendDomainEventNotifHandler
foreach ($domain->getEvents()->filter( foreach ($domain->getEvents()->filter(
fn ($event) => $message->updatedAt < $event->getDate() && $event->getDate() < new \DateTimeImmutable()) as $event fn ($event) => $message->updatedAt < $event->getDate() && $event->getDate() < new \DateTimeImmutable()) as $event
) { ) {
$watchListTriggers = $watchList->getWatchListTriggers() if (!in_array($event->getAction(), $watchList->getTrackedEvents())) {
->filter(fn ($trigger) => $trigger->getEvent() === $event->getAction()); continue;
}
/*
* 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()); $recipient = new Recipient($watchList->getUser()->getEmail());
$notification = new DomainUpdateNotification($this->sender, $event); $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', [ $this->logger->info('New action has been detected on this domain name : an email is sent to user', [
'event' => $event->getAction(), 'event' => $event->getAction(),
'ldhName' => $message->ldhName, 'ldhName' => $message->ldhName,
@ -84,12 +74,9 @@ final readonly class SendDomainEventNotifHandler
]); ]);
$this->mailer->send($notification->asEmailMessage($recipient)->getMessage()); $this->mailer->send($notification->asEmailMessage($recipient)->getMessage());
} elseif (TriggerAction::SendChat == $watchListTrigger->getAction()) {
$webhookDsn = $watchList->getWebhookDsn();
if (null === $webhookDsn || 0 === count($webhookDsn)) {
continue;
}
$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', [ $this->logger->info('New action has been detected on this domain name : a notification is sent to user', [
'event' => $event->getAction(), 'event' => $event->getAction(),
'ldhName' => $message->ldhName, 'ldhName' => $message->ldhName,
@ -100,10 +87,9 @@ final readonly class SendDomainEventNotifHandler
} }
if ($this->influxdbEnabled) { if ($this->influxdbEnabled) {
$this->influxdbService->addDomainNotificationPoint($domain, TriggerAction::SendChat, true); $this->influxdbService->addDomainNotificationPoint($domain, 'chat', true);
} }
$this->statService->incrementStat('stats.alert.sent'); $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; namespace App\Service;
use App\Config\TriggerAction;
use App\Entity\Connector; use App\Entity\Connector;
use App\Entity\Domain; use App\Entity\Domain;
use App\Entity\RdapServer; use App\Entity\RdapServer;
@ -68,12 +67,12 @@ readonly class InfluxdbService
$this->client->close(); $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', [ $this->writePoints(new Point('domain_notification', [
'domain' => $domain->getLdhName(), 'domain' => $domain->getLdhName(),
'tld' => $domain->getTld()->getTld(), 'tld' => $domain->getTld()->getTld(),
'medium' => $triggerAction->value, 'medium' => $triggerAction,
], [ ], [
'success' => $success, 'success' => $success,
])); ]));

View File

@ -36,7 +36,6 @@ final class WatchlistControllerTest extends ApiTestCase
$client = WatchListUpdateProcessorTest::createUserAndWatchlist(); $client = WatchListUpdateProcessorTest::createUserAndWatchlist();
$client->getContainer()->get('doctrine')->getManager()->clear(); $client->getContainer()->get('doctrine')->getManager()->clear();
sleep(2);
$response = $client->request('GET', '/api/tracked'); $response = $client->request('GET', '/api/tracked');
$this->assertResponseIsSuccessful(); $this->assertResponseIsSuccessful();

View File

@ -44,15 +44,13 @@ final class WatchListUpdateProcessorTest extends ApiTestCase
$response = $client->request('PUT', '/api/watchlists/'.$token, ['json' => [ $response = $client->request('PUT', '/api/watchlists/'.$token, ['json' => [
'domains' => ['/api/domains/iana.org', '/api/domains/example.com'], 'domains' => ['/api/domains/iana.org', '/api/domains/example.com'],
'name' => 'My modified Watchlist', 'name' => 'My modified Watchlist',
'triggers' => [ 'trackedEvents' => ['last changed'],
['action' => 'email', 'event' => 'last changed'],
],
]]); ]]);
$this->assertResponseIsSuccessful(); $this->assertResponseIsSuccessful();
$this->assertMatchesResourceItemJsonSchema(WatchList::class); $this->assertMatchesResourceItemJsonSchema(WatchList::class);
$data = $response->toArray(); $data = $response->toArray();
$this->assertCount(2, $data['domains']); $this->assertCount(2, $data['domains']);
$this->assertCount(1, $data['triggers']); $this->assertCount(1, $data['trackedEvents']);
} }
public static function createUserAndWatchlist(?Client $client = null): Client public static function createUserAndWatchlist(?Client $client = null): Client
@ -61,12 +59,7 @@ final class WatchListUpdateProcessorTest extends ApiTestCase
$client->request('POST', '/api/watchlists', ['json' => [ $client->request('POST', '/api/watchlists', ['json' => [
'domains' => ['/api/domains/example.com'], 'domains' => ['/api/domains/example.com'],
'name' => 'My Watchlist', 'name' => 'My Watchlist',
'triggers' => [ 'trackedEvents' => ['last changed', 'transfer', 'expiration', 'deletion'],
['action' => 'email', 'event' => 'last changed'],
['action' => 'email', 'event' => 'transfer'],
['action' => 'email', 'event' => 'expiration'],
['action' => 'email', 'event' => 'deletion'],
],
]]); ]]);
return $client; return $client;