PushNotificationService.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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\CloudMessage;
  10. use Kreait\Firebase\Messaging\Notification;
  11. use Throwable;
  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()->withNotification(
  30. Notification::create($notification->title(), $notification->body())
  31. );
  32. $report = $this->messaging->sendMulticast($message, $tokens);
  33. $this->deactivateInvalidTokens($report->invalidTokens());
  34. if ($report->successes()->count() > 0) {
  35. $this->log($user, $notification);
  36. }
  37. }
  38. /**
  39. * Envia para uma coleção de usuários, respeitando cooldowns.
  40. * Usuários sem tokens ativos são ignorados silenciosamente.
  41. */
  42. public function sendToUsers(Collection $users, BasePushNotification $notification): void
  43. {
  44. foreach ($users as $user) {
  45. $this->sendToUser($user, $notification);
  46. }
  47. }
  48. private function log(User $user, BasePushNotification $notification): void
  49. {
  50. PushNotificationLog::create([
  51. 'label' => $notification->label(),
  52. 'user_id' => $user->id,
  53. 'target' => $notification->target()->value,
  54. 'category' => $notification->category()->value,
  55. 'sent_at' => now(),
  56. ]);
  57. }
  58. private function deactivateInvalidTokens(array $tokens): void
  59. {
  60. if (empty($tokens)) {
  61. return;
  62. }
  63. DeviceToken::whereIn('token', $tokens)->update(['active' => false]);
  64. }
  65. }