public async Task <IActionResult> SendNotificationMobile(string userId, string message)
        {
            // IActionResult OpmUserProvince = null;
            var mobileObj = _context.UserTokenMobiles
                            .Where(w => w.UserID == userId)
                            .ToArray();

            foreach (var item in mobileObj)
            {
                var p8privateKey = $"MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgpaXr/CZEsUSHeky8aQQ6teO4cDSsLwVq3j7PWdpr6wOgCgYIKoZIzj0DAQehRANCAAQe9meUPmcbinwleRVTxlolByUcfJjX9uxhYie57KxZJZZEfYrM4/U/IAcDu3EiWWBoKYmsVtDMTBGbFTfVCUvo";
                if (item.DeviceType == "ios")
                {
                    using (var apn = new ApnSender(p8privateKey, "7D37LMN3C4", "RVLQ6T4Y33", "com.tot.inspec", ApnServerType.Production))
                    {
                        // await apn.SendAsync(item.Token,message );
                        await apn.SendAsync(new { alert = message }, item.Token);
                    }
                }
                else
                {
                    using (var fcm = new FcmSender("AAAAzLUSLHk:APA91bEPP7_VRyQf7nFxKPTpZ6BYZ_yk7A0sXEWTOo--4i8kykZpmZnxzneKB5jdkRj8hJIPGu7Nfsvtu81YM2bZ3zFGOS8oTV_QGPWMcuUimytm8GOOjA9OT6_4nxLLQ1oPZOEep8Jb", "879211195513"))
                    {
                        await fcm.SendAsync(item.Token, message);
                    }
                }
            }

            return(Ok(mobileObj));
        }
        //totake:את כל המחלקה

        public static async Task SendNotification(string title, string body, string userToken)
        {
            try
            {
                using (var fcm = new FcmSender(GetFireBaseServerKey(), GetFireBaseSenderID()))
                {
                    await fcm.SendAsync(userToken, new
                    {
                        notification = new
                        {
                            title = title,
                            body  = body,
                            //כל שאר הערכים רשות
                            vibrate = "[300, 100, 400, 100, 400, 100, 400]",
                            //todoever: להחליף לאייקון הולם יותר
                            icon = "https://upload.wikimedia.org/wikipedia/en/thumb/3/34/AlthepalHappyface.svg/256px-AlthepalHappyface.svg.png",
                            tag  = "push demo",
                            data = new { url = "https://maps.google.com" }
                        }
                    });
                }
            }
            catch (Exception e)
            {
            }
        }
        public async Task SendFirebaseNotificationAsync(string title, string body, IEnumerable <Device> devices, string externalUrl = "")
        {
            var serverKey = _config["Firebase:ServerKey"];
            var senderId  = _config["Firebase:SenderId"];

            var data = new Dictionary <string, string>()
            {
                { "notiTitle", title },
                { "notiBody", body },
                { "externalUrl", externalUrl },
                { "click_action", "FLUTTER_NOTIFICATION_CLICK" }
            };

            foreach (var device in devices)
            {
                using (var fcm = new FcmSender(serverKey, senderId))
                {
                    Message message = new Message()
                    {
                        Notification = new Notification
                        {
                            Title = title,
                            Body  = body,
                            Sound = "default"
                        },
                        Data  = data,
                        Token = device.Token
                    };

                    var response = await fcm.SendAsync(device.Token, message);
                }
            }
        }
Ejemplo n.º 4
0
        private async Task SendFirebaseNotificationAsync(string title, string body, IEnumerable <Device> devices)
        {
            var serverKey = _config["Firebase:ServerKey"];
            var senderId  = _config["Firebase:SenderId"];

            foreach (var device in devices)
            {
                using (var fcm = new FcmSender(serverKey, senderId))
                {
                    Message message = new Message()
                    {
                        Notification = new Notification
                        {
                            Title = title,
                            Body  = body,
                        },
                        Token = device.Token
                    };
                    try
                    {
                        var response = await fcm.SendAsync(device.Token, message);
                    }
                    catch (Exception)
                    {
                        // TODO
                    }
                }
            }
        }
