PushNotificationService.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Services;
  3. use App\Models\DeviceToken;
  4. use App\Models\PushNotificationLog;
  5. use App\Models\User;
  6. use App\Notifications\Push\BasePushNotification;
  7. use Illuminate\Support\Collection;
  8. use Kreait\Firebase\Contract\Messaging;
  9. use Kreait\Firebase\Messaging\AndroidConfig;
  10. use Kreait\Firebase\Messaging\CloudMessage;
  11. use Kreait\Firebase\Messaging\Notification;
  12. class PushNotificationService
  13. {
  14. public function __construct(private Messaging $messaging) {}
  15. /**
  16. * Envia uma push notification para todos os tokens ativos de um usuário.
  17. * Registra o envio no log e desativa tokens inválidos automaticamente.
  18. */
  19. public function sendToUser(User $user, BasePushNotification $notification): void
  20. {
  21. $tokens = DeviceToken::where('user_id', $user->id)
  22. ->where('app_type', $notification->target()->value)
  23. ->where('active', true)
  24. ->pluck('token')
  25. ->toArray();
  26. if (empty($tokens)) {
  27. return;
  28. }
  29. $message = CloudMessage::new()
  30. ->withNotification(Notification::create($notification->title(), $notification->body()))
  31. ->withAndroidConfig(AndroidConfig::fromArray([
  32. 'notification' => ['channel_id' => 'default'],
  33. 'priority' => 'high',
  34. ]));
  35. $report = $this->messaging->sendMulticast($message, $tokens);
  36. $this->deactivateInvalidTokens($report->invalidTokens());
  37. if ($report->successes()->count() > 0) {
  38. $this->log($user, $notification);
  39. }
  40. }
  41. /**
  42. * Envia para uma coleção de usuários, respeitando cooldowns.
  43. * Usuários sem tokens ativos são ignorados silenciosamente.
  44. */
  45. public function sendToUsers(Collection $users, BasePushNotification $notification): void
  46. {
  47. foreach ($users as $user) {
  48. $this->sendToUser($user, $notification);
  49. }
  50. }
  51. //
  52. private function deactivateInvalidTokens(array $tokens): void
  53. {
  54. if (empty($tokens)) {
  55. return;
  56. }
  57. DeviceToken::whereIn('token', $tokens)->update(['active' => false]);
  58. }
  59. private function log(User $user, BasePushNotification $notification): void
  60. {
  61. PushNotificationLog::create([
  62. 'label' => $notification->label(),
  63. 'user_id' => $user->id,
  64. 'target' => $notification->target()->value,
  65. 'category' => $notification->category()->value,
  66. 'sent_at' => now(),
  67. ]);
  68. }
  69. }