diff --git a/Marco.Pms.Services/Service/FirebaseService.cs b/Marco.Pms.Services/Service/FirebaseService.cs index bcaff4d..43b7255 100644 --- a/Marco.Pms.Services/Service/FirebaseService.cs +++ b/Marco.Pms.Services/Service/FirebaseService.cs @@ -137,7 +137,59 @@ namespace Marco.Pms.Services.Service .Where(ft => employeeIds.Contains(ft.EmployeeId) && ft.TenantId == tenantId) .Select(ft => ft.FcmToken).ToListAsync(); - await SendMessageToMultipleDevicesAsync(registrationTokens, notificationFirebase); + var data = new Dictionary() + { + { "Keyword", "Attendance" }, + { "ProjectId", projectId.ToString() }, + { "Action", markType.ToString() } + }; + + await SendMessageToMultipleDevicesWithDataAsync(registrationTokens, notificationFirebase, data); + } + public async Task SendMessageToMultipleDevicesWithDataAsync(List registrationTokens, Notification notificationFirebase, Dictionary data) + { + + try + { + var message = new MulticastMessage() + { + Tokens = registrationTokens, + Data = data, + Notification = notificationFirebase + }; + // Send the multicast message + var response = await FirebaseMessaging.DefaultInstance.SendEachForMulticastAsync(message); + _logger.LogInfo("{SuccessCount} messages were sent successfully.", response.SuccessCount); + + if (response.FailureCount > 0) + { + var failedTokens = new List(); + for (int i = 0; i < response.Responses.Count; i++) + { + if (!response.Responses[i].IsSuccess) + { + failedTokens.Add(registrationTokens[i]); + } + } + _logger.LogInfo("List of tokens that caused failures: " + string.Join(", ", failedTokens)); + } + } + catch (FirebaseMessagingException ex) + { + // Log the specific Firebase error. + _logger.LogError(ex, "Error sending push notification"); + + // Check for specific error codes that indicate an invalid or unregistered token. + if (ex.MessagingErrorCode == MessagingErrorCode.Unregistered || + ex.MessagingErrorCode == MessagingErrorCode.InvalidArgument) + { + _logger.LogWarning("FCM token is invalid and should be deleted from the database"); + + // TODO: Implement the logic here to remove the invalid token from your database. + // Example: await YourTokenService.DeleteTokenAsync(loginDto.DeviceToken); + } + } + } public async Task SendMessageToMultipleDevicesAsync(List registrationTokens, Notification notificationFirebase) {