Publication initiale de RelaisSMS : documentation et sources nettoyees

This commit is contained in:
2026-10-21 09:29:39 +02:00
commit ac186b03b1
158 changed files with 24818 additions and 0 deletions
@@ -0,0 +1,232 @@
<?php
namespace App\Services\Calendar;
use App\Contracts\Calendar\CalendarClientInterface;
use Carbon\CarbonInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use RuntimeException;
use SimpleXMLElement;
use Throwable;
class CalDavCalendarClient implements CalendarClientInterface
{
public function __construct(
private readonly ClientInterface $http,
) {}
/**
* @return array<int, CalendarRemoteEvent>
*/
public function fetchEvents(CarbonInterface $from, CarbonInterface $to): array
{
try {
$events = $this->fetchEventsWithReport($from, $to);
if ($events !== []) {
return $events;
}
} catch (GuzzleException|RuntimeException) {
// Some CalDAV servers restrict calendar-query. Fall back to PROPFIND + GET.
}
return $this->fetchEventsWithPropfind();
}
/**
* @return array<int, CalendarRemoteEvent>
*/
private function fetchEventsWithReport(CarbonInterface $from, CarbonInterface $to): array
{
$url = rtrim((string) config('relais_sms.caldav.url'), '/').'/';
$username = (string) config('relais_sms.caldav.username');
$password = (string) config('relais_sms.caldav.password');
$this->ensureConfigured($url, $username, $password);
$response = $this->http->request('REPORT', $url, [
'auth' => [$username, $password],
'headers' => [
'Content-Type' => 'application/xml; charset=utf-8',
'Depth' => '1',
],
'body' => $this->calendarQueryBody($from, $to),
'timeout' => (float) config('relais_sms.caldav.timeout'),
]);
return $this->parseReport((string) $response->getBody());
}
/**
* @return array<int, CalendarRemoteEvent>
*/
private function fetchEventsWithPropfind(): array
{
$url = rtrim((string) config('relais_sms.caldav.url'), '/').'/';
$username = (string) config('relais_sms.caldav.username');
$password = (string) config('relais_sms.caldav.password');
$this->ensureConfigured($url, $username, $password);
$response = $this->http->request('PROPFIND', $url, [
'auth' => [$username, $password],
'headers' => [
'Content-Type' => 'application/xml; charset=utf-8',
'Depth' => '1',
],
'body' => <<<'XML'
<?xml version="1.0" encoding="utf-8" ?>
<d:propfind xmlns:d="DAV:">
<d:prop>
<d:getetag />
</d:prop>
</d:propfind>
XML,
'timeout' => (float) config('relais_sms.caldav.timeout'),
]);
$entries = $this->parsePropfind((string) $response->getBody(), $url);
$events = [];
foreach ($entries as $entry) {
$eventResponse = $this->http->request('GET', $entry['url'], [
'auth' => [$username, $password],
'headers' => [
'Accept' => 'text/calendar,text/plain,*/*',
],
'timeout' => (float) config('relais_sms.caldav.timeout'),
]);
$events[] = new CalendarRemoteEvent(
href: $entry['href'],
etag: $entry['etag'],
ical: (string) $eventResponse->getBody(),
);
}
return $events;
}
private function ensureConfigured(string $url, string $username, string $password): void
{
if ($url === '/' || $username === '' || $password === '') {
throw new RuntimeException('Configuration CalDAV agenda incomplete.');
}
}
private function calendarQueryBody(CarbonInterface $from, CarbonInterface $to): string
{
$start = $from->copy()->utc()->format('Ymd\THis\Z');
$end = $to->copy()->utc()->format('Ymd\THis\Z');
return <<<XML
<?xml version="1.0" encoding="utf-8" ?>
<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
<d:prop>
<d:getetag />
<c:calendar-data />
</d:prop>
<c:filter>
<c:comp-filter name="VCALENDAR">
<c:comp-filter name="VEVENT">
<c:time-range start="$start" end="$end" />
</c:comp-filter>
</c:comp-filter>
</c:filter>
</c:calendar-query>
XML;
}
/**
* @return array<int, CalendarRemoteEvent>
*/
private function parseReport(string $xml): array
{
try {
$document = new SimpleXMLElement($xml);
} catch (Throwable $exception) {
throw new RuntimeException('Reponse CalDAV REPORT illisible.', previous: $exception);
}
$document->registerXPathNamespace('d', 'DAV:');
$responses = $document->xpath('//d:response') ?: [];
$events = [];
foreach ($responses as $response) {
$response->registerXPathNamespace('d', 'DAV:');
$response->registerXPathNamespace('c', 'urn:ietf:params:xml:ns:caldav');
$hrefNodes = $response->xpath('./d:href') ?: [];
$calendarDataNodes = $response->xpath('.//c:calendar-data') ?: [];
$href = trim((string) ($hrefNodes[0] ?? ''));
$ical = (string) ($calendarDataNodes[0] ?? '');
if ($href === '' || trim($ical) === '') {
continue;
}
$etagNodes = $response->xpath('.//d:getetag') ?: [];
$events[] = new CalendarRemoteEvent(
href: $href,
etag: trim((string) ($etagNodes[0] ?? ''), '"') ?: null,
ical: $ical,
);
}
return $events;
}
/**
* @return array<int, array{href: string, etag: ?string, url: string}>
*/
private function parsePropfind(string $xml, string $baseUrl): array
{
try {
$document = new SimpleXMLElement($xml);
} catch (Throwable $exception) {
throw new RuntimeException('Reponse CalDAV PROPFIND illisible.', previous: $exception);
}
$document->registerXPathNamespace('d', 'DAV:');
$responses = $document->xpath('//d:response') ?: [];
$entries = [];
foreach ($responses as $response) {
$response->registerXPathNamespace('d', 'DAV:');
$hrefNodes = $response->xpath('./d:href') ?: [];
$href = trim((string) ($hrefNodes[0] ?? ''));
if ($href === '' || ! str_ends_with(strtolower(parse_url($href, PHP_URL_PATH) ?: $href), '.ics')) {
continue;
}
$etagNodes = $response->xpath('.//d:getetag') ?: [];
$entries[] = [
'href' => $href,
'etag' => trim((string) ($etagNodes[0] ?? ''), '"') ?: null,
'url' => $this->absoluteUrl($baseUrl, $href),
];
}
return $entries;
}
private function absoluteUrl(string $baseUrl, string $href): string
{
if (parse_url($href, PHP_URL_SCHEME)) {
return $href;
}
$base = parse_url($baseUrl);
if (! isset($base['scheme'], $base['host'])) {
throw new RuntimeException('URL CalDAV agenda invalide.');
}
$port = isset($base['port']) ? ':'.$base['port'] : '';
$path = str_starts_with($href, '/') ? $href : rtrim((string) ($base['path'] ?? ''), '/').'/'.$href;
return $base['scheme'].'://'.$base['host'].$port.$path;
}
}
@@ -0,0 +1,214 @@
<?php
namespace App\Services\Calendar;
use App\Contracts\Calendar\CalendarClientInterface;
use App\Models\CalendarEvent;
use App\Models\CalendarReminder;
use App\Models\SourceSyncRun;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Throwable;
class CalendarEventSyncService
{
public function __construct(
private readonly CalendarClientInterface $client,
private readonly ICalendarParser $parser,
) {}
public function sync(?Carbon $from = null, ?Carbon $to = null): SourceSyncRun
{
$from ??= Carbon::now()->subDay();
$to ??= Carbon::now()->addDays((int) config('relais_sms.caldav.lookahead_days', 90));
$run = SourceSyncRun::query()->create([
'source' => 'caldav_calendar',
'status' => 'running',
'started_at' => Carbon::now(),
]);
try {
$remoteEvents = $this->client->fetchEvents($from, $to);
DB::transaction(function () use ($run, $remoteEvents, $from, $to): void {
$seenExternalIds = [];
$syncedEvents = 0;
$scheduledReminders = 0;
foreach ($remoteEvents as $remoteEvent) {
foreach ($this->parser->parse($remoteEvent->ical, $from, $to) as $parsedEvent) {
$externalId = $parsedEvent->recurrenceId === null
? $parsedEvent->uid
: 'recurrence:'.sha1($parsedEvent->uid.'|'.$parsedEvent->recurrenceId->format('Y-m-d H:i:s'));
$seenExternalIds[] = $externalId;
$event = $this->upsertEvent($externalId, $remoteEvent, $parsedEvent);
$scheduledReminders += $this->syncReminders($event, $parsedEvent);
$syncedEvents++;
}
}
$cancelledEvents = $this->cancelMissingEvents($seenExternalIds);
$run->update([
'status' => 'success',
'finished_at' => Carbon::now(),
'fetched_contacts' => count($remoteEvents),
'synced_contacts' => $syncedEvents,
'deleted_contacts' => $cancelledEvents,
'message' => $syncedEvents.' evenement(s) CalDAV synchronise(s), '.$scheduledReminders.' rappel(s) programme(s).',
]);
});
} catch (Throwable $exception) {
$run->update([
'status' => 'failed',
'finished_at' => Carbon::now(),
'error' => $exception->getMessage(),
]);
throw $exception;
}
return $run->refresh();
}
private function upsertEvent(string $externalId, CalendarRemoteEvent $remoteEvent, ParsedCalendarEvent $parsedEvent): CalendarEvent
{
$event = CalendarEvent::query()
->where('source', 'caldav')
->where('external_id', $externalId)
->first();
// Preserve the reminder history when an existing single event becomes a series.
if (! $event && $parsedEvent->recurrenceId !== null) {
$event = CalendarEvent::query()
->where('source', 'caldav')
->where('external_id', $parsedEvent->uid)
->where('starts_at', $parsedEvent->recurrenceId->format('Y-m-d H:i:s'))
->first();
}
$attributes = [
'source' => 'caldav',
'external_id' => $externalId,
'remote_url' => $remoteEvent->href,
'remote_etag' => $remoteEvent->etag,
'summary' => $parsedEvent->summary,
'description' => $parsedEvent->description,
'location' => $parsedEvent->location,
'starts_at' => $parsedEvent->startsAt,
'ends_at' => $parsedEvent->endsAt,
'attendees' => $parsedEvent->attendees,
'synced_at' => Carbon::now(),
'deleted_at' => null,
];
if (! $event) {
return CalendarEvent::query()->create($attributes);
}
$event->fill($attributes);
$event->save();
return $event;
}
private function syncReminders(CalendarEvent $event, ParsedCalendarEvent $parsedEvent): int
{
$seenReminderKeys = [];
$scheduledReminders = 0;
foreach ($parsedEvent->alarms as $index => $alarm) {
if ($alarm->action !== 'DISPLAY') {
continue;
}
$remindAt = $this->remindAt($parsedEvent, $alarm);
if ($remindAt === null) {
continue;
}
$reminderKey = sha1($alarm->action.'|'.$alarm->trigger.'|'.$index);
$seenReminderKeys[] = $reminderKey;
$reminder = CalendarReminder::query()
->where('calendar_event_id', $event->id)
->where('reminder_key', $reminderKey)
->first();
$attributes = [
'action' => $alarm->action,
'trigger_minutes' => $alarm->triggerMinutes,
'remind_at' => $remindAt,
];
if (! $reminder) {
CalendarReminder::query()->create(array_merge($attributes, [
'calendar_event_id' => $event->id,
'reminder_key' => $reminderKey,
'status' => 'pending',
]));
$scheduledReminders++;
continue;
}
if (! in_array($reminder->status, ['sent', 'sending', 'uncertain', 'skipped'], true)) {
$reminder->update(array_merge($attributes, [
'status' => 'pending',
'last_error' => null,
]));
$scheduledReminders++;
}
}
CalendarReminder::query()
->where('calendar_event_id', $event->id)
->whereNotIn('reminder_key', $seenReminderKeys ?: [''])
->whereIn('status', ['pending', 'failed'])
->update([
'status' => 'cancelled',
'last_error' => 'Rappel absent de la derniere synchronisation.',
]);
return $scheduledReminders;
}
private function remindAt(ParsedCalendarEvent $event, ParsedCalendarAlarm $alarm): ?Carbon
{
if ($alarm->absoluteRemindAt !== null) {
return $alarm->absoluteRemindAt;
}
if ($event->startsAt === null || $alarm->triggerMinutes === null) {
return null;
}
return $event->startsAt->copy()->addMinutes($alarm->triggerMinutes);
}
/**
* @param array<int, string> $seenExternalIds
*/
private function cancelMissingEvents(array $seenExternalIds): int
{
$events = CalendarEvent::query()
->where('source', 'caldav')
->whereNull('deleted_at')
->whereNotIn('external_id', $seenExternalIds ?: [''])
->get();
foreach ($events as $event) {
$event->update(['deleted_at' => Carbon::now()]);
$event->reminders()
->whereIn('status', ['pending', 'failed'])
->update([
'status' => 'cancelled',
'last_error' => 'Evenement absent de la derniere synchronisation.',
]);
}
return $events->count();
}
}
@@ -0,0 +1,82 @@
<?php
namespace App\Services\Calendar;
use Carbon\CarbonInterface;
use DateTimeZone;
use RuntimeException;
use Sabre\VObject\Component\VCalendar;
use Sabre\VObject\Component\VEvent;
use Sabre\VObject\Reader;
class CalendarOccurrenceExpander
{
public function expand(string $ical, CarbonInterface $from, CarbonInterface $to): string
{
if (! preg_match('/^(RRULE|RDATE|RECURRENCE-ID)[;:]/mi', $ical)) {
return $ical;
}
$calendar = Reader::read($ical);
if (! $calendar instanceof VCalendar) {
throw new RuntimeException('La source agenda ne contient pas un calendrier iCalendar.');
}
$additionalDates = clone $calendar;
$additionalUids = [];
foreach ($calendar->select('VEVENT') as $event) {
// A cancelled detached occurrence may contain only UID and RECURRENCE-ID.
// It must still suppress the original occurrence during expansion.
if (! isset($event->DTSTART) && isset($event->{'RECURRENCE-ID'})) {
$start = clone $event->{'RECURRENCE-ID'};
$start->name = 'DTSTART';
$event->add($start);
}
// VObject chooses RDATE instead of RRULE when both are present.
// Expand their union separately, then deduplicate by occurrence identity.
if (isset($event->RRULE, $event->RDATE)) {
$additionalUids[] = (string) $event->UID;
unset($event->RDATE);
}
}
$timezone = new DateTimeZone((string) config('app.timezone', 'UTC'));
$expanded = $calendar->expand($from, $to, $timezone);
if ($additionalUids !== []) {
foreach ($additionalDates->select('VEVENT') as $event) {
if (! in_array((string) $event->UID, $additionalUids, true)) {
$additionalDates->remove($event);
} else {
unset($event->RRULE);
if (! isset($event->DTSTART) && isset($event->{'RECURRENCE-ID'})) {
$start = clone $event->{'RECURRENCE-ID'};
$start->name = 'DTSTART';
$event->add($start);
}
}
}
$seen = [];
foreach ($expanded->select('VEVENT') as $event) {
$seen[$this->identity($event)] = true;
}
foreach ($additionalDates->expand($from, $to, $timezone)->select('VEVENT') as $event) {
$key = $this->identity($event);
if (! isset($seen[$key])) {
$expanded->add(clone $event);
$seen[$key] = true;
}
}
}
return $expanded->serialize();
}
private function identity(VEvent $event): string
{
return (string) $event->UID.'|'.(string) $event->{'RECURRENCE-ID'};
}
}
@@ -0,0 +1,269 @@
<?php
namespace App\Services\Calendar;
use App\Models\CalendarReminder;
use App\Models\Contact;
use App\Models\User;
use App\Services\Recipients\RecipientResolver;
use App\Services\Sms\SmsCampaignSender;
use App\Services\Sms\SmsMessageLength;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class CalendarReminderSender
{
public function __construct(
private readonly RecipientResolver $recipientResolver,
private readonly SmsCampaignSender $campaignSender,
private readonly SmsMessageLength $smsMessageLength,
) {}
public function sendDue(?Carbon $now = null, int $limit = 50): int
{
$now ??= Carbon::now();
$dueAt = $now->copy()->utc()->format('Y-m-d H:i:s');
$sent = 0;
CalendarReminder::query()
->with('event')
->where('status', 'pending')
->whereNotNull('remind_at')
->where('remind_at', '<=', $dueAt)
->orderBy('remind_at')
->limit($limit)
->get()
->each(function (CalendarReminder $reminder) use (&$sent, $now): void {
if ($this->sendReminder($reminder, $now)) {
$sent++;
}
});
return $sent;
}
private function sendReminder(CalendarReminder $reminder, Carbon $now): bool
{
$reminder = DB::transaction(function () use ($reminder): ?CalendarReminder {
$fresh = CalendarReminder::query()
->whereKey($reminder->id)
->lockForUpdate()
->first();
if (! $fresh || $fresh->status !== 'pending') {
return null;
}
$fresh->update(['status' => 'sending']);
return $fresh->load('event');
});
if (! $reminder || ! $reminder->event || $reminder->event->deleted_at !== null) {
return false;
}
$rawStartsAt = $reminder->event->getRawOriginal('starts_at');
$rawRemindAt = $reminder->getRawOriginal('remind_at');
if ($rawStartsAt !== null && $rawRemindAt !== null) {
$startsAt = Carbon::parse((string) $rawStartsAt, 'UTC');
$remindAt = Carbon::parse((string) $rawRemindAt, 'UTC');
if ($remindAt->lessThan($startsAt) && $startsAt->lessThanOrEqualTo($now)) {
$reminder->update([
'status' => 'skipped',
'last_error' => 'Rappel expire : evenement deja commence.',
]);
return false;
}
}
$resolution = $this->recipientResolver->resolve(
$this->contactIdsForReminder($reminder),
$this->configuredIds('relais_sms.caldav.default_group_ids'),
);
if ($resolution->recipients === []) {
$reminder->update([
'status' => 'skipped',
'last_error' => 'Aucun destinataire SMS valide pour ce rappel.',
]);
return false;
}
$maxRecipients = (int) config('relais_sms.default_settings.max_sms_per_campaign', 100);
if (count($resolution->recipients) > $maxRecipients) {
$reminder->update([
'status' => 'failed',
'last_error' => 'La selection depasse la limite de '.$maxRecipients.' SMS.',
]);
return false;
}
$user = $this->user();
if ($user === null) {
$reminder->update([
'status' => 'failed',
'last_error' => 'Aucun utilisateur applicatif disponible.',
]);
return false;
}
$campaign = $this->campaignSender->send($user, $this->message($reminder), $resolution->recipients);
$reminder->update([
'sms_campaign_id' => $campaign->id,
'status' => in_array($campaign->status, ['failed', 'uncertain'], true) ? $campaign->status : 'sent',
'last_error' => $campaign->error_message,
'sent_at' => in_array($campaign->status, ['failed', 'uncertain'], true) ? null : Carbon::now(),
]);
return in_array($campaign->status, ['sent', 'partial'], true);
}
/**
* @return array<int, int>
*/
private function contactIdsForReminder(CalendarReminder $reminder): array
{
$ids = $this->configuredIds('relais_sms.caldav.default_contact_ids');
$attendeeEmails = collect($reminder->event->attendees ?? [])
->pluck('email')
->filter()
->map(fn (string $email): string => strtolower($email))
->unique()
->values()
->all();
if ($attendeeEmails !== []) {
$ids = array_merge($ids, Contact::query()
->whereIn(DB::raw('lower(email)'), $attendeeEmails)
->pluck('id')
->all());
}
return array_values(array_unique(array_map('intval', $ids)));
}
/**
* @return array<int, int>
*/
private function configuredIds(string $key): array
{
return collect(config($key, []))
->map(fn (mixed $id): int => (int) $id)
->filter(fn (int $id): bool => $id > 0)
->unique()
->values()
->all();
}
private function user(): ?User
{
$userId = (int) config('relais_sms.caldav.reminder_user_id');
if ($userId > 0) {
return User::query()->find($userId);
}
return User::query()->orderBy('id')->first();
}
private function message(CalendarReminder $reminder): string
{
$event = $reminder->event;
$rawStartsAt = $event->getRawOriginal('starts_at');
$startsAt = $rawStartsAt === null
? 'date inconnue'
: Carbon::parse((string) $rawStartsAt, 'UTC')
->timezone((string) config('relais_sms.caldav.display_timezone'))
->format('d/m/Y H:i');
$titlePrefix = 'Rappel : ';
$title = trim((string) ($event->summary ?: 'Evenement'));
$title = $this->smsMessageLength->truncateBetween(
$titlePrefix,
$title,
"\n".$startsAt,
);
$coreLines = [$titlePrefix.$title, $startsAt];
$header = '';
$footer = '';
$configuredHeader = trim($this->configuredText('relais_sms.caldav.reminder_message_header'));
if ($configuredHeader !== '' && $this->smsMessageLength->fitsInOneSms($this->assembleMessage($coreLines, $configuredHeader))) {
$header = $configuredHeader;
}
$configuredFooter = trim($this->configuredText('relais_sms.caldav.reminder_message_footer'));
if ($configuredFooter !== '' && $this->smsMessageLength->fitsInOneSms($this->assembleMessage($coreLines, $header, $configuredFooter))) {
$footer = $configuredFooter;
}
$location = trim(preg_replace('/\s+/', ' ', (string) $event->location) ?? '');
if ($location !== '' && $this->fitsWithOptionalParts($coreLines, [$location], $header, $footer)) {
$coreLines[] = $location;
}
$description = $this->description((string) $event->description);
if ($description !== '') {
$prefix = collect([$header, ...$coreLines])
->filter(fn (string $part): bool => $part !== '')
->implode("\n")."\n";
$suffix = $footer === '' ? '' : "\n".$footer;
$description = $this->smsMessageLength->truncateBetween($prefix, $description, $suffix);
if ($description !== '') {
$coreLines[] = $description;
}
}
return $this->assembleMessage($coreLines, $header, $footer);
}
/**
* @param array<int, string> $coreLines
* @param array<int, string> $optionalLines
*/
private function fitsWithOptionalParts(array $coreLines, array $optionalLines, string $header, string $footer): bool
{
return $this->smsMessageLength->fitsInOneSms($this->assembleMessage([...$coreLines, ...$optionalLines], $header, $footer));
}
/** @param array<int, string> $coreLines */
private function assembleMessage(array $coreLines, string $header = '', string $footer = ''): string
{
return collect([
$header,
...$coreLines,
$footer,
])->map(fn (string $part): string => trim($part))
->filter()
->implode("\n");
}
private function description(string $description): string
{
$description = trim(preg_replace('/\s+/', ' ', $description) ?? '');
if ($description === '') {
return '';
}
$maxLength = max(1, (int) config('relais_sms.caldav.reminder_description_max_length', 120));
return Str::limit($description, $maxLength, '[...]');
}
private function configuredText(string $key): string
{
return str_replace('\n', "\n", (string) config($key, ''));
}
}
@@ -0,0 +1,12 @@
<?php
namespace App\Services\Calendar;
class CalendarRemoteEvent
{
public function __construct(
public readonly string $href,
public readonly ?string $etag,
public readonly string $ical,
) {}
}
+341
View File
@@ -0,0 +1,341 @@
<?php
namespace App\Services\Calendar;
use Carbon\CarbonInterface;
use Illuminate\Support\Carbon;
class ICalendarParser
{
/**
* @return array<int, ParsedCalendarEvent>
*/
public function parse(string $ical, ?CarbonInterface $from = null, ?CarbonInterface $to = null): array
{
$ical = (new CalendarOccurrenceExpander)->expand(
$ical,
$from ?? Carbon::now()->subDay(),
$to ?? Carbon::now()->addDays((int) config('relais_sms.caldav.lookahead_days', 90)),
);
$lines = $this->unfoldLines($ical);
$events = [];
$eventLines = null;
$alarmLines = null;
$alarms = [];
foreach ($lines as $line) {
$upper = strtoupper($line);
if ($upper === 'BEGIN:VEVENT') {
$eventLines = [];
$alarms = [];
continue;
}
if ($upper === 'END:VEVENT') {
if ($eventLines !== null) {
$event = $this->parseEvent($eventLines, $alarms);
if (! $event->cancelled) {
$events[] = $event;
}
}
$eventLines = null;
$alarmLines = null;
$alarms = [];
continue;
}
if ($eventLines === null) {
continue;
}
if ($upper === 'BEGIN:VALARM') {
$alarmLines = [];
continue;
}
if ($upper === 'END:VALARM') {
if ($alarmLines !== null) {
$alarms[] = $this->parseAlarm($alarmLines);
}
$alarmLines = null;
continue;
}
if ($alarmLines !== null) {
$alarmLines[] = $line;
continue;
}
$eventLines[] = $line;
}
return array_values(array_filter($events, fn (ParsedCalendarEvent $event): bool => $event->uid !== ''));
}
/**
* @param array<int, string> $lines
* @param array<int, ParsedCalendarAlarm> $alarms
*/
private function parseEvent(array $lines, array $alarms): ParsedCalendarEvent
{
$uid = '';
$summary = null;
$description = null;
$location = null;
$startsAt = null;
$endsAt = null;
$attendees = [];
$recurrenceId = null;
$cancelled = false;
foreach ($lines as $line) {
$property = $this->parseProperty($line);
$name = strtoupper($property['name']);
match ($name) {
'UID' => $uid = $this->decodeText($property['value']),
'SUMMARY' => $summary = $this->decodeText($property['value']),
'DESCRIPTION' => $description = $this->decodeText($property['value']),
'LOCATION' => $location = $this->decodeText($property['value']),
'DTSTART' => $startsAt = $this->parseDateTime($property['value'], $property['params']),
'DTEND' => $endsAt = $this->parseDateTime($property['value'], $property['params']),
'RECURRENCE-ID' => $recurrenceId = $this->parseDateTime($property['value'], $property['params']),
'STATUS' => $cancelled = strtoupper($property['value']) === 'CANCELLED',
'ATTENDEE', 'ORGANIZER' => $attendees[] = $this->parseAttendee($property['value'], $property['params']),
default => null,
};
}
return new ParsedCalendarEvent(
uid: $uid,
summary: $summary,
description: $description,
location: $location,
startsAt: $startsAt,
endsAt: $endsAt,
attendees: array_values(array_filter(
$attendees,
fn (array $attendee): bool => $attendee['email'] !== '',
)),
alarms: $alarms,
recurrenceId: $recurrenceId,
cancelled: $cancelled,
);
}
/**
* @param array<int, string> $lines
*/
private function parseAlarm(array $lines): ParsedCalendarAlarm
{
$action = '';
$trigger = '';
$triggerMinutes = null;
$absoluteRemindAt = null;
foreach ($lines as $line) {
$property = $this->parseProperty($line);
$name = strtoupper($property['name']);
if ($name === 'ACTION') {
$action = strtoupper($property['value']);
}
if ($name === 'TRIGGER') {
$trigger = $property['value'];
if (strtoupper((string) ($property['params']['VALUE'] ?? '')) === 'DATE-TIME') {
$absoluteRemindAt = $this->parseDateTime($property['value'], $property['params']);
} else {
$triggerMinutes = $this->parseDurationMinutes($property['value']);
}
}
}
return new ParsedCalendarAlarm(
action: $action,
trigger: $trigger,
triggerMinutes: $triggerMinutes,
absoluteRemindAt: $absoluteRemindAt,
);
}
/**
* @return array{name: string, params: array<string, string>, value: string}
*/
private function parseProperty(string $line): array
{
[$left, $value] = $this->splitPropertyValue($line);
$parts = $this->splitOutsideQuotes($left, ';');
$name = array_shift($parts) ?: '';
$params = [];
foreach ($parts as $part) {
[$key, $paramValue] = array_pad(explode('=', $part, 2), 2, '');
if ($key !== '') {
$params[strtoupper($key)] = trim($paramValue, '"');
}
}
return [
'name' => $name,
'params' => $params,
'value' => $value,
];
}
/**
* A CalDAV parameter can contain a URI, for example
* MEMBER="mailto:circle+id@example.test". The colon in that quoted URI is
* not the separator between the property metadata and its value.
*
* @return array{string, string}
*/
private function splitPropertyValue(string $line): array
{
$quoted = false;
for ($index = 0, $length = strlen($line); $index < $length; $index++) {
if ($line[$index] === '"') {
$quoted = ! $quoted;
continue;
}
if ($line[$index] === ':' && ! $quoted) {
return [substr($line, 0, $index), substr($line, $index + 1)];
}
}
return [$line, ''];
}
/**
* @return array<int, string>
*/
private function splitOutsideQuotes(string $value, string $delimiter): array
{
$parts = [];
$part = '';
$quoted = false;
for ($index = 0, $length = strlen($value); $index < $length; $index++) {
$character = $value[$index];
if ($character === '"') {
$quoted = ! $quoted;
}
if ($character === $delimiter && ! $quoted) {
$parts[] = $part;
$part = '';
continue;
}
$part .= $character;
}
$parts[] = $part;
return $parts;
}
/**
* @param array<string, string> $params
* @return array{email: string, name: ?string}
*/
private function parseAttendee(string $value, array $params): array
{
$email = preg_replace('/^mailto:/i', '', trim($value)) ?? '';
return [
'email' => strtolower($email),
'name' => isset($params['CN']) ? $this->decodeText($params['CN']) : null,
];
}
/**
* @param array<string, string> $params
*/
private function parseDateTime(string $value, array $params): ?Carbon
{
$value = trim($value);
if ($value === '') {
return null;
}
$timezone = $params['TZID'] ?? config('app.timezone', 'UTC');
if (str_ends_with($value, 'Z')) {
return Carbon::createFromFormat('Ymd\THis\Z', $value, 'UTC')?->utc();
}
if (str_contains($value, 'T')) {
return Carbon::createFromFormat('Ymd\THis', $value, $timezone)?->utc();
}
return Carbon::createFromFormat('Ymd', $value, $timezone)?->startOfDay()->utc();
}
private function parseDurationMinutes(string $value): ?int
{
$value = strtoupper(trim($value));
if (! preg_match('/^([+-])?P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/', $value, $matches)) {
return null;
}
$sign = ($matches[1] ?? '') === '-' ? -1 : 1;
$days = (int) ($matches[2] ?? 0);
$hours = (int) ($matches[3] ?? 0);
$minutes = (int) ($matches[4] ?? 0);
$seconds = (int) ($matches[5] ?? 0);
return $sign * (($days * 24 * 60) + ($hours * 60) + $minutes + (int) ceil($seconds / 60));
}
/**
* @return array<int, string>
*/
private function unfoldLines(string $ical): array
{
$rawLines = preg_split('/\r\n|\n|\r/', $ical) ?: [];
$lines = [];
foreach ($rawLines as $line) {
if ($line === '') {
continue;
}
if ((str_starts_with($line, ' ') || str_starts_with($line, "\t")) && $lines !== []) {
$lines[array_key_last($lines)] .= substr($line, 1);
continue;
}
$lines[] = $line;
}
return $lines;
}
private function decodeText(string $value): string
{
return str_replace(
['\\n', '\\N', '\\,', '\\;', '\\\\'],
["\n", "\n", ',', ';', '\\'],
$value,
);
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Services\Calendar;
use Illuminate\Support\Carbon;
class ParsedCalendarAlarm
{
public function __construct(
public readonly string $action,
public readonly string $trigger,
public readonly ?int $triggerMinutes,
public readonly ?Carbon $absoluteRemindAt,
) {}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Services\Calendar;
use Illuminate\Support\Carbon;
class ParsedCalendarEvent
{
/**
* @param array<int, array{email: string, name: ?string}> $attendees
* @param array<int, ParsedCalendarAlarm> $alarms
*/
public function __construct(
public readonly string $uid,
public readonly ?string $summary,
public readonly ?string $description,
public readonly ?string $location,
public readonly ?Carbon $startsAt,
public readonly ?Carbon $endsAt,
public readonly array $attendees,
public readonly array $alarms,
public readonly ?Carbon $recurrenceId = null,
public readonly bool $cancelled = false,
) {}
}
+213
View File
@@ -0,0 +1,213 @@
<?php
namespace App\Services\CardDav;
use App\Contracts\CardDav\CardDavClientInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use RuntimeException;
use SimpleXMLElement;
use Throwable;
class CardDavClient implements CardDavClientInterface
{
public function __construct(
private readonly ClientInterface $http,
) {}
public function fetchCards(): array
{
try {
$cards = $this->fetchCardsWithReport();
if ($cards !== []) {
return $cards;
}
} catch (GuzzleException|RuntimeException) {
// Some CardDAV servers restrict addressbook-query. Fall back to PROPFIND + GET.
}
return $this->fetchCardsWithPropfind();
}
/**
* @return array<int, CardDavRemoteCard>
*/
private function fetchCardsWithReport(): array
{
$url = rtrim((string) config('relais_sms.carddav.url'), '/').'/';
$username = (string) config('relais_sms.carddav.username');
$password = (string) config('relais_sms.carddav.password');
$this->ensureConfigured($url, $username, $password);
$response = $this->http->request('REPORT', $url, [
'auth' => [$username, $password],
'headers' => [
'Content-Type' => 'application/xml; charset=utf-8',
'Depth' => '1',
],
'body' => <<<'XML'
<?xml version="1.0" encoding="utf-8" ?>
<c:addressbook-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:carddav">
<d:prop>
<d:getetag />
<c:address-data />
</d:prop>
</c:addressbook-query>
XML,
'timeout' => (float) config('relais_sms.carddav.timeout'),
]);
return $this->parseReport((string) $response->getBody());
}
/**
* @return array<int, CardDavRemoteCard>
*/
private function fetchCardsWithPropfind(): array
{
$url = rtrim((string) config('relais_sms.carddav.url'), '/').'/';
$username = (string) config('relais_sms.carddav.username');
$password = (string) config('relais_sms.carddav.password');
$this->ensureConfigured($url, $username, $password);
$response = $this->http->request('PROPFIND', $url, [
'auth' => [$username, $password],
'headers' => [
'Content-Type' => 'application/xml; charset=utf-8',
'Depth' => '1',
],
'body' => <<<'XML'
<?xml version="1.0" encoding="utf-8" ?>
<d:propfind xmlns:d="DAV:">
<d:prop>
<d:getetag />
</d:prop>
</d:propfind>
XML,
'timeout' => (float) config('relais_sms.carddav.timeout'),
]);
$entries = $this->parsePropfind((string) $response->getBody(), $url);
$cards = [];
foreach ($entries as $entry) {
$cardResponse = $this->http->request('GET', $entry['url'], [
'auth' => [$username, $password],
'headers' => [
'Accept' => 'text/vcard,text/x-vcard,text/plain,*/*',
],
'timeout' => (float) config('relais_sms.carddav.timeout'),
]);
$cards[] = new CardDavRemoteCard(
href: $entry['href'],
etag: $entry['etag'],
vcard: (string) $cardResponse->getBody(),
);
}
return $cards;
}
private function ensureConfigured(string $url, string $username, string $password): void
{
if ($url === '/' || $username === '' || $password === '') {
throw new RuntimeException('Configuration CardDAV incomplete.');
}
}
/**
* @return array<int, CardDavRemoteCard>
*/
private function parseReport(string $xml): array
{
try {
$document = new SimpleXMLElement($xml);
} catch (Throwable $exception) {
throw new RuntimeException('Reponse CardDAV REPORT illisible.', previous: $exception);
}
$document->registerXPathNamespace('d', 'DAV:');
$responses = $document->xpath('//d:response') ?: [];
$cards = [];
foreach ($responses as $response) {
$response->registerXPathNamespace('d', 'DAV:');
$response->registerXPathNamespace('c', 'urn:ietf:params:xml:ns:carddav');
$hrefNodes = $response->xpath('./d:href') ?: [];
$cardNodes = $response->xpath('.//c:address-data') ?: [];
$href = trim((string) ($hrefNodes[0] ?? ''));
$vcard = (string) ($cardNodes[0] ?? '');
if ($href === '' || trim($vcard) === '') {
continue;
}
$etagNodes = $response->xpath('.//d:getetag') ?: [];
$cards[] = new CardDavRemoteCard(
href: $href,
etag: trim((string) ($etagNodes[0] ?? ''), '"') ?: null,
vcard: $vcard,
);
}
return $cards;
}
/**
* @return array<int, array{href: string, etag: ?string, url: string}>
*/
private function parsePropfind(string $xml, string $baseUrl): array
{
try {
$document = new SimpleXMLElement($xml);
} catch (Throwable $exception) {
throw new RuntimeException('Reponse CardDAV PROPFIND illisible.', previous: $exception);
}
$document->registerXPathNamespace('d', 'DAV:');
$responses = $document->xpath('//d:response') ?: [];
$entries = [];
foreach ($responses as $response) {
$response->registerXPathNamespace('d', 'DAV:');
$hrefNodes = $response->xpath('./d:href') ?: [];
$href = trim((string) ($hrefNodes[0] ?? ''));
if ($href === '' || ! str_ends_with(strtolower(parse_url($href, PHP_URL_PATH) ?: $href), '.vcf')) {
continue;
}
$etagNodes = $response->xpath('.//d:getetag') ?: [];
$entries[] = [
'href' => $href,
'etag' => trim((string) ($etagNodes[0] ?? ''), '"') ?: null,
'url' => $this->absoluteUrl($baseUrl, $href),
];
}
return $entries;
}
private function absoluteUrl(string $baseUrl, string $href): string
{
if (parse_url($href, PHP_URL_SCHEME)) {
return $href;
}
$base = parse_url($baseUrl);
if (! isset($base['scheme'], $base['host'])) {
throw new RuntimeException('URL CardDAV invalide.');
}
$port = isset($base['port']) ? ':'.$base['port'] : '';
$path = str_starts_with($href, '/') ? $href : rtrim((string) ($base['path'] ?? ''), '/').'/'.$href;
return $base['scheme'].'://'.$base['host'].$port.$path;
}
}
@@ -0,0 +1,240 @@
<?php
namespace App\Services\CardDav;
use App\Contracts\CardDav\CardDavClientInterface;
use App\Contracts\PhoneNumberNormalizerInterface;
use App\Models\Contact;
use App\Models\ContactGroup;
use App\Models\SourceSyncRun;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Throwable;
class CardDavContactSyncService
{
public function __construct(
private readonly CardDavClientInterface $client,
private readonly VCardParser $parser,
private readonly PhoneNumberNormalizerInterface $phoneNumberNormalizer,
) {}
public function sync(): SourceSyncRun
{
$run = SourceSyncRun::query()->create([
'source' => 'carddav',
'status' => 'running',
'started_at' => Carbon::now(),
]);
try {
$cards = $this->client->fetchCards();
DB::transaction(function () use ($run, $cards): void {
$seenContactExternalIds = [];
$seenGroupExternalIds = [];
$syncedContacts = 0;
foreach ($cards as $card) {
$parsedCard = $this->parser->parse($card->vcard);
$externalId = $this->externalId($parsedCard, $card);
$seenContactExternalIds[] = $externalId;
$contact = $this->upsertContact($externalId, $card, $parsedCard);
$this->replacePhoneNumbers($contact, $parsedCard);
$groupIds = [];
foreach ($parsedCard->categories as $category) {
$group = $this->upsertGroup($category);
$groupIds[] = $group->id;
$seenGroupExternalIds[] = (string) $group->external_id;
}
$this->syncCardDavGroupMemberships($contact, $groupIds);
$syncedContacts++;
}
$deletedContacts = $this->deleteMissingContacts($seenContactExternalIds);
$this->deleteMissingGroups(array_values(array_unique($seenGroupExternalIds)));
$run->update([
'status' => 'success',
'finished_at' => Carbon::now(),
'fetched_contacts' => count($cards),
'synced_contacts' => $syncedContacts,
'deleted_contacts' => $deletedContacts,
'message' => $syncedContacts.' contact(s) CardDAV synchronise(s).',
]);
});
} catch (Throwable $exception) {
$run->update([
'status' => 'failed',
'finished_at' => Carbon::now(),
'error' => $exception->getMessage(),
]);
throw $exception;
}
return $run->refresh();
}
private function upsertContact(string $externalId, CardDavRemoteCard $card, ParsedVCard $parsedCard): Contact
{
$contact = Contact::withTrashed()
->where('source', 'carddav')
->where('external_id', $externalId)
->first();
$attributes = [
'source' => 'carddav',
'external_id' => $externalId,
'remote_url' => $card->href,
'remote_etag' => $card->etag,
'first_name' => $parsedCard->firstName,
'last_name' => $this->lastName($parsedCard),
'organization' => $parsedCard->organization,
'email' => $parsedCard->email,
'synced_at' => Carbon::now(),
];
if (! $contact) {
return Contact::query()->create($attributes);
}
$contact->fill($attributes);
$contact->deleted_at = null;
$contact->save();
return $contact;
}
private function replacePhoneNumbers(Contact $contact, ParsedVCard $parsedCard): void
{
$contact->phoneNumbers()->delete();
$defaultCountry = (string) config('relais_sms.default_settings.default_country');
foreach ($parsedCard->phoneNumbers as $index => $phoneNumber) {
$result = $this->phoneNumberNormalizer->normalize($phoneNumber->rawNumber, $defaultCountry);
$contact->phoneNumbers()->create([
'label' => $phoneNumber->label,
'raw_number' => $result->rawNumber,
'normalized_number' => $result->normalizedNumber,
'country' => $result->country,
'is_valid' => $result->isValid,
'is_mobile' => $result->isMobile,
'is_primary' => $index === 0,
'validation_error' => $result->error,
]);
}
}
private function upsertGroup(string $category): ContactGroup
{
$externalId = Str::slug($category);
$slug = 'carddav-'.$externalId;
$group = ContactGroup::withTrashed()
->where('source', 'carddav')
->where('external_id', $externalId)
->first();
$attributes = [
'source' => 'carddav',
'external_id' => $externalId,
'name' => $category,
'slug' => $slug,
'synced_at' => Carbon::now(),
];
if (! $group) {
return ContactGroup::query()->create($attributes);
}
$group->fill($attributes);
$group->deleted_at = null;
$group->save();
return $group;
}
/**
* @param array<int, int> $groupIds
*/
private function syncCardDavGroupMemberships(Contact $contact, array $groupIds): void
{
$currentCardDavGroupIds = $contact->groups()
->where('contact_groups.source', 'carddav')
->pluck('contact_groups.id')
->all();
if ($currentCardDavGroupIds !== []) {
$contact->groups()->detach($currentCardDavGroupIds);
}
if ($groupIds !== []) {
$contact->groups()->syncWithoutDetaching($groupIds);
}
}
/**
* @param array<int, string> $seenExternalIds
*/
private function deleteMissingContacts(array $seenExternalIds): int
{
$contacts = Contact::query()
->where('source', 'carddav')
->whereNotIn('external_id', $seenExternalIds ?: [''])
->get();
foreach ($contacts as $contact) {
$cardDavGroupIds = $contact->groups()
->where('contact_groups.source', 'carddav')
->pluck('contact_groups.id')
->all();
if ($cardDavGroupIds !== []) {
$contact->groups()->detach($cardDavGroupIds);
}
$contact->delete();
}
return $contacts->count();
}
/**
* @param array<int, string> $seenExternalIds
*/
private function deleteMissingGroups(array $seenExternalIds): void
{
ContactGroup::query()
->where('source', 'carddav')
->whereNotIn('external_id', $seenExternalIds ?: [''])
->delete();
}
private function externalId(ParsedVCard $parsedCard, CardDavRemoteCard $card): string
{
return $parsedCard->uid ?: sha1($card->href);
}
private function lastName(ParsedVCard $parsedCard): string
{
if ($parsedCard->lastName) {
return $parsedCard->lastName;
}
if ($parsedCard->fullName) {
return $parsedCard->fullName;
}
if ($parsedCard->organization) {
return $parsedCard->organization;
}
return 'Contact CardDAV';
}
}
@@ -0,0 +1,12 @@
<?php
namespace App\Services\CardDav;
readonly class CardDavRemoteCard
{
public function __construct(
public string $href,
public ?string $etag,
public string $vcard,
) {}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Services\CardDav;
readonly class ParsedVCard
{
/**
* @param array<int, ParsedVCardPhoneNumber> $phoneNumbers
* @param array<int, string> $categories
*/
public function __construct(
public ?string $uid,
public ?string $fullName,
public ?string $firstName,
public ?string $lastName,
public ?string $organization,
public ?string $email,
public array $phoneNumbers,
public array $categories,
) {}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Services\CardDav;
readonly class ParsedVCardPhoneNumber
{
public function __construct(
public string $rawNumber,
public ?string $label,
) {}
}
+189
View File
@@ -0,0 +1,189 @@
<?php
namespace App\Services\CardDav;
class VCardParser
{
public function parse(string $contents): ParsedVCard
{
$uid = null;
$fullName = null;
$firstName = null;
$lastName = null;
$organization = null;
$email = null;
$phoneNumbers = [];
$categories = [];
foreach ($this->parseLines($contents) as $line) {
[$name, $params, $value] = $line;
match ($name) {
'UID' => $uid = $uid ?? $this->cleanValue($value),
'FN' => $fullName = $fullName ?? $this->cleanValue($value),
'N' => [$lastName, $firstName] = $this->parseStructuredName($value, $lastName, $firstName),
'ORG' => $organization = $organization ?? $this->cleanValue($this->splitEscaped($value, ';')[0] ?? ''),
'EMAIL' => $email = $email ?? $this->cleanValue($value),
'TEL' => $phoneNumbers[] = new ParsedVCardPhoneNumber($this->cleanValue($value), $this->phoneLabel($params)),
'CATEGORIES' => $categories = array_merge($categories, $this->parseCategories($value)),
default => null,
};
}
$categories = array_values(array_unique(array_filter($categories)));
return new ParsedVCard(
uid: $uid,
fullName: $fullName,
firstName: $firstName,
lastName: $lastName,
organization: $organization,
email: $email,
phoneNumbers: array_values(array_filter(
$phoneNumbers,
fn (ParsedVCardPhoneNumber $phoneNumber): bool => $phoneNumber->rawNumber !== '',
)),
categories: $categories,
);
}
/**
* @return array<int, array{0: string, 1: array<string, array<int, string>>, 2: string}>
*/
private function parseLines(string $contents): array
{
$contents = str_replace(["\r\n", "\r"], "\n", $contents);
$contents = preg_replace("/\n[ \t]/", '', $contents) ?? $contents;
$lines = [];
foreach (explode("\n", $contents) as $line) {
$line = trim($line);
if ($line === '' || ! str_contains($line, ':')) {
continue;
}
[$left, $value] = explode(':', $line, 2);
$propertyParts = explode(';', $left);
$name = strtoupper((string) array_shift($propertyParts));
if ($name === 'BEGIN' || $name === 'END' || $name === 'VERSION') {
continue;
}
$params = [];
foreach ($propertyParts as $part) {
if (str_contains($part, '=')) {
[$paramName, $paramValue] = explode('=', $part, 2);
$paramName = strtoupper($paramName);
$params[$paramName] = array_merge(
$params[$paramName] ?? [],
array_map('strtoupper', $this->splitEscaped($paramValue, ',')),
);
continue;
}
$params['TYPE'][] = strtoupper($part);
}
$lines[] = [$name, $params, $value];
}
return $lines;
}
/**
* @return array{0: ?string, 1: ?string}
*/
private function parseStructuredName(string $value, ?string $currentLastName, ?string $currentFirstName): array
{
$parts = $this->splitEscaped($value, ';');
$lastName = $this->cleanValue($parts[0] ?? '') ?: $currentLastName;
$firstName = $this->cleanValue($parts[1] ?? '') ?: $currentFirstName;
return [$lastName, $firstName];
}
/**
* @return array<int, string>
*/
private function parseCategories(string $value): array
{
return array_map(
fn (string $category): string => $this->cleanValue($category),
$this->splitEscaped($value, ','),
);
}
/**
* @param array<string, array<int, string>> $params
*/
private function phoneLabel(array $params): ?string
{
$types = array_filter($params['TYPE'] ?? []);
if ($types === []) {
return null;
}
return implode(', ', array_map(
fn (string $type): string => ucfirst(strtolower($type)),
array_unique($types),
));
}
/**
* @return array<int, string>
*/
private function splitEscaped(string $value, string $separator): array
{
$parts = [];
$buffer = '';
$escaped = false;
foreach (str_split($value) as $char) {
if ($escaped) {
$buffer .= '\\'.$char;
$escaped = false;
continue;
}
if ($char === '\\') {
$escaped = true;
continue;
}
if ($char === $separator) {
$parts[] = $buffer;
$buffer = '';
continue;
}
$buffer .= $char;
}
if ($escaped) {
$buffer .= '\\';
}
$parts[] = $buffer;
return $parts;
}
private function cleanValue(string $value): string
{
$value = str_replace(
['\n', '\N', '\;', '\,', '\\\\'],
["\n", "\n", ';', ',', '\\'],
trim($value),
);
return trim($value);
}
}
@@ -0,0 +1,56 @@
<?php
namespace App\Services\Phone;
use App\Contracts\PhoneNumberNormalizerInterface;
use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberType;
use libphonenumber\PhoneNumberUtil;
class LibPhoneNumberNormalizer implements PhoneNumberNormalizerInterface
{
public function __construct(
private readonly PhoneNumberUtil $phoneNumberUtil,
) {}
public function normalize(string $rawNumber, string $defaultCountry): PhoneNumberResult
{
$rawNumber = trim($rawNumber);
$defaultCountry = strtoupper(trim($defaultCountry));
if ($rawNumber === '') {
return new PhoneNumberResult($rawNumber, null, null, false, false, 'Numero vide.');
}
try {
$number = $this->phoneNumberUtil->parse($rawNumber, $defaultCountry);
} catch (NumberParseException $exception) {
return new PhoneNumberResult($rawNumber, null, null, false, false, $exception->getMessage());
}
$isValid = $this->phoneNumberUtil->isValidNumber($number);
$normalizedNumber = $isValid
? $this->phoneNumberUtil->format($number, PhoneNumberFormat::E164)
: null;
$country = $this->phoneNumberUtil->getRegionCodeForNumber($number);
$mobileRegex = (string) config('relais_sms.default_settings.mobile_phone_regex');
$numberType = $this->phoneNumberUtil->getNumberType($number);
$isMobile = $isValid && (
in_array($numberType, [PhoneNumberType::MOBILE, PhoneNumberType::FIXED_LINE_OR_MOBILE], true)
|| ($mobileRegex !== '' && (
preg_match($mobileRegex, $rawNumber) === 1
|| ($normalizedNumber !== null && preg_match($mobileRegex, $normalizedNumber) === 1)
))
);
return new PhoneNumberResult(
rawNumber: $rawNumber,
normalizedNumber: $normalizedNumber,
country: $country,
isValid: $isValid,
isMobile: $isMobile,
error: $isValid ? null : 'Numero invalide.',
);
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace App\Services\Phone;
final readonly class PhoneNumberResult
{
public function __construct(
public string $rawNumber,
public ?string $normalizedNumber,
public ?string $country,
public bool $isValid,
public bool $isMobile,
public ?string $error = null,
) {}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Services\Recipients;
final readonly class RecipientResolutionResult
{
/**
* @param array<int, array<string, mixed>> $recipients
* @param array<int, array<string, mixed>> $excluded
*/
public function __construct(
public array $recipients,
public array $excluded,
public int $selectedContactCount,
public int $selectedGroupCount,
) {}
/**
* @return array<string, int>
*/
public function summary(): array
{
return [
'selected_contacts' => $this->selectedContactCount,
'selected_groups' => $this->selectedGroupCount,
'ready_numbers' => count($this->recipients),
'excluded_total' => count($this->excluded),
'opt_out' => $this->countExcludedReason('opt_out'),
'missing_phone' => $this->countExcludedReason('missing_phone'),
'invalid' => $this->countExcludedReason('invalid'),
'non_mobile' => $this->countExcludedReason('non_mobile'),
'duplicate' => $this->countExcludedReason('duplicate'),
];
}
/**
* @return array<int, array<string, mixed>>
*/
public function excludedByReason(string $reason): array
{
return array_values(array_filter(
$this->excluded,
fn (array $entry): bool => ($entry['reason'] ?? null) === $reason,
));
}
private function countExcludedReason(string $reason): int
{
return count($this->excludedByReason($reason));
}
}
@@ -0,0 +1,173 @@
<?php
namespace App\Services\Recipients;
use App\Models\Contact;
use App\Models\ContactGroup;
use App\Models\ContactPhoneNumber;
use Illuminate\Support\Collection;
class RecipientResolver
{
/**
* @param array<int, int|string> $contactIds
* @param array<int, int|string> $groupIds
*/
public function resolve(array $contactIds, array $groupIds): RecipientResolutionResult
{
$directContactIds = $this->cleanIds($contactIds);
$selectedGroupIds = $this->cleanIds($groupIds);
$groups = ContactGroup::query()
->with(['contacts' => fn ($query) => $query->select('contacts.id')])
->whereKey($selectedGroupIds)
->orderBy('name')
->get();
/** @var array<int, array<int, string>> $groupNamesByContactId */
$groupNamesByContactId = [];
foreach ($groups as $group) {
foreach ($group->contacts as $contact) {
$groupNamesByContactId[$contact->id][] = $group->name;
}
}
$selectedContactIds = $directContactIds
->merge($groups->flatMap(fn (ContactGroup $group): Collection => $group->contacts->pluck('id')))
->unique()
->values();
$contacts = Contact::query()
->with([
'groups',
'phoneNumbers' => fn ($query) => $query
->orderByDesc('is_primary')
->orderBy('id'),
])
->whereKey($selectedContactIds)
->orderBy('last_name')
->orderBy('first_name')
->get();
$recipients = [];
$excluded = [];
$seenNumbers = [];
foreach ($contacts as $contact) {
$selection = $this->selectionLabels($contact, $directContactIds, $groupNamesByContactId[$contact->id] ?? []);
if ($contact->sms_opt_out) {
$excluded[] = $this->excludedEntry($contact, 'opt_out', null, $selection);
continue;
}
if ($contact->phoneNumbers->isEmpty()) {
$excluded[] = $this->excludedEntry($contact, 'missing_phone', null, $selection);
continue;
}
foreach ($contact->phoneNumbers as $phoneNumber) {
if (! $phoneNumber->is_valid || $phoneNumber->normalized_number === null) {
$excluded[] = $this->excludedEntry($contact, 'invalid', $phoneNumber, $selection);
continue;
}
if (! $phoneNumber->hasDetectedMobileNumber()) {
$excluded[] = $this->excludedEntry($contact, 'non_mobile', $phoneNumber, $selection);
continue;
}
if (isset($seenNumbers[$phoneNumber->normalized_number])) {
$excluded[] = $this->excludedEntry(
$contact,
'duplicate',
$phoneNumber,
$selection,
['duplicate_of' => $seenNumbers[$phoneNumber->normalized_number]],
);
continue;
}
$entry = [
'contact_id' => $contact->id,
'contact_name' => $contact->displayName(),
'phone_number_id' => $phoneNumber->id,
'number' => $phoneNumber->normalized_number,
'raw_number' => $phoneNumber->raw_number,
'label' => $phoneNumber->label,
'selection' => $selection,
];
$recipients[] = $entry;
$seenNumbers[$phoneNumber->normalized_number] = $entry['contact_name'];
}
}
return new RecipientResolutionResult(
recipients: $recipients,
excluded: $excluded,
selectedContactCount: $contacts->count(),
selectedGroupCount: $groups->count(),
);
}
/**
* @param array<int, int|string> $ids
* @return Collection<int, int>
*/
private function cleanIds(array $ids): Collection
{
return collect($ids)
->map(fn (int|string $id): int => (int) $id)
->filter(fn (int $id): bool => $id > 0)
->unique()
->values();
}
/**
* @param Collection<int, int> $directContactIds
* @param array<int, string> $groupNames
* @return array<int, string>
*/
private function selectionLabels(Contact $contact, Collection $directContactIds, array $groupNames): array
{
$selection = $groupNames;
if ($directContactIds->contains($contact->id)) {
array_unshift($selection, 'Selection directe');
}
return array_values(array_unique($selection));
}
/**
* @param array<int, string> $selection
* @param array<string, mixed> $extra
* @return array<string, mixed>
*/
private function excludedEntry(
Contact $contact,
string $reason,
?ContactPhoneNumber $phoneNumber,
array $selection,
array $extra = [],
): array {
return array_merge([
'contact_id' => $contact->id,
'contact_name' => $contact->displayName(),
'contact_source' => $contact->source,
'phone_number_id' => $phoneNumber?->id,
'reason' => $reason,
'number' => $phoneNumber?->normalized_number,
'raw_number' => $phoneNumber?->raw_number,
'label' => $phoneNumber?->label,
'selection' => $selection,
], $extra);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Services\Sms;
class OvhShortCodeMessage
{
public function prepare(string $message): string
{
// Keep visible labels of Markdown/HTML links, but never their target.
$message = preg_replace('~\[([^\]\r\n]*)\]\(https?://[^\s)]+\)~iu', '$1', $message) ?? $message;
$message = preg_replace('~<a\b[^>]*>(.*?)</a>~isu', '$1', $message) ?? $message;
$message = preg_replace('~https?://[^\s<>"\']+|(?<![\pL\pN_@])www\.[^\s<>"\']+~iu', '', $message) ?? $message;
// Also remove bare domain links, without eating email addresses or dates.
$message = preg_replace('~(?<![\pL\pN_@.-])(?:[\pL\pN](?:[\pL\pN-]*[\pL\pN])?\.)+[\pL]{2,63}(?::\d+)?(?:[/\?#][^\s<>"\']*)?(?![\pL\pN_@-])~iu', '', $message) ?? $message;
$message = preg_replace('/[ \t]+/u', ' ', $message) ?? $message;
$message = preg_replace('/ *\R */u', "\n", $message) ?? $message;
$message = preg_replace('/\n{3,}/', "\n\n", $message) ?? $message;
return trim($message);
}
}
+256
View File
@@ -0,0 +1,256 @@
<?php
namespace App\Services\Sms;
use App\Contracts\Sms\SmsProviderInterface;
use App\Models\SmsCampaign;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
class OvhSmsProvider implements SmsProviderInterface
{
private ?int $serverTimestamp = null;
private int $timestampFetchedAt = 0;
public function __construct(private readonly ClientInterface $client) {}
/**
* @param array<int, array<string, mixed>> $recipients
*/
public function send(SmsCampaign $campaign, array $recipients): SmsSendResult
{
$payload = $this->payload($campaign, $recipients);
$serviceName = $this->serviceName();
$path = '/sms/'.rawurlencode($serviceName).'/jobs';
// Keep the exact request even if the process loses OVH's response.
if ($campaign->exists) {
$campaign->update([
'provider_service_name' => $serviceName,
'request_payload' => $payload,
'message' => $payload['message'],
]);
}
$response = $this->request('POST', $path, $payload);
if (! isset($response['ids']) || ! is_array($response['ids'])
|| count($response['ids']) + count($this->stringList($response['invalidReceivers'] ?? [])) < count($recipients)) {
throw new SmsProviderException('Reponse OVH incomplete : envoi a verifier.', $response, outcomeUnknown: true);
}
return new SmsSendResult(
serviceName: $serviceName,
providerJobId: $this->stringValue($response['id'] ?? $response['jobId'] ?? null),
requestPayload: $payload,
responsePayload: $response,
providerMessageIds: $this->stringList($response['ids'] ?? []),
failedNumbers: $this->stringList($response['invalidReceivers'] ?? []),
);
}
/** @return array<int, array<string, mixed>> */
public function outgoing(SmsCampaign $campaign): array
{
if (! $campaign->provider_tag) {
throw new SmsProviderException('Verification impossible sans reference de campagne OVH.');
}
$path = '/sms/'.rawurlencode($campaign->provider_service_name ?: $this->serviceName()).'/outgoing';
$ids = $this->request('GET', $path.'?'.http_build_query(['tag' => $campaign->provider_tag]));
$messages = [];
foreach ($ids as $id) {
$messages[] = $this->request('GET', $path.'/'.rawurlencode((string) $id));
}
return $messages;
}
private function serviceName(): string
{
$configured = trim((string) config('relais_sms.ovh.sms_service_name', ''));
if ($configured !== '') {
return $configured;
}
$services = $this->request('GET', '/sms');
$service = $services[0] ?? null;
if (! is_string($service) || $service === '') {
throw new SmsProviderException('Aucun service SMS OVH disponible pour ces identifiants.', [
'services' => $services,
]);
}
return $service;
}
/**
* @param array<int, array<string, mixed>> $recipients
* @return array<string, mixed>
*/
private function payload(SmsCampaign $campaign, array $recipients): array
{
$shortCode = (bool) config('relais_sms.ovh.sms_short_code');
$sender = trim((string) config('relais_sms.ovh.sms_sender', ''));
if ($shortCode && $sender !== '') {
throw new SmsProviderException('OVH_SMS_SHORT_CODE=true est incompatible avec OVH_SMS_SENDER.');
}
if (! $shortCode && $sender === '') {
throw new SmsProviderException('Configurer OVH_SMS_SENDER pour utiliser OVH_SMS_SHORT_CODE=false.');
}
$message = $shortCode ? (new OvhShortCodeMessage)->prepare($campaign->message) : $campaign->message;
if (trim($message) === '') {
throw new SmsProviderException('Le SMS est vide apres retrait des liens interdits par OVH en numero court.');
}
$payload = [
'message' => $message,
'receivers' => array_values(array_map(
fn (array $recipient): string => (string) $recipient['number'],
$recipients,
)),
'noStopClause' => (bool) config('relais_sms.ovh.sms_no_stop_clause'),
'tag' => $campaign->provider_tag,
];
if ($sender !== '') {
$payload['sender'] = $sender;
} elseif ($shortCode) {
$payload['senderForResponse'] = true;
}
return $payload;
}
/**
* @param array<string, mixed>|null $payload
* @return array<string, mixed>|array<int, mixed>
*/
private function request(string $method, string $path, ?array $payload = null): array
{
$body = $payload === null ? '' : json_encode($payload, JSON_THROW_ON_ERROR);
$url = $this->baseUrl().$path;
$timestamp = $this->timestamp();
try {
$response = $this->client->request($method, $url, [
'headers' => [
'Content-Type' => 'application/json',
'X-Ovh-Application' => $this->requiredConfig('application_key'),
'X-Ovh-Consumer' => $this->requiredConfig('consumer_key'),
'X-Ovh-Signature' => $this->signature($method, $url, $body, $timestamp),
'X-Ovh-Timestamp' => (string) $timestamp,
],
'body' => $body,
'timeout' => $method === 'POST'
? (float) config('relais_sms.ovh.send_timeout', 60)
: (float) config('relais_sms.ovh.timeout', 20),
'connect_timeout' => 10,
'allow_redirects' => false,
]);
} catch (RequestException $exception) {
$responsePayload = $this->decode((string) $exception->getResponse()?->getBody());
$message = $responsePayload['message'] ?? $exception->getMessage();
throw new SmsProviderException((string) $message, $responsePayload,
outcomeUnknown: $method === 'POST' && ($exception->getResponse() === null || $exception->getResponse()->getStatusCode() >= 500));
} catch (GuzzleException $exception) {
throw new SmsProviderException($exception->getMessage(), outcomeUnknown: $method === 'POST');
}
return $this->decode((string) $response->getBody());
}
private function timestamp(): int
{
if ($this->serverTimestamp !== null) {
return $this->serverTimestamp + time() - $this->timestampFetchedAt;
}
try {
$response = $this->client->request('GET', $this->baseUrl().'/auth/time', [
'timeout' => (float) config('relais_sms.ovh.timeout', 20),
]);
$this->timestampFetchedAt = time();
return $this->serverTimestamp = (int) trim((string) $response->getBody());
} catch (GuzzleException) {
return time();
}
}
private function signature(string $method, string $url, string $body, int $timestamp): string
{
return '$1$'.sha1(implode('+', [
$this->requiredConfig('application_secret'),
$this->requiredConfig('consumer_key'),
strtoupper($method),
$url,
$body,
(string) $timestamp,
]));
}
private function baseUrl(): string
{
return match ((string) config('relais_sms.ovh.endpoint', 'ovh-eu')) {
'ovh-ca' => 'https://ca.api.ovh.com/1.0',
'ovh-eu' => 'https://eu.api.ovh.com/1.0',
default => throw new SmsProviderException('Endpoint OVH non pris en charge : utiliser ovh-eu ou ovh-ca.'),
};
}
private function requiredConfig(string $key): string
{
$value = trim((string) config('relais_sms.ovh.'.$key, ''));
if ($value === '') {
throw new SmsProviderException('Configuration OVH incomplete : '.$key.'.');
}
return $value;
}
/**
* @return array<string, mixed>|array<int, mixed>
*/
private function decode(string $body): array
{
if (trim($body) === '') {
return [];
}
$decoded = json_decode($body, true);
return is_array($decoded) ? $decoded : [];
}
private function stringValue(mixed $value): ?string
{
if ($value === null || $value === '') {
return null;
}
return (string) $value;
}
/**
* @return array<int, string>
*/
private function stringList(mixed $values): array
{
if (! is_array($values)) {
return [];
}
return array_values(array_map('strval', $values));
}
}
@@ -0,0 +1,99 @@
<?php
namespace App\Services\Sms;
use App\Models\CalendarReminder;
use App\Models\SmsCampaign;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class SmsCampaignReconciler
{
public function __construct(private readonly OvhSmsProvider $provider) {}
public function reconcile(SmsCampaign $campaign): SmsCampaign
{
try {
$messages = $this->provider->outgoing($campaign);
} catch (SmsProviderException $exception) {
Log::warning('SMS campaign verification unavailable.', [
'sms_campaign_id' => $campaign->id,
'reason' => $exception->getMessage(),
]);
return $campaign;
}
return $this->applyOutgoing($campaign, $messages);
}
/** @param array<int, array<string, mixed>> $messages */
public function applyOutgoing(SmsCampaign $campaign, array $messages): SmsCampaign
{
return DB::transaction(function () use ($campaign, $messages): SmsCampaign {
$campaign = SmsCampaign::query()->lockForUpdate()->findOrFail($campaign->id);
if (! in_array($campaign->status, ['uncertain', 'sending'], true)) {
return $campaign;
}
$byNumber = [];
foreach ($messages as $message) {
if (($message['tag'] ?? null) !== $campaign->provider_tag
|| ($message['message'] ?? null) !== $campaign->message
|| empty($message['id']) || empty($message['receiver'])) {
continue;
}
$byNumber[(string) $message['receiver']] = $message;
}
foreach ($campaign->deliveries()->whereIn('status', ['uncertain', 'queued'])->get() as $delivery) {
$message = $byNumber[$delivery->number] ?? null;
if ($message === null) {
$delivery->update(['status' => 'uncertain']);
continue;
}
// "sent" records acceptance by OVH, not delivery to the handset.
$delivery->update([
'status' => 'sent',
'provider_message_id' => (string) $message['id'],
'provider_response' => $message,
'error_message' => null,
'sent_at' => $message['sentAt'] ?? $message['creationDatetime'] ?? now(),
]);
}
$sentCount = $campaign->deliveries()->where('status', 'sent')->count();
$failedCount = $campaign->deliveries()->where('status', 'failed')->count();
$unconfirmed = $campaign->deliveries()->whereIn('status', ['uncertain', 'queued'])->exists();
$status = $unconfirmed ? 'uncertain' : ($failedCount > 0 ? ($sentCount > 0 ? 'partial' : 'failed') : 'sent');
$campaign->update([
'status' => $status,
'sent_count' => $sentCount,
'failed_count' => $failedCount,
'sent_at' => $campaign->deliveries()->where('status', 'sent')->min('sent_at'),
'response_payload' => ['verification' => 'OVH outgoing history', 'confirmed_recipients' => $sentCount],
'error_message' => $unconfirmed
? 'Certains envois restent a verifier chez OVH. Aucun renvoi automatique ; ne pas renvoyer cette campagne.'
: null,
]);
CalendarReminder::query()->where('sms_campaign_id', $campaign->id)->where('status', 'uncertain')->update([
'status' => $status === 'uncertain' ? 'uncertain' : ($sentCount > 0 ? 'sent' : 'failed'),
'last_error' => $campaign->error_message,
'sent_at' => $campaign->sent_at,
]);
Log::info('SMS campaign verified against OVH history.', [
'sms_campaign_id' => $campaign->id,
'sent_count' => $sentCount,
'status' => $status,
]);
return $campaign->fresh(['deliveries', 'user']);
});
}
}
+260
View File
@@ -0,0 +1,260 @@
<?php
namespace App\Services\Sms;
use App\Contracts\Sms\SmsProviderInterface;
use App\Models\ContactGroup;
use App\Models\SmsCampaign;
use App\Models\SmsDelivery;
use App\Models\User;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class SmsCampaignSender
{
public function __construct(private readonly SmsProviderInterface $provider) {}
/**
* @param array<int, array<string, mixed>> $recipients
* @param array<int, int|string> $selectedContactIds
* @param array<int, int|string> $selectedGroupIds
*/
public function send(
User $user,
string $message,
array $recipients,
array $selectedContactIds = [],
array $selectedGroupIds = [],
): SmsCampaign {
$campaign = $this->createCampaign($user, $message, $recipients, $selectedContactIds, $selectedGroupIds, 'sending');
return $this->sendExistingCampaign($campaign, $recipients);
}
/**
* @param array<int, array<string, mixed>> $recipients
* @param array<int, int|string> $selectedContactIds
* @param array<int, int|string> $selectedGroupIds
*/
public function schedule(
User $user,
string $message,
array $recipients,
array $selectedContactIds,
array $selectedGroupIds,
CarbonInterface $scheduledAt,
): SmsCampaign {
return $this->createCampaign($user, $message, $recipients, $selectedContactIds, $selectedGroupIds, 'scheduled', $scheduledAt);
}
public function sendScheduled(SmsCampaign $campaign): ?SmsCampaign
{
$campaign = DB::transaction(function () use ($campaign): ?SmsCampaign {
$fresh = SmsCampaign::query()
->whereKey($campaign->id)
->lockForUpdate()
->first();
if (! $fresh || $fresh->status !== 'scheduled') {
return null;
}
$fresh->update(['status' => 'sending']);
Log::info('SMS campaign status changed from scheduled to sending.', [
'sms_campaign_id' => $fresh->id,
'scheduled_at' => $fresh->scheduled_at?->toIso8601String(),
]);
return $fresh->fresh(['deliveries', 'user']);
});
if ($campaign === null) {
return null;
}
return $this->sendExistingCampaign($campaign, $this->recipientsFromDeliveries($campaign));
}
/**
* @param array<int, array<string, mixed>> $recipients
* @param array<int, int|string> $selectedContactIds
* @param array<int, int|string> $selectedGroupIds
*/
private function createCampaign(
User $user,
string $message,
array $recipients,
array $selectedContactIds,
array $selectedGroupIds,
string $status,
?CarbonInterface $scheduledAt = null,
): SmsCampaign {
$selectedContactIds = $this->cleanIds($selectedContactIds);
$selectedGroupIds = $this->cleanIds($selectedGroupIds);
$selectedGroupNames = ContactGroup::query()
->whereKey($selectedGroupIds)
->orderBy('name')
->pluck('name')
->values()
->all();
return $this->createResolvedCampaign(
$user,
$message,
$recipients,
$selectedContactIds,
$selectedGroupIds,
$selectedGroupNames,
$status,
$scheduledAt,
);
}
/**
* @param array<int, array<string, mixed>> $recipients
* @param array<int, int> $selectedContactIds
* @param array<int, int> $selectedGroupIds
* @param array<int, string> $selectedGroupNames
*/
private function createResolvedCampaign(
User $user,
string $message,
array $recipients,
array $selectedContactIds,
array $selectedGroupIds,
array $selectedGroupNames,
string $status,
?CarbonInterface $scheduledAt,
): SmsCampaign {
return DB::transaction(function () use ($user, $message, $recipients, $selectedContactIds, $selectedGroupIds, $selectedGroupNames, $status, $scheduledAt): SmsCampaign {
$attributes = [
'user_id' => $user->id,
'provider' => (string) config('relais_sms.default_settings.active_sms_provider', 'ovh'),
'status' => $status,
'message' => $message,
'recipients_count' => count($recipients),
'selected_contact_ids' => $selectedContactIds,
'selected_group_ids' => $selectedGroupIds,
'selected_group_names' => $selectedGroupNames,
];
if ($scheduledAt !== null) {
$attributes['scheduled_at'] = $scheduledAt;
}
$campaign = SmsCampaign::query()->create($attributes);
$campaign->update(['provider_tag' => 'relais-sms-campaign-'.$campaign->id]);
foreach ($recipients as $recipient) {
$campaign->deliveries()->create([
'contact_id' => $recipient['contact_id'] ?? null,
'contact_phone_number_id' => $recipient['phone_number_id'] ?? null,
'contact_name' => (string) $recipient['contact_name'],
'number' => (string) $recipient['number'],
'status' => 'queued',
]);
}
return $campaign;
});
}
/**
* @param array<int, array<string, mixed>> $recipients
*/
private function sendExistingCampaign(SmsCampaign $campaign, array $recipients): SmsCampaign
{
try {
$result = $this->provider->send($campaign, $recipients);
} catch (SmsProviderException $exception) {
$status = $exception->outcomeUnknown ? 'uncertain' : 'failed';
$message = $exception->outcomeUnknown
? 'OVH n a pas confirme la reponse. Les SMS peuvent avoir ete envoyes. Verification automatique au prochain passage du cron ; ne pas renvoyer cette campagne.'
: $exception->getMessage();
DB::transaction(function () use ($campaign, $exception, $status, $message, $recipients): void {
$campaign->deliveries()->update(['status' => $status, 'error_message' => $message]);
$campaign->update([
'status' => $status,
'failed_count' => $exception->outcomeUnknown ? 0 : count($recipients),
'response_payload' => $exception->responsePayload,
'error_message' => $message,
]);
});
Log::warning('SMS provider request failed.', [
'sms_campaign_id' => $campaign->id,
'outcome_unknown' => $exception->outcomeUnknown,
'reason' => $exception->getMessage(),
]);
return $campaign->fresh(['deliveries', 'user']);
}
$failedNumbers = array_flip($result->failedNumbers);
$sentCount = 0;
$failedCount = 0;
foreach ($campaign->deliveries()->orderBy('id')->get()->values() as $index => $delivery) {
$failed = isset($failedNumbers[$delivery->number]);
$delivery->update([
'status' => $failed ? 'failed' : 'sent',
'provider_message_id' => $result->providerMessageIds[$index] ?? null,
'provider_response' => $result->responsePayload,
'error_message' => $failed ? 'Numero refuse par OVH.' : null,
'sent_at' => $failed ? null : now(),
]);
$failed ? $failedCount++ : $sentCount++;
}
$campaign->update([
'status' => $failedCount > 0 ? ($sentCount > 0 ? 'partial' : 'failed') : 'sent',
'sent_count' => $sentCount,
'failed_count' => $failedCount,
'provider_service_name' => $result->serviceName,
'provider_job_id' => $result->providerJobId,
'message' => (string) ($result->requestPayload['message'] ?? $campaign->message),
'request_payload' => $result->requestPayload,
'response_payload' => $result->responsePayload,
'sent_at' => $sentCount > 0 ? now() : null,
]);
return $campaign->fresh(['deliveries', 'user']);
}
/**
* @return array<int, array<string, mixed>>
*/
private function recipientsFromDeliveries(SmsCampaign $campaign): array
{
return $campaign->deliveries()
->orderBy('id')
->get()
->map(fn (SmsDelivery $delivery): array => [
'contact_id' => $delivery->contact_id,
'phone_number_id' => $delivery->contact_phone_number_id,
'contact_name' => $delivery->contact_name,
'number' => $delivery->number,
])
->values()
->all();
}
/**
* @param array<int, int|string> $ids
* @return array<int, int>
*/
private function cleanIds(array $ids): array
{
return collect($ids)
->map(fn (int|string $id): int => (int) $id)
->filter(fn (int $id): bool => $id > 0)
->unique()
->values()
->all();
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Services\Sms;
use App\Models\AppSetting;
class SmsMessageComposer
{
/**
* @return array{header: string, footer: string}
*/
public function settings(): array
{
return [
'header' => AppSetting::string('sms_message_header'),
'footer' => AppSetting::string('sms_message_footer'),
];
}
public function compose(string $body, bool $includeHeader = true, bool $includeFooter = true): string
{
$settings = $this->settings();
$parts = [];
if ($includeHeader && $settings['header'] !== '') {
$parts[] = $settings['header'];
}
if (trim($body) !== '') {
$parts[] = trim($body);
}
if ($includeFooter && $settings['footer'] !== '') {
$parts[] = $settings['footer'];
}
return implode("\n", $parts);
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
namespace App\Services\Sms;
class SmsMessageLength
{
private const GSM_BASIC = "@\u{00A3}$\u{00A5}\u{00E8}\u{00E9}\u{00F9}\u{00EC}\u{00F2}\u{00C7}\n\u{00D8}\u{00F8}\r\u{00C5}\u{00E5}\u{0394}_\u{03A6}\u{0393}\u{039B}\u{03A9}\u{03A0}\u{03A8}\u{03A3}\u{0398}\u{039E}\u{00C6}\u{00E6}\u{00DF}\u{00C9} !\"#\u{00A4}%&'()*+,-./0123456789:;<=>?\u{00A1}ABCDEFGHIJKLMNOPQRSTUVWXYZ\u{00C4}\u{00D6}\u{00D1}\u{00DC}\u{00A7}\u{00BF}abcdefghijklmnopqrstuvwxyz\u{00E4}\u{00F6}\u{00F1}\u{00FC}\u{00E0}";
private const GSM_EXTENDED = "^{}\\[~]|\u{20AC}";
public function fitsInOneSms(string $message): bool
{
return $this->units($message) <= $this->singleSmsCapacity($message);
}
public function units(string $message): int
{
if (! $this->usesGsmAlphabet($message)) {
return intdiv(strlen(mb_convert_encoding($message, 'UTF-16BE', 'UTF-8')), 2);
}
return array_sum(array_map(
fn (string $character): int => str_contains(self::GSM_EXTENDED, $character) ? 2 : 1,
mb_str_split($message),
));
}
public function singleSmsCapacity(string $message): int
{
return $this->usesGsmAlphabet($message) ? 160 : 70;
}
/**
* Truncate a value so that prefix + value + suffix still fits in one SMS.
*/
public function truncateBetween(string $prefix, string $value, string $suffix, string $marker = '[...]'): string
{
if ($this->fitsInOneSms($prefix.$value.$suffix)) {
return $value;
}
$truncated = '';
foreach (mb_str_split($value) as $character) {
if (! $this->fitsInOneSms($prefix.$truncated.$character.$marker.$suffix)) {
break;
}
$truncated .= $character;
}
if ($this->fitsInOneSms($prefix.$truncated.$marker.$suffix)) {
return rtrim($truncated).$marker;
}
return rtrim($truncated);
}
private function usesGsmAlphabet(string $message): bool
{
foreach (mb_str_split($message) as $character) {
if (! str_contains(self::GSM_BASIC, $character) && ! str_contains(self::GSM_EXTENDED, $character)) {
return false;
}
}
return true;
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Services\Sms;
use RuntimeException;
class SmsProviderException extends RuntimeException
{
/**
* @param array<string, mixed>|null $responsePayload
*/
public function __construct(
string $message,
public readonly ?array $responsePayload = null,
public readonly bool $outcomeUnknown = false,
) {
parent::__construct($message);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Services\Sms;
class SmsSendResult
{
/**
* @param array<string, mixed> $requestPayload
* @param array<string, mixed> $responsePayload
* @param array<int, string> $providerMessageIds
* @param array<int, string> $failedNumbers
*/
public function __construct(
public readonly string $serviceName,
public readonly ?string $providerJobId,
public readonly array $requestPayload,
public readonly array $responsePayload,
public readonly array $providerMessageIds = [],
public readonly array $failedNumbers = [],
) {}
}