feat: expo channel

This commit is contained in:
Leon Morival 2026-05-16 15:53:39 +02:00
parent 276978128d
commit d9e80f7603
12 changed files with 448 additions and 16 deletions

View File

@ -57,6 +57,8 @@ MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
EXPO_ACCESS_TOKEN=
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1

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,
]);
}
}
}

View File

@ -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
{

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

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 [
//
];
}
}

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'),
]);
}

View File

@ -22,6 +22,10 @@ return [
'key' => env('RESEND_API_KEY'),
],
'expo' => [
'access_token' => env('EXPO_ACCESS_TOKEN'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),

View File

@ -14,7 +14,7 @@ return new class extends Migration
Schema::create('device_tokens', function (Blueprint $table) {
$table->id();
$table->foreignUlid('user_id')->constrained()->cascadeOnDelete();
$table->string('expo_push_token');
$table->string('expo_push_token')->unique();
$table->string('platform')->nullable();
$table->timestampsTz();
});

View File

@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('notifications', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('type');
$table->ulidMorphs('notifiable');
$table->text('data');
$table->timestamp('read_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('notifications');
}
};

View File

@ -23,7 +23,8 @@
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="BROADCAST_CONNECTION" value="null"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_DATABASE" value="testing"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>

View File

@ -19,6 +19,7 @@ Route::prefix('auth')->group(function (): void {
Route::middleware('auth:sanctum')->group(function (): void {
Route::post('device-tokens', [DeviceTokenController::class, 'store']);
Route::delete('device-tokens', [DeviceTokenController::class, 'destroy']);
Route::get('test-notifs', [DeviceTokenController::class, 'notifs']);
});
Route::middleware('auth:sanctum')->apiResource('meal-posts', MealPostController::class);

View File

@ -0,0 +1,157 @@
<?php
use App\Broadcasting\ExpoPushChannel;
use App\Models\DeviceToken;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Http;
uses(RefreshDatabase::class);
it('sends expo push notifications to every registered device token', function () {
Http::fake([
'https://exp.host/*' => Http::response([
'data' => [
['status' => 'ok', 'id' => 'ticket-one'],
['status' => 'ok', 'id' => 'ticket-two'],
],
]),
]);
$user = User::factory()->create();
$user->deviceTokens()->create([
'expo_push_token' => 'ExponentPushToken[first]',
'platform' => 'ios',
]);
$user->deviceTokens()->create([
'expo_push_token' => 'ExponentPushToken[second]',
'platform' => 'android',
]);
(new ExpoPushChannel)->send($user, expoPushTestNotification());
Http::assertSent(fn (Request $request) => $request->url() === 'https://exp.host/--/api/v2/push/send'
&& $request->data() === [
[
'to' => 'ExponentPushToken[first]',
'title' => 'Nouveau repas',
'body' => 'Un ami vient de publier son repas.',
'data' => ['meal_post_id' => 123],
],
[
'to' => 'ExponentPushToken[second]',
'title' => 'Nouveau repas',
'body' => 'Un ami vient de publier son repas.',
'data' => ['meal_post_id' => 123],
],
]);
});
it('can be used from a notification via the expo channel alias', function () {
Http::fake([
'https://exp.host/*' => Http::response([
'data' => [
['status' => 'ok', 'id' => 'ticket-one'],
],
]),
]);
$user = User::factory()->create();
$user->deviceTokens()->create([
'expo_push_token' => 'ExponentPushToken[first]',
'platform' => 'ios',
]);
$user->notify(new class extends Notification
{
public function via(object $notifiable): array
{
return ['expo'];
}
public function toExpoPush(object $notifiable): array
{
return [
'title' => 'Nouveau repas',
'body' => 'Un ami vient de publier son repas.',
'data' => ['meal_post_id' => 123],
];
}
});
Http::assertSent(fn (Request $request) => $request->data()[0]['to'] === 'ExponentPushToken[first]');
});
it('removes device tokens rejected as not registered by expo', function () {
Http::fake([
'https://exp.host/*' => Http::response([
'data' => [
[
'status' => 'error',
'message' => '"ExponentPushToken[invalid]" is not a registered push notification recipient',
'details' => ['error' => 'DeviceNotRegistered'],
],
['status' => 'ok', 'id' => 'ticket-two'],
],
]),
]);
$user = User::factory()->create();
$invalidToken = $user->deviceTokens()->create([
'expo_push_token' => 'ExponentPushToken[invalid]',
'platform' => 'ios',
]);
$validToken = $user->deviceTokens()->create([
'expo_push_token' => 'ExponentPushToken[valid]',
'platform' => 'android',
]);
(new ExpoPushChannel)->send($user, expoPushTestNotification());
expect(DeviceToken::query()->whereKey($invalidToken->getKey())->exists())->toBeFalse()
->and(DeviceToken::query()->whereKey($validToken->getKey())->exists())->toBeTrue();
});
it('chunks expo push notifications into requests of one hundred messages', function () {
Http::fake([
'https://exp.host/*' => Http::response(['data' => []]),
]);
$user = User::factory()->create();
foreach (range(1, 101) as $number) {
$user->deviceTokens()->create([
'expo_push_token' => sprintf('ExponentPushToken[%03d]', $number),
'platform' => 'ios',
]);
}
(new ExpoPushChannel)->send($user, expoPushTestNotification());
Http::assertSentCount(2);
$requests = Http::recorded()
->map(fn (array $pair) => $pair[0]->data())
->values();
expect($requests[0])->toHaveCount(100)
->and($requests[1])->toHaveCount(1)
->and($requests[1][0]['to'])->toBe('ExponentPushToken[101]');
});
function expoPushTestNotification(): Notification
{
return new class extends Notification
{
public function toExpoPush(object $notifiable): array
{
return [
'title' => 'Nouveau repas',
'body' => 'Un ami vient de publier son repas.',
'data' => ['meal_post_id' => 123],
];
}
};
}