public async Task PushNotification(PushNotificationModel model, PushNotificationPayloadModel payloadmodel)
        {
            string payload = payloadToString(payloadmodel);

            _logger.LogDebug(payload);
            await NofityUser(model, payload);
        }
Esempio n. 2
0
        /// <summary>
        /// Send push notification to client app
        /// </summary>
        /// <param name="model">Push information</param>
        /// <returns>Task no return</returns>
        public async Task SendPush(PushNotificationRequest model)
        {
            try
            {
                var userDevices = await this._deviceRepository.GetAllByUsernameAsync(model.Username);

                var iosDevices     = userDevices.Where(x => x.DeviceType == Core.Enumerations.DeviceType.IOS).ToList();
                var androidDevices = userDevices.Where(x => x.DeviceType == Core.Enumerations.DeviceType.Android).ToList();

                if (iosDevices.Count > 0)
                {
                    var pushData = new PushNotificationModel
                    {
                        Type         = model.Type,
                        Message      = model.Message,
                        DeviceTokens = iosDevices.Select(x => x.DeviceToken).ToList()
                    };

                    var result = this._applePushService.SendPushNotification(pushData);

                    this._logger.LogInformation(result);
                }
            }
            catch
            {
                throw;
            }
        }
Esempio n. 3
0
        public virtual async Task <IActionResult> SendNotification(PushNotificationModel model)
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageCustomers))
            {
                return(AccessDeniedView());
            }

            IPagedList <Customer> notificationCustomers = await _customerService.GetAllPushNotificationCustomersAsync(sendToAll : true);

            foreach (var customer in notificationCustomers)
            {
                if (!string.IsNullOrEmpty(customer.PushToken))
                {
                    var expoSDKClient = new PushApiClient();
                    var pushTicketReq = new PushTicketRequest()
                    {
                        PushTo = new List <string>()
                        {
                            customer.PushToken
                        },
                        PushTitle = model.MessageTitle,
                        PushBody  = model.MessageBody
                    };
                    var result = await expoSDKClient.PushSendAsync(pushTicketReq);
                }
            }
            //prepare model
            model = new PushNotificationModel();

            //if we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 4
0
        public async Task <bool> Post([FromBody] PushNotificationModel subscription)
        {
            try
            {
                var pushSubscription = new PushSubscription(subscription.Endpoint, subscription.Key, subscription.AuthSecret);
                var vapidDetails     = new VapidDetails("http://localhost:50973/forum", "BAdnuHOxwOFm_GV_NYG1CZOjddlrVfDbKobDFTTxQvgcGBhPI47gkxfEUdtgX2iO_x4PwUkyj-xS7Uke_UmIaqQ",
                                                        "vrRVfvxyx4kIEYSfansI_eOI4a-HdTCJpa0EVmjLYnE");

                ForumPostSubscriptions.AddSubscription(pushSubscription);

                var webPushClient = new WebPushClient();
                webPushClient.SetVapidDetails(vapidDetails);

                var payload = new PushNotificationPayload
                {
                    Msg  = "Thank you for subscribing",
                    Icon = "C:/Temp/icon192x192.png",
                };
                string temp = JsonConvert.SerializeObject(payload);

                //await webPushClient.SendNotificationAsync(pushSubscription, temp, );
                await webPushClient.SendNotificationAsync(pushSubscription, temp, vapidDetails);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        public int AddFirebaseToken([FromBody] PushNotificationModel pushNotification)
        {
            try
            {
                var data = this.context.pushNotifications.Where(t => t.UserId == pushNotification.UserId).FirstOrDefault();
                if (data == null)
                {
                    var newUser = new PushNotificationModel()
                    {
                        UserId    = pushNotification.UserId,
                        PushToken = pushNotification.PushToken
                    };

                    int save = 0;
                    this.context.pushNotifications.Add(newUser);
                    save = this.context.SaveChanges();
                    return(save);
                }

                data.PushToken = pushNotification.PushToken;
                int result = 0;
                result = this.context.SaveChanges();
                return(result);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Esempio n. 6
0
        public async Task SendAsync(PushNotificationModel content)
        {
            var httpWebRequest = WebRequest.Create(_firebaseSettings.Address);

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Headers.Add("Authorization:key=" + _firebaseSettings.ServerKey);
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync()))
            {
                var settings = new JsonSerializerSettings
                {
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new SnakeCaseNamingStrategy()
                    }
                };
                var json = JsonConvert.SerializeObject(content, settings);
                await streamWriter.WriteAsync(json);

                await streamWriter.FlushAsync();
            }

            var httpResponse = await httpWebRequest.GetResponseAsync();

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = await streamReader.ReadToEndAsync();
            }
        }
