Publication initiale de RelaisSMS : documentation et sources nettoyees
This commit is contained in:
@@ -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,
|
||||
) {}
|
||||
}
|
||||
@@ -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,
|
||||
) {}
|
||||
}
|
||||
Reference in New Issue
Block a user