feat: expo channel

This commit is contained in:
2026-05-16 15:53:39 +02:00
parent 276978128d
commit d9e80f7603
12 changed files with 448 additions and 16 deletions
+158
View File
@@ -0,0 +1,158 @@
<?php
namespace App\Broadcasting;
use App\Models\DeviceToken;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use InvalidArgumentException;
class ExpoPushChannel
{
private const EXPO_PUSH_ENDPOINT = 'https://exp.host/--/api/v2/push/send';
private const MAX_MESSAGES_PER_REQUEST = 100;
public function send($notifiable, Notification $notification): void
{
$tokens = $this->tokensFor($notifiable, $notification);
if ($tokens->isEmpty()) {
return;
}
$payload = $this->payloadFor($notifiable, $notification);
$tokens
->chunk(self::MAX_MESSAGES_PER_REQUEST)
->each(fn (Collection $chunk) => $this->sendChunk($chunk, $payload));
}
private function tokensFor($notifiable, Notification $notification): Collection
{
$tokens = method_exists($notifiable, 'routeNotificationFor')
? $notifiable->routeNotificationFor('expoPush', $notification)
: null;
return collect($tokens)
->filter(fn ($token) => is_string($token) && $token !== '')
->unique()
->values();
}
private function payloadFor($notifiable, Notification $notification): array
{
if (! method_exists($notification, 'toExpoPush')) {
throw new InvalidArgumentException(sprintf(
'Notification [%s] is missing a toExpoPush($notifiable) method.',
$notification::class,
));
}
$payload = $notification->toExpoPush($notifiable);
if ($payload instanceof Arrayable) {
$payload = $payload->toArray();
}
if (! is_array($payload)) {
throw new InvalidArgumentException(sprintf(
'Notification [%s] must return an array or Arrayable from toExpoPush($notifiable).',
$notification::class,
));
}
return collect($payload)
->except('to')
->reject(fn ($value) => $value === null)
->all();
}
private function sendChunk(Collection $tokens, array $payload): void
{
$messages = $tokens
->map(fn (string $token) => ['to' => $token] + $payload)
->values()
->all();
try {
$response = Http::acceptJson()
->asJson()
->timeout(10)
->connectTimeout(5)
->when(config('services.expo.access_token'), fn ($request, string $accessToken) => $request->withToken($accessToken))
->retry(
3,
250,
fn ($exception) => $this->shouldRetry($exception),
throw: false,
)
->post(self::EXPO_PUSH_ENDPOINT, $messages);
} catch (ConnectionException $exception) {
Log::warning('Unable to connect to Expo Push API.', [
'exception' => $exception->getMessage(),
'tokens_count' => $tokens->count(),
]);
return;
}
if ($response->failed()) {
Log::warning('Expo Push API rejected a notification request.', [
'status' => $response->status(),
'response' => $response->json(),
'tokens_count' => $tokens->count(),
]);
return;
}
$body = $response->json();
$this->handleTickets(is_array($body) ? $body : null, $tokens);
}
private function shouldRetry($exception): bool
{
if ($exception instanceof ConnectionException) {
return true;
}
if (! $exception instanceof RequestException) {
return false;
}
return $exception->response->status() === 429
|| $exception->response->serverError();
}
private function handleTickets(?array $response, Collection $tokens): void
{
foreach (Arr::get($response, 'data', []) as $index => $ticket) {
if (($ticket['status'] ?? null) !== 'error') {
continue;
}
$token = $tokens->values()->get($index);
$error = Arr::get($ticket, 'details.error');
if ($error === 'DeviceNotRegistered' && is_string($token)) {
DeviceToken::query()
->where('expo_push_token', $token)
->delete();
}
Log::warning('Expo Push API rejected a notification.', [
'error' => $error,
'message' => $ticket['message'] ?? null,
'token' => $token,
]);
}
}
}
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
use App\Http\Requests\DeviceTokenRequest;
use App\Models\DeviceToken;
use App\Notifications\TestNotification;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
@@ -33,6 +34,14 @@ class DeviceTokenController extends Controller
],
], $deviceToken->wasRecentlyCreated ? 201 : 200);
}
public function notifs(): JsonResponse
{
auth()->user()->notify(new TestNotification());
return response()->json([
'message' => 'Notification envoyée'
]);
}
public function destroy(Request $request): Response
{
+11 -4
View File
@@ -15,7 +15,7 @@ use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable implements FilamentUser
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable, HasApiTokens, HasUlids;
use HasApiTokens, HasFactory, HasUlids, Notifiable;
/**
* The attributes that are mass assignable.
@@ -27,7 +27,7 @@ class User extends Authenticatable implements FilamentUser
'email',
'password',
'avatar_url',
'bio'
'bio',
];
/**
@@ -53,16 +53,23 @@ class User extends Authenticatable implements FilamentUser
];
}
public function deviceTokens(): HasMany
{
return $this->hasMany(DeviceToken::class);
}
public function routeNotificationForExpoPush(): array
{
return $this->deviceTokens()
->orderBy('id')
->pluck('expo_push_token')
->all();
}
public function isAdmin()
{
return true;
// return $this->role === 'admin';
// return $this->role === 'admin';
}
public function canAccessPanel(Panel $panel): bool
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class TestNotification extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*/
public function __construct()
{
//
}
/**
* Get the notification's delivery channels.
*
* @return array<int, string>
*/
public function via(object $notifiable): array
{
return ['expo'];
}
/**
* Get the mail representation of the notification.
*/
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
public function toExpoPush($notifiable)
{
return [
'title' => 'Test',
'body' => 'Notification depuis Laravel API',
'data' => ['test' => true],
];
}
/**
* Get the array representation of the notification.
*
* @return array<string, mixed>
*/
public function toArray(object $notifiable): array
{
return [
//
];
}
}
+10 -10
View File
@@ -2,23 +2,21 @@
namespace App\Providers;
use Dedoc\Scramble\Scramble;
use Dedoc\Scramble\Support\Generator\OpenApi;
use Dedoc\Scramble\Support\Generator\SecurityScheme;
use App\Broadcasting\ExpoPushChannel;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
use Meilisearch\Meilisearch;
use Spatie\Health\Checks\Checks\DatabaseCheck;
use Spatie\Health\Checks\Checks\DebugModeCheck;
use Spatie\Health\Checks\Checks\EnvironmentCheck;
use Spatie\Health\Checks\Checks\HorizonCheck;
use Spatie\Health\Checks\Checks\MeilisearchCheck;
use Spatie\Health\Checks\Checks\OptimizedAppCheck;
use Spatie\Health\Checks\Checks\RedisCheck;
use Spatie\Health\Checks\Checks\ScheduleCheck;
use Spatie\Health\Checks\Checks\UsedDiskSpaceCheck;
use Spatie\Health\Facades\Health;
use Spatie\Health\Checks\Checks\DatabaseCheck;
use Spatie\Health\Checks\Checks\RedisCheck;
use Spatie\Health\Checks\Checks\HorizonCheck;
use Spatie\Health\Checks\Checks\OptimizedAppCheck;
use Spatie\Health\Checks\Checks\DebugModeCheck;
class AppServiceProvider extends ServiceProvider
{
@@ -39,6 +37,8 @@ class AppServiceProvider extends ServiceProvider
URL::forceScheme('https');
}
Notification::extend('expo', fn ($app) => $app->make(ExpoPushChannel::class));
Gate::define('viewApiDocs', function ($user = null) {
// Option A : Autoriser tout le monde (Attention : la doc sera publique hors local)
return true;
@@ -60,7 +60,7 @@ class AppServiceProvider extends ServiceProvider
EnvironmentCheck::new(),
DebugModeCheck::new(),
MeilisearchCheck::new()
->url('http://meilisearch:7700/health')
->url('http://meilisearch:7700/health'),
]);
}