Ejemplo n.º 5
0
        // GET: /<controller>/
        public async Task <IActionResult> Index()
        {
            var         httpClient = new HttpClient();
            FcmSettings settings   = new FcmSettings();

            settings.SenderId  = "557535861881";
            settings.ServerKey = "AAAAgc-6HHk:APA91bGGjo4Xld7-Lg0vRTcORTZWKFIwZaTZnmw4fr21pgusvwobvSCjzUSjj7-7JlaIcQr2GDNptWZQKe5oWuopgkgpmH-aOHe9_Q9eKUHGgUIMhLPJhEtrq-jHPIyDpBLHmWp2tTf8";


            var fcm = new FcmSender(settings, httpClient);

            var notification = new GoogleNotification
            {
                Data = new GoogleNotification.DataPayload
                {
                    ExperienceId = "@choby/seekit24",
                    Message      = "安卓测试消息 🆚"
                },
                Priority = "high"
            };

            string deviceToken = "fQVPgfq8TZKrltAwHSB-WI:APA91bFWh5E5PKp_8fdjlkkeE7K6xjoA9CH9Dll-nJBvPwnKDcsNnH2Py5Gf5T7SMna4X0D35_tA8a32ytB29nApEei4Kx78pIsk7md6xfBh-_JffilmRZQSR179e2pc8pbZs4T78ocp";

            FcmResponse response = await fcm.SendAsync(deviceToken, notification);

            //  await fcm.SendAsync();

            return(Content($"android push result:"));//{response.IsSuccess().ToString()}
        }
Ejemplo n.º 6
0
 public async Task SendAsync(string deviceToken, FcmPayloadNotification payload)
 {
     using (var apn = new FcmSender(_appSettings.FCMServerKey, _appSettings.FCMSenderID))
     {
         await apn.SendAsync(deviceToken, payload);
     }
 }
Ejemplo n.º 7
0
        public async static void Push(string deviceToken, int busId, NotificationDto notification)
        {
            notification.Priority = priority;
            notification.Title    = appName;

            using var fcmClient = new FcmSender(firebaseApiKey, firebaseUser);
            await fcmClient.SendAsync(deviceToken, new { data = notification, busId = busId });
        }
Ejemplo n.º 8
0
 public NotificationsService(string senderId, string serverKey, string token)
 {
     _fcmSender = new FcmSender(new FcmSettings()
     {
         SenderId  = senderId,
         ServerKey = serverKey,
     }, new System.Net.Http.HttpClient());
     _token = token;
 }
Ejemplo n.º 9
0
        public async Task SendToAllDeviceUsers(Guid userId, FcmPayloadNotification payload)
        {
            var devices = _unitOfWork.DeviceRepository.Get(x => x.UserId == userId && x.IsActive && x.ExpiredAt > DateTime.UtcNow);

            using (var apn = new FcmSender(_appSettings.FCMServerKey, _appSettings.FCMSenderID))
            {
                foreach (var device in devices)
                {
                    await apn.SendAsync(device.DeviceToken, payload);
                }
            }
        }
Ejemplo n.º 10
0
        public async Task SendFireBaseNotificationsAsync()
        {
            var serverKey = _config["Firebase:ServerKey"];
            var senderId  = _config["Firebase:SenderId"];

            var tokens = await _uow.DeviceRepository.GetAllAsync();

            foreach (var device in tokens)
            {
                using (var fcm = new FcmSender(serverKey, senderId))
                {
                    //if (device.Type == Data.Entities.Enums.DeviceTypeEnum.ANDROID)
                    //{
                    //var googleNot = new GoogleNotification();
                    //googleNot.Data = new GoogleNotification.DataPayload
                    //{
                    //    Message = "Testing"
                    //};

                    Message message = new Message()
                    {
                        Notification = new Notification
                        {
                            Title = "My push notification title",
                            Body  = "Content for this push notification"
                        }
                        ,
                        //           Data = new Dictionary<string, string>()
                        //{
                        //    { "AdditionalData1", "data 1" },
                        //    { "AdditionalData2", "data 2" },
                        //    { "AdditionalData3", "data 3" },
                        //},
                        Token = device.Token
                    };

                    var response = await fcm.SendAsync(device.Token, message);

                    //}
                    //else
                    //{
                    //    var appleNot = new AppleNotification();
                    //    appleNot.Aps = new AppleNotification.ApsPayload
                    //    {
                    //        AlertBody = "Testing"
                    //    };
                    //    await fcm.SendAsync(device.Token, appleNot);
                    //}
                }
            }
        }