Esempio n. 7
0
        public async Task <IActionResult> SendPushNotification(PushNotificationModel model)
        {
            var user = await _userManager.FindByIdAsync(model.UserId);

            if (user == null)
            {
                return(Json(new { result = false }));
            }

            NotificationCreateResult pushResult;

            try {
                pushResult = PushNotificationHelper.SendPushOneSignal(user.Email.ToLowerInvariant(), model.Message);   // .SendAPNSNotification(model.DeviceToken, model.Message);

                _context.Files.Add(new FileStorage {
                    Content   = $"{model.Message}",
                    Type      = FileStorageType.PushNotification,
                    CreatedAt = DateTime.UtcNow,
                    MimeType  = "text/plain",
                    Title     = "Push Message",
                    Owner     = user,
                    Viewed    = true
                });
                await _context.SaveChangesAsync();
            } catch (Exception e) {
                return(Json(new { exception = e.Message, result = false }));
            }

            return(Json(new { result = pushResult.Recipients > 0 }));
        }
Esempio n. 8
0
        public void Broadcast(PushNotificationModel notification, CancellationToken cancellationToken)
        {
            var pushMessage = notification.ToPushMessage();

            foreach (PushSubscription pushSubscription in _pushSubscriptionService.GetAll())
            {
                _pushClient.RequestPushMessageDeliveryAsync(pushSubscription, pushMessage, cancellationToken);
            }
        }
Esempio n. 9
0
        public async Task <IActionResult> SelectMenuForToday(PushNotificationModel notification)
        {
            //TODO: save to database

            //notification
            await SendNotification(notification);

            return(RedirectToAction("Menus", "Admin"));
        }
Esempio n. 10
0
        protected override void OnMessageReceivedInternal(object pushNotification, PushNotificationModel parsedNotification, bool inForeground)
        {
            base.OnMessageReceivedInternal(pushNotification, parsedNotification, inForeground);

            if (!parsedNotification.IsSilent)
            {
                ShowNotification(pushNotification, parsedNotification, inForeground);
            }
        }
Esempio n. 11
0
        public async Task NewUserAsync(string email, PushNotificationModel model)
        {
            model.IdentityEmail = email;
            model.Id            = Guid.NewGuid();
            await _mongoRepo.AddAsync(model);

            var modelstring = model.ToJSON();

            _logger.LogDebug("model : " + modelstring);
        }
Esempio n. 12
0
        public async Task<IRestResponse> Send(PushNotificationModel model, Authenticator authenticator = null)
        {
            const string Resource = "PushNotifications/Send";
            if (ReferenceEquals(null, model)) throw new ArgumentNullException(nameof(model));

            var request = CreateRestRequest(Resource, Method.POST, authenticator)
                .AddJsonBody(model);

            return await CreateRestClient().ExecuteAsync(request);
        }
Esempio n. 13
0
        private void ShowNotification(object pushNotification, PushNotificationModel parsedPushNotification, bool inForeground)
        {
            if (_showForegroundNotificationsInSystemOptions.ShouldShow() || !inForeground)
            {
                var remoteMessage    = pushNotification as RemoteMessage;
                var notificationData = remoteMessage?.Data ?? new Dictionary <string, string>();

                NotificationsHelper.CreateNotification(_appContext, parsedPushNotification, notificationData);
            }
        }
Esempio n. 14
0
        public async Task <PushNotificationModel> PreparePushNotificationListModel()
        {
            var pushNotifications = await _pushNotificationService.GetAllPushNotificationsAsync();

            var model = new PushNotificationModel
            {
                PushNotifications = pushNotifications
            };

            return(model);
        }
Esempio n. 15
0
        public virtual async Task <IActionResult> SendNotification()
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageCustomers))
            {
                return(AccessDeniedView());
            }

            //prepare model
            var model = new PushNotificationModel();

            return(View(model));
        }
 public static Domain.Aggregates.Notification ToNotification(this PushNotificationModel model, string language)
 {
     return(new Domain.Aggregates.Notification
     {
         Title = model.Title,
         Text = model.Text,
         DocumentId = model.DocumentId,
         Created = DateTime.UtcNow,
         Language = language,
         IsSentToAllDevices = model.IsSendToAllDevices
     });
 }
        // You should call Init prior to using this method
        public static void CreateNotification(
            Context context,
            PushNotificationModel pushNotification,
            IDictionary <string, string> notificationData)
        {
            if (context == null || _notificationsSettings == null)
            {
                return;
            }

            var channelId = _notificationsSettings.GetChannelIdForNotification(pushNotification);

            if (string.IsNullOrEmpty(channelId))
            {
                channelId = _notificationsSettings.DefaultChannelId;
            }

            var title   = string.IsNullOrEmpty(pushNotification.Title) ? GetApplicationName(context) : pushNotification.Title;
            var message = pushNotification.Body;

            var styles = _notificationsSettings.GetStylesForNotification(pushNotification);

            var notificationBuilder = new NotificationCompat.Builder(context, channelId)
                                      .SetContentTitle(title)
                                      .SetContentText(message)
                                      .SetPriority((int)styles.Priority)
                                      .SetAutoCancel(styles.AutoCancel)
                                      .SetStyle(styles.Style)
                                      .SetSound(styles.SoundUri)
                                      .SetSmallIcon(styles.IconRes)
                                      .SetColor(styles.IconArgbColor);

            var intentActivityInfo = _notificationsSettings.GetIntentActivityInfoFromPush(pushNotification);
            var intent             = new Intent(context, intentActivityInfo.ActivityType);

            intent.PutExtra(_notificationsSettings.LaunchedFromPushNotificationKey, true);
            if (notificationData != null)
            {
                foreach (var(key, value) in notificationData)
                {
                    intent.PutExtra(key, value);
                }
            }

            var pendingIntent = CreatePendingIntent(context, intent, intentActivityInfo.DoCreateParentStack, intentActivityInfo.Flags);

            notificationBuilder.SetContentIntent(pendingIntent);

            _notificationsSettings.CustomizeNotificationBuilder(notificationBuilder, pushNotification, styles.Id);

            NotificationManagerCompat.From(context).Notify(styles.Id, notificationBuilder.Build());
        }
        private PushNotificationModel GetStore(PushNotificationModel model)
        {
            model.StockTakeList          = GetStockTakeStore(null);
            model.AvailableStockTakeList = model.StockTakeList.Select(stList => new SelectListItem
            {
                Text  = stList.StockTakeNo,
                Value = stList.StockTakeNo
            }).ToList();

            model.SelectedStockTake = new List <int?>();

            return(model);
        }
Esempio n. 19
0
        public async Task <IActionResult> FeaturePublish([FromBody] PushNotificationModel featureModel)
        {
            List <string> failureDeviceIds = new List <string>();

            try
            {
                foreach (var item in featureModel.DeviceIdList)
                {
                    logger.LogInformation("Feature Publish push notification called for deviceId- {0}, feature- {1}, description- {2}", item, featureModel.FeatureName, featureModel.FeatureDescription);
                    var jsonNotification = "{\"deviceId\":\"" + item + "\",\"notificationType\":\"Feature\", \"id\":\"" + featureModel.Id + "\", \"featureName\":\"" + featureModel.FeatureName + "\",\"methodName\":\"" + featureModel.MethodName + "\", \"featureDescription\":\"" + featureModel.FeatureDescription + "\"}";
                    var outcome          = await _notificationHubRepo.SendNotification("{\"data\":{\"message\":" + jsonNotification + "}}",
                                                                                       item);

                    if (outcome.Results != null)
                    {
                        foreach (RegistrationResult result in outcome.Results)
                        {
                            logger.LogInformation("Notification log result Platform- {0}, registrationId- {1}, outcome- {2}",
                                                  result.ApplicationPlatform, result.RegistrationId, result.Outcome);
                        }
                    }
                    else
                    {
                        failureDeviceIds.Add(item);
                    }
                }

                if (failureDeviceIds.Count == 0)
                {
                    return(Ok(true));
                }
                else
                {
                    StringBuilder failureMsg = new StringBuilder("Failed to send notification to deviceIds -");
                    foreach (var item in failureDeviceIds)
                    {
                        failureMsg.Append(item + ",");
                    }
                    logger.LogError("Feature Publish push notification message- {0}", failureMsg.ToString());
                    return(StatusCode(StatusCodes.Status502BadGateway, failureMsg.ToString()));
                }
            }
            catch (Exception e)
            {
                logger.LogError(e, "Feature Publish push notification called Exception {0}, for deviceId- {1}, feature- {2}, description- {3}",
                                e.Message, featureModel.DeviceIdList.First(), featureModel.FeatureName, featureModel.FeatureDescription);
                throw;
            }
        }
Esempio n. 20
0
        public PushNotificationModel Parse(object pushNotificationData)
        {
            var pushNotification = new PushNotificationModel();

            if (pushNotificationData is RemoteMessage remoteNotification)
            {
                pushNotification = ParseRemoteMessageNotification(remoteNotification);
            }
            else if (pushNotificationData is Bundle bundleNotification)
            {
                pushNotification = ParseBundleNotification(bundleNotification);
            }

            return(pushNotification);
        }
Esempio n. 21
0
        private PushNotificationModel ParseBundleNotification(Bundle bundleNotification)
        {
            var pushNotification = new PushNotificationModel();

            pushNotification.Title = bundleNotification.GetString(DataTitleKey); // if stored inside Data
            pushNotification.Body  = bundleNotification.GetString(DataBodyKey);  // if stored inside Data

            // If we are here it means that the user tapped on a notification thus it is definitely not silent
            pushNotification.IsSilent = false;

            pushNotification.AdditionalData = bundleNotification.GetString(DataKey) !;
            pushNotification.Type           = ParseNotificationTypeFromBundle(bundleNotification);

            return(pushNotification);
        }
Esempio n. 22
0
        private PushNotificationModel ParseRemoteMessageNotification(RemoteMessage remoteNotification)
        {
            var pushNotification = new PushNotificationModel();

            var pushMessage = remoteNotification.GetNotification();
            var pushData    = remoteNotification.Data;

            pushNotification.Title = ParseNotificationTitleFromData(pushMessage, pushData);
            pushNotification.Body  = ParseNotificationMessageFromData(pushMessage, pushData);

            pushNotification.IsSilent = string.IsNullOrEmpty(pushNotification.Body);

            pushNotification.Type           = ParseNotificationTypeFromData(pushData);
            pushNotification.AdditionalData = GetStringFromDictionary(pushData, DataKey);

            return(pushNotification);
        }
        private PushNotificationModel GetRepeat(PushNotificationModel model)
        {
            Array         arr     = Enum.GetValues(typeof(RepeatEnum));
            List <string> lstDays = new List <string>(arr.Length);

            for (int i = 0; i < arr.Length; i++)
            {
                model.AvailableRepeatList.Add(new SelectListItem
                {
                    Text  = GetDescription((RepeatEnum)Enum.Parse(typeof(RepeatEnum), arr.GetValue(i).ToString())),
                    Value = ((int)arr.GetValue(i)).ToString()
                });
            }

            model.SelectedRepeat = new int?();

            return(model);
        }
Esempio n. 24
0
        public async Task <IActionResult> UnRegisterPushNotifications([FromBody] PushNotificationModel model)
        {
            try
            {
                var pushNotificationToken = new PushNotificationToken
                {
                    Token = model.Token
                };

                await _pushNotificationTokensRepository.RemovePushNotificationToken(pushNotificationToken);

                return(Ok(model));
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                return(BadRequest(new ErrorMessage(ex)));
            }
        }
        public static PushNotificationAndroidRequest ToAndroidNotification(this PushNotificationModel notifyModel, string topicLanguage, string clickAction)
        {
            const string androidTopic = "platform_android";
            var          now          = DateTime.UtcNow;
            var          id           = now.Second + now.Minute * 100 + now.Hour * 10000 + now.Day * 1000000 + now.Month * 100000000;

            return(new PushNotificationAndroidRequest
            {
                Condition = $"'{androidTopic}' in topics && '{topicLanguage}' in topics",
                Data = new PushNotifyData
                {
                    Id = id,
                    Title = notifyModel.Title,
                    Body = notifyModel.Text,
                    DocumentId = notifyModel.DocumentId,
                    ClickAction = clickAction
                }
            });
        }
Esempio n. 26
0
        public JsonResult SaveSubscription(string pushSubscription)
        {
            bool   success = false;
            string error   = "error";

            try
            {
                var model = new PushNotificationModel();

                model.SaveSubscription(pushSubscription, base.Request.Browser.Browser);
                success = true;
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }

            return(Json(new { Success = success, Message = error }));
        }
        public static PushNotificationIosRequest ToIosNotification(this PushNotificationModel notifyModel, string topicLanguage, string clickAction)
        {
            const string iosTopic = "platform_ios";

            return(new PushNotificationIosRequest
            {
                Condition = $"'{iosTopic}' in topics && '{topicLanguage}' in topics",
                Data = new PushNotifyData
                {
                    DocumentId = notifyModel.DocumentId,
                },
                Notification = new IosNotification
                {
                    Title = notifyModel.Title,
                    Body = notifyModel.Text,
                    ClickAction = clickAction,
                    // other fields initialized by default in the model
                }
            });
        }
Esempio n. 28
0
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                await Task.Delay(NOTIFICATION_FREQUENCY, cancellationToken);

                var temperatureC = _random.Next(-20, 55);
                var notification = new PushNotificationModel()
                {
                    Notification = new Notification
                    {
                        Title = "New Weather Forecast",
                        Body  = $"Temp. (C): {temperatureC} | Temp. (F): {32 + (int)(temperatureC / 0.5556)}",
                        Icon  = "assets/icons/icon-96x96.png"
                    }
                };

                Broadcast(notification, cancellationToken);
            }
        }
Esempio n. 29
0
        private async Task NofityUser(PushNotificationModel model, string payload)
        {
            var client = new WebPushClient();
            var subs   = new PushSubscription(model.Endpoint, model.Keys.P256dh, model.Keys.Auth);

            try
            {
                await client.SendNotificationAsync(subs, payload, vapidDetails);

                _logger.LogDebug("Message Sent email:" + model.IdentityEmail + payload);
            }
            catch (WebPushException ex)
            {
                if (ex.StatusCode == HttpStatusCode.Gone || ex.StatusCode == HttpStatusCode.NotFound)
                {
                    await _mongoRepo.RemoveAsync(model.Id);

                    _logger.LogError(payload);
                }
            }
        }
Esempio n. 30
0
        public virtual PushNotificationModel Parse(object pushNotificationData)
        {
            var dictionary       = (NSDictionary)pushNotificationData;
            var pushNotification = new PushNotificationModel();

            var aps = dictionary.GetDictionaryByKey(ApsKey);

            if (aps == null)
            {
                throw new NullReferenceException($"{nameof(aps)} dictionary is null");
            }

            var alertObject = aps.GetObjectByKey(AlertKey);

            var title = string.Empty;
            var body  = string.Empty;

            if (alertObject is NSDictionary alertDictionary)
            {
                title = alertDictionary.GetStringByKey(TitleKey);
                body  = alertDictionary.GetStringByKey(BodyKey);
            }
            else if (alertObject is NSString str)
            {
                body = str;
            }

            pushNotification.Title = title;
            pushNotification.Body  = body;

            pushNotification.IsSilent = aps.GetIntByKey(ContentAvailableKey) == 1;

            var additionalData = dictionary.GetStringByKey(DataKey);

            pushNotification.AdditionalData = additionalData;

            pushNotification.Type = ParseNotificationType(dictionary, aps, additionalData);

            return(pushNotification);
        }
Esempio n. 31
0
        public async Task <IActionResult> RegisterPushNotifications([FromBody] PushNotificationModel model)
        {
            try
            {
                var user = await GetCurrentAuthenticatedUser();

                var pushNotificationToken = new PushNotificationToken
                {
                    Token             = model.Token,
                    ApplicationUserId = user.Id
                };

                await _pushNotificationTokensRepository.SavePushNotificationToken(pushNotificationToken);

                return(Ok(model));
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                return(BadRequest(new ErrorMessage(ex)));
            }
        }