Example #1
0
        public async Task sendNotification(RequestedItem requestedItem,
                                           NotificationType notificationType,
                                           string notificationTitle,
                                           string notificationMessage,
                                           bool dataOnly)
        {
            var devices = await _beachBuddyRepository.GetDevices();

            Dictionary <string, string> data;

            if (dataOnly)
            {
                data = new Dictionary <string, string>
                {
                    { "notificationType", notificationType.ToString() },
                    { "updateOnly", "true" }
                };
            }
            else
            {
                data = new Dictionary <string, string>
                {
                    { "notificationType", notificationType.ToString() },
                    { "updateOnly", "false" },
                    { "itemId", $"{requestedItem.Id}" },
                    { "name", $"{requestedItem.Name}" },
                    { "count", $"{requestedItem.Count}" },
                    { "sentByUserId", $"{requestedItem.RequestedByUserId}" }
                };
            }

            var deviceList = devices.ToList();
            var results    = await SendFcmNotification(deviceList, notificationTitle, notificationMessage, dataOnly, data);

            for (var i = 0; i < results.Count; i++)
            {
                var response = results[i];
                var device   = deviceList[i];
                if (response.IsSuccess)
                {
                    _logger.LogDebug($"Message was sent!");
                    // Woohoo!
                }
                else
                {
                    _logger.LogWarning(response.Exception.InnerException,
                                       $"Error sending notification to device {device.DeviceToken}");
                    if (response.Exception.MessagingErrorCode.HasValue &&
                        response.Exception.MessagingErrorCode == MessagingErrorCode.Unregistered)
                    {
                        // the token has been unregistered, must delete the device record
                        _beachBuddyRepository.DeleteDevice(device);
                        await _beachBuddyRepository.Save();

                        _logger.LogDebug($"Device {device.DeviceToken} has been unregistered");
                    }
                }
            }
        }