PushNotificationService.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. private function log(User $user, BasePushNotification $notification): void
  52. {
  53. PushNotificationLog::create([
  54. 'label' => $notification->label(),
  55. 'user_id' => $user->id,
  56. 'target' => $notification->target()->value,
  57. 'category' => $notification->category()->value,
  58. 'sent_at' => now(),
  59. ]);
  60. }
  61. private function deactivateInvalidTokens(array $tokens): void
  62. {
  63. if (empty($tokens)) {
  64. return;
  65. }
  66. DeviceToken::whereIn('token', $tokens)->update(['active' => false]);
  67. }
  68. }