Ejemplo n.º 11
0
        private async Task <FcmResponse> SendToPushProvider(PushMessage message)
        {
            var fcm = new FcmSender("AAAAKquFIcw:APA91bGOmzRaHrhrJamb70K29-ecgflt8OZTYdQs8cSvB8kAYZME9TdeJlWDuYuEgXV7mF3fWyNVRka91so8ua-yzOgnVWNi7KuB-Ib8xSLQ_0MxzsL5QB5jxqOcme8Y8_NbDgcbnSUb", "183266255308");
            var res = await fcm.SendAsync(message.DeviceToken,
                                          new
            {
                notification = new
                {
                    body = message.TextMessage
                },
            });

            return(res);
        }
Ejemplo n.º 12
0
 public void sendMessageAsync()
 {
     using (var fcm = new FcmSender("AAAAANIAdg4:APA91bHMu_e6u-n6LhobVUTHGT5AsGhRmp3y9nQSMTE3VPh-QUbwgX_8w8kA8b3BOT6mfaRRSATsGNqe7_az5clbXvS3j7xKfyuYXB0t6TGtjFlYavNmUi-Hwc2YR9wmgh99mHiv263q", "3523245582"))
     {
         fcm.SendAsync("BMbolvHP5_Rl_XEoxNgVBTV4ZrFUIV4iyssRRQTk60HVWvBH5UaBkplgtZEyjMm_TMa4LfCtfw2jtUZhQBLnPME",
                       new
         {
             notification = new
             {
                 title = "Test",
                 body  = "Yeah",
             },
         });
     }
 }
        private static async Task SendFcmNotificationAsync()
        {
            var settings = new FcmSettings
            {
                SenderId  = fcmSenderId,
                ServerKey = fcmServerKey
            };

            var payload = new
            {
                notification = new { body = "Hello World!" }
            };

            var fcm      = new FcmSender(settings, new HttpClient());
            var response = await fcm.SendAsync(fcmReceiverToken, payload);
        }
 public async Task SendPushNotificationAsync(IEnumerable <string> deviceTokens,
                                             Notification notification)
 {
     using var fcm = new FcmSender(_firebaseNotification.ServerKey, _firebaseNotification.SenderId);
     foreach (string token in deviceTokens)
     {
         FcmResponse fcmResponse = await fcm.SendAsync(token, new
         {
             notification = new
             {
                 title        = notification.Title,
                 body         = notification.Message,
                 click_action = notification.Url
             },
         });
     }
 }
Ejemplo n.º 15
0
        public async Task SendUserNotificationAsync(int loggedUser, int id, UserNotificationRequest notif)
        {
            var user = await _uow.UserRepository.GetAsync(loggedUser);

            if (user.Role == RoleEnum.NORMAL)
            {
                throw new NotAllowedException("User");
            }
            var userToUpdate = await _uow.UserRepository.GetAll()
                               .Include(u => u.Devices)
                               .Where(u => u.Id == id)
                               .FirstOrDefaultAsync();

            if (userToUpdate == null)
            {
                throw new NotFoundException("User");
            }
            var serverKey = _config["Firebase:ServerKey"];
            var senderId  = _config["Firebase:SenderId"];

            foreach (var dev in userToUpdate.Devices)
            {
                using (var fcm = new FcmSender(serverKey, senderId))
                {
                    Message message = new Message()
                    {
                        Notification = new Notification
                        {
                            Title = notif.Title,
                            Body  = notif.Body
                        },
                        Token = dev.Token
                    };
                    try
                    {
                        var response = await fcm.SendAsync(dev.Token, message);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
Ejemplo n.º 16
0
        public async Task SendNotification(PushNotificationItem notification)
        {
            var users = dbService.GetUsers();

            foreach (var token in users)
            {
                using (var fcm = new FcmSender(_serverKey, token.UserName))
                {
                    await fcm.SendAsync(token.Token,
                                        new
                    {
                        notification = new
                        {
                            title = notification.Title,
                            body  = notification.Body
                        },
                    });
                }
            }
        }
        public async Task SendNotification(NotificationItem notification)
        {
            var users = _dbService.GetUsers();

            foreach (var user in users)
            {
                using (var fcm = new FcmSender(_options.ServerKey, user.UserName))
                {
                    await fcm.SendAsync(user.Token,
                                        new
                    {
                        notification = new
                        {
                            title = notification.Title,
                            body  = notification.Body
                        }
                    });
                }
            }
        }
Ejemplo n.º 18
0
        public void SendFcmMessageByToken()
        {
            FcmMessage message = new FcmMessage
            {
                DryRun          = true,
                RegistrationIds = new System.Collections.Generic.List <string>()
                {
                    _deviceId.Value, _deviceId2.Value
                },
                Notification = new FcmNotification
                {
                    Title = "test using c# unit test",
                    Body  = "test"
                }
            };
            FcmSender sender   = new FcmSender(_serverKey.Value, _senderId.Value);
            var       response = sender.Send(message);

            Assert.AreNotEqual(response.Result.Results[0].Error, string.Empty);
            Assert.AreNotEqual(response.Result.Results[1].Error, string.Empty);
        }
Ejemplo n.º 19
0
        static async Task Main(string[] args)
        {
            var path = args.Length > 0 ? args[0] : Path.Combine(Directory.GetCurrentDirectory(), "google.json");
            var json = JObject.Parse(File.ReadAllText(path));

            var serverKey   = json["serverKey"].ToString();
            var senderId    = json["senderId"].ToString();
            var deviceToken = json["deviceToken"].ToString();

            var settings = new FcmSettings
            {
                SenderId  = senderId,
                ServerKey = serverKey
            };

            var notification = json["payload"].ToObject <GoogleNotification>();

            var fcm      = new FcmSender(settings, http);
            var response = await fcm.SendAsync(deviceToken, notification);

            Console.WriteLine($"Response: {JsonConvert.SerializeObject(response)}");
        }
Ejemplo n.º 20
0
        public async void SendFcmMessageByGroupKey()
        {
            // Create a test group
            var groupName       = $"Group-{Guid.NewGuid().ToString()}";
            var fcmGroupHandler = new FcmGroupHandler(_serverKey.Value, _senderId.Value);
            var groupKey        = await fcmGroupHandler.AddTokenToGroup(groupName, new string[] { _deviceId.Value });

            // Send message by created group
            FcmMessage message = new FcmMessage
            {
                DryRun       = true,
                To           = groupKey,
                Notification = new FcmNotification
                {
                    Title = "test using c# unit test",
                    Body  = "test"
                }
            };
            FcmSender sender   = new FcmSender(_serverKey.Value, _senderId.Value);
            var       response = sender.Send(message);

            Assert.AreEqual(response.Result.Results, null);
        }
Ejemplo n.º 21
0
        private async Task SendNotificationsForDevices(List <Device> devices, string message, string type, Dictionary <string, string> payload)
        {
            if (devices.Count == 0)
            {
                return;
            }

            var iosPayload = new AppleNotification
            {
                Aps = new ApsPayload
                {
                    Alert = message,
                },
                Type   = type,
                Params = payload,
            };

            var androidPayload = new FirebaseNotification
            {
                Android = new FirebaseAndroidPayload
                {
                    Notification = new FirebaseAndroidNotification
                    {
                        Body      = message,
                        ChannelId = "GENERAL"
                    },
                    Priority = 10,
                    Data     = new FirebasePayload
                    {
                        Type   = type,
                        Params = payload
                    }
                },
                Notification = new FirebaseNotificationInfo
                {
                    Body = message
                }
            };

            var iOSDevices = devices.Where(d => d.Platform == 1).ToList();

            using var apn = new ApnSender(
                      settings.Connection.ApplePushKey,
                      settings.Connection.ApplePushKeyId,
                      settings.Connection.ApplePushTeamId,
                      settings.Connection.ApplePushBundleId,
                      ApnServerType.Production
                      );

            await Task.WhenAll(iOSDevices.Select(device => Policy
                                                 .HandleResult <ApnsResponse>(r => !r.IsSuccess)
                                                 .WaitAndRetryAsync(new[]
            {
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(4),
                TimeSpan.FromSeconds(8)
            }, (exception, timeSpan) =>
            {
                var time = timeSpan.ToString("h'h 'm'm 's's'", CultureInfo.CurrentCulture);
                Logger.LogWarning($"Failed to send iOS notification to device id {device.Token} in {time}: {exception?.Result?.Error?.Reason}");
            })
                                                 .ExecuteAsync(() => apn.SendAsync(iosPayload, device.Token))
                                                 ).ToArray())
            .ConfigureAwait(false);

            var androidDevices = devices.Where(d => d.Platform == 2).ToList();

            using var fcm = new FcmSender(settings.Connection.FirebaseServerKey, settings.Connection.FirebaseSenderId);
            await Task.WhenAll(androidDevices.Select(device => Policy
                                                     .HandleResult <FcmResponse>(r => r.Failure > 0)
                                                     .WaitAndRetryAsync(new[]
            {
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(4),
                TimeSpan.FromSeconds(8)
            }, (_, timeSpan) =>
            {
                var time = timeSpan.ToString("h'h 'm'm 's's'", CultureInfo.CurrentCulture);
                Logger.LogWarning($"Failed to send Android notification to device id {device.Token} in {time}");
            })
                                                     .ExecuteAsync(() => fcm.SendAsync(device.Token, androidPayload))
                                                     ).ToArray())
            .ConfigureAwait(false);
        }
Ejemplo n.º 22
0
        public async Task SendFireBaseNotificationsRemindersAsync()
        {
            var serverKey = _config["Firebase:ServerKey"];
            var senderId  = _config["Firebase:SenderId"];

            var tomorrow          = DateTime.UtcNow.AddDays(1);
            var usersWithoutPlans = await _uow.UserRepository.GetAll()
                                    .Include(u => u.Eats)
                                    .Include(u => u.Devices)
                                    .Include(u => u.UserSettings)
                                    .ThenInclude(s => s.Setting)
                                    .Where(u => !u.Eats.Any(e => e.CreatedAt.Date == tomorrow.Date))
                                    .ToListAsync();

            var reminder = await _uow.ReminderRepository.GetAll().Where(r => r.CodeName == RemindersConstants.NO_EAT_PLANNED_FOR_TOMORROW).FirstOrDefaultAsync();

            if (reminder != null)
            {
                foreach (var us in usersWithoutPlans)
                {
                    var lang     = us.UserSettings.Where(us => us.Setting.Name == SettingsConstants.LANGUAGE).FirstOrDefault();
                    var language = "";

                    if (lang == null || string.IsNullOrWhiteSpace(lang.Value))
                    {
                        language = "ES";
                    }
                    else
                    {
                        language = lang.Value.ToUpper();
                    }

                    foreach (var device in us.Devices)
                    {
                        using (var fcm = new FcmSender(serverKey, senderId))
                        {
                            Message message = new Message()
                            {
                                Notification = new Notification
                                {
                                    Title = language == "EN" && !string.IsNullOrWhiteSpace(reminder.TitleEN) ? reminder.TitleEN :
                                            (language == "IT" && !string.IsNullOrWhiteSpace(reminder.TitleIT) ? reminder.TitleIT : reminder.Title),
                                    Body = language == "EN" && !string.IsNullOrWhiteSpace(reminder.BodyEN) ? reminder.BodyEN :
                                           (language == "IT" && !string.IsNullOrWhiteSpace(reminder.BodyIT) ? reminder.BodyIT : reminder.Body),
                                },
                                Token = device.Token
                            };
                            try
                            {
                                var response = await fcm.SendAsync(device.Token, message);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }

            //await RecurringJobSchedulerAsync();
        }