PushNotificationService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. if (! array_key_exists('push_notifications_enabled', $user->getAttributes())) {
  22. $user = $user->fresh() ?? $user;
  23. }
  24. if (! $user->push_notifications_enabled) {
  25. return;
  26. }
  27. $tokens = DeviceToken::where('user_id', $user->id)
  28. ->where('app_type', $notification->target()->value)
  29. ->where('active', true)
  30. ->pluck('token')
  31. ->toArray();
  32. if (empty($tokens)) {
  33. return;
  34. }
  35. $message = CloudMessage::new()
  36. ->withNotification(
  37. Notification::create(
  38. $notification->title(),
  39. $notification->body()
  40. )
  41. )
  42. ->withAndroidConfig(AndroidConfig::fromArray([
  43. 'notification' => ['channel_id' => 'diaria'],
  44. 'priority' => 'high',
  45. ]));
  46. $report = $this->messaging->sendMulticast($message, $tokens);
  47. $this->deactivateInvalidTokens($report->invalidTokens());
  48. if ($report->successes()->count() > 0) {
  49. $this->log($user, $notification);
  50. }
  51. }
  52. /**
  53. * Envia para uma coleção de usuários, respeitando cooldowns.
  54. * Usuários sem tokens ativos são ignorados silenciosamente.
  55. */
  56. public function sendToUsers(Collection $users, BasePushNotification $notification): void
  57. {
  58. foreach ($users as $user) {
  59. $this->sendToUser($user, $notification);
  60. }
  61. }
  62. //
  63. private function deactivateInvalidTokens(array $tokens): void
  64. {
  65. if (empty($tokens)) {
  66. return;
  67. }
  68. DeviceToken::whereIn('token', $tokens)->update(['active' => false]);
  69. }
  70. private function log(User $user, BasePushNotification $notification): void
  71. {
  72. PushNotificationLog::create([
  73. 'label' => $notification->label(),
  74. 'user_id' => $user->id,
  75. 'target' => $notification->target()->value,
  76. 'category' => $notification->category()->value,
  77. 'sent_at' => now(),
  78. ]);
  79. }
  80. }