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
+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 = [],
) {}
}