/// <summary> /// The SendPushNotificationToStudent. /// </summary> /// <param name="assignment">The assignment<see cref="TeacherAssignment"/>.</param> /// <returns>The <see cref="Task"/>.</returns> private async Task SendPushNotificationToStudent(TeacherAssignment assignment) { try { var pushNotification = new PushNotification { Title = assignment.SubjectName, Body = assignment.AssignmentName }; var studentData = await _tableStorage.GetAllAsync <Entites.Student>("Student"); var students = studentData.Where(s => s.PartitionKey == assignment.SchoolId && s.ClassId == assignment.ClassId); foreach (var student in students) { if (!String.IsNullOrEmpty(student.NotificationToken)) { pushNotification.RecipientDeviceToken = student.NotificationToken; await _pushNotificationService.SendAsync(pushNotification); } } } catch (Exception ex) { throw new AppException("Exception thrown in Notify Service: ", ex.InnerException); } }
/// <summary> /// The SendPushNotificationToStudent. /// </summary> /// <param name="model">The model<see cref="AssessmentShare"/>.</param> /// <returns>The <see cref="Task"/>.</returns> private async Task SendPushNotificationToStudent(AssessmentShare model) { try { var assessments = await _tableStorage.GetAllAsync <Entites.Assessment>("Assessments"); var assessment = assessments.SingleOrDefault(a => a.RowKey == model.AssessmentId); var pushNotification = new PushNotification { Title = $"{assessment.SubjectName}", Body = $"Assessment available, ${assessment.AssessmentTitle}" }; var studentData = await _tableStorage.GetAllAsync <Entites.Student>("Student"); var students = studentData.Where(s => s.PartitionKey == model.SchoolId && s.ClassId == model.ClassId); foreach (var student in students) { if (!String.IsNullOrEmpty(student.NotificationToken)) { pushNotification.RecipientDeviceToken = student.NotificationToken; await _pushNotificationService.SendAsync(pushNotification); } } } catch (Exception ex) { throw new AppException("Exception thrown in Notify Service: ", ex.InnerException); } }
private async Task SendPushNotificationToStudent(Distribution model) { try { var contents = await _tableStorage.GetAllAsync <Entites.Content>("Content"); var content = contents.SingleOrDefault(user => user.RowKey == model.ContentId); var pushNotification = new PushNotification { Title = $"Course content {content.CourseName}", Body = $"Course content available, ${content.CourseDescription}" }; var studentData = await _tableStorage.GetAllAsync <Entites.Student>("Student"); var students = studentData.Where(s => s.PartitionKey == model.SchoolId && s.ClassId == model.ClassId); foreach (var student in students) { if (!String.IsNullOrEmpty(student.NotificationToken)) { pushNotification.RecipientDeviceToken = student.NotificationToken; await _pushNotificationService.SendAsync(pushNotification); } } } catch (Exception ex) { throw new AppException("Exception thrown in Notify Service: ", ex.InnerException); } }
/// <summary> /// Contains the information that should be sent to the customer about missing match /// </summary> /// <param name="expiredRide">Ride which did not find a match</param> /// <returns></returns> private async Task NotifyCustomerAboutMatchNotFound(Ride expiredRide) { var notification = _pushNotificationFactory.GetPushNotification(); notification.Name = "Ingen match"; notification.Title = "Ingen match"; notification.Body = $"Din dele-tur kl. {expiredRide.DepartureTime.Hour}:{expiredRide.DepartureTime.Minute} til {expiredRide.EndDestination.StreetName} fandt ingen match. Prøv en solotur. "; notification.Devices.Add(expiredRide.DeviceId); notification.CustomData.Add("Type", "NoMatch"); notification.CustomData.Add("RideId", expiredRide.Id.ToString()); await _pushNotificationService.SendAsync(notification); }
/// <summary> /// Send notification to devices registered to userId with optional data as payload. /// </summary> /// <param name="service">Instance of <see cref="IPushNotificationService"/>.</param> /// <param name="configurePushNotificationMessage">The delegate that will be used to build the <see cref="PushNotificationMessage"/>.</param> public static async Task SendAsync(this IPushNotificationService service, Func <PushNotificationMessageBuilder, PushNotificationMessageBuilder> configurePushNotificationMessage) { if (configurePushNotificationMessage == null) { throw new ArgumentNullException(nameof(configurePushNotificationMessage)); } var pushNotificationMessageBuilder = configurePushNotificationMessage(new PushNotificationMessageBuilder()); var pushNotificationMessage = pushNotificationMessageBuilder.Build(); await service.SendAsync(pushNotificationMessage.Title, pushNotificationMessage.Body, pushNotificationMessage.Data, pushNotificationMessage.UserTag, pushNotificationMessage.Classification, pushNotificationMessage.Tags.ToArray()); }
public async Task ProcessBytes(byte[] data, WebSocketReceiveResult result) { var reservedBytes = 12; var soundChars = data .Take(result.Count) .Skip(reservedBytes) .Select(d => (char)d) .ToArray(); var soundData = new string(soundChars) .Trim() .Split(' ') .Select(s => double.Parse(s)); var normalizedSoundData = soundData .Select(d => d > 542 || d < 538 ? d : 0) .Select(d => d / 1024d) .ToArray(); var firstBlock = normalizedSoundData.Take(normalizedSoundData.Length / 2).ToArray(); var matches = _soundRecognitionService.Recognize(firstBlock).ToList(); var secondBlock = normalizedSoundData.Skip(normalizedSoundData.Length / 2).ToArray(); matches.AddRange(_soundRecognitionService.Recognize(secondBlock).ToList()); var mostSimilar = matches.OrderByDescending(m => m.Match).First(); if (mostSimilar.Match >= 0.6 && mostSimilar.Match <= 0.85) { return; } var sensorId = SensorHelper.IdFromBytes(data); var sensorInfo = await _sensorRepository.FindAsync(sensorId); var soundLabel = await _soundLabelRepository.GetByLabelNumberAsync(mostSimilar.LabelNumber); await _pushNotificationService.SendAsync(new PushNotificationModel { Notification = new NotificationContentModel { Body = soundLabel?.LabelDescription, Payload = sensorInfo.RoomTag, Title = sensorInfo.PlaceAlias }, RegistrationIds = sensorInfo.ObservingDevices?.Select(o => o.Device.Token).ToArray() }); await _soundLogRepository.CreateAsync(sensorId, soundLabel.LabelNumber, mostSimilar.Match); }
public async Task <IActionResult> Get() { await pushNotificationService.SendAsync("dJDZ5g_scFg:APA91bFPJeRCinee3WKWFBvPradWvUG91VU-xg6M6HTBPpw9z4x5N-9hDh6bzNtbLCY3eSA8PVcGaaVgy60bccOTjNgMxlSJg_ZhRPJx1NLNxp1UEGsf3ByWsp9Ldmc4WRMSGicPXSCh", new FcmPayloadNotification { Notification = new FcmNotification { Title = "Test", Body = "content", }, Data = new FcmDataNotification { Id = "guid", Image = null, NotificationDate = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ") } }); return(Success()); }
public async Task <IdentityResult> ApproveUser(string username) { ApplicationUser user = await _userManager.FindByNameAsync(username); if (user == null) { return(IdentityResult.Failed($"User '{username}' not found.")); } user.IsApproved = true; // TODO: The hook should be deleted. // The hook for load lazy property UserInfo. user.UserInfo.ToString(); try { var result = await _userManager.UpdateAsync(user); if (result.Succeeded) { if (!string.IsNullOrWhiteSpace(user.FCMPushNotificationToken) && _pushService != null) { await _pushService.SendAsync( user.FCMPushNotificationToken, "Approved by admin in Nanobank.", $"Account '{user.UserName}' have been approved by admin."); } await _userManager.SendEmailAsync( user.Id, "Approved by admin in Nanobank.", $"<p>Account <i>{user.UserName}</i> have been <b>approved</b> by admin.</p>"); } return(result); } catch (DbUpdateException ex) { _logger.Error("UserRepository.ApproveUser", ex.InnerException.InnerException); return(IdentityResult.Failed(ex.InnerException.InnerException.Message)); } }
/// <summary> /// Notify all customers related to the order that their ride has been accepted. /// </summary> /// <param name="order">The order containing the customers that should be notified</param> /// <returns></returns> private async Task NotifyCustomersAsync(Order order) { try { foreach (var ride in order.Rides) { var notification = _pushNotificationFactory.GetPushNotification(); notification.Name = "Accept"; notification.Title = "Tur accepteret"; notification.Body = $"Din tur kl. {ride.DepartureTime.Hour}:{ride.DepartureTime.Minute} til {ride.EndDestination.StreetName} er accepteret af {order.TaxiCompany.Name}"; notification.Devices.Add(ride.DeviceId); notification.CustomData.Add("rideId", ride.Id.ToString()); await _pushNotificationService.SendAsync(notification); } } catch (Exception e) { Debug.WriteLine(e); } }
public async Task <IActionResult> SendPushNotification( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "push/notification")] [RequestBodyType(typeof(PushNotification), "Send push notification")] HttpRequest request) { var validateStatus = base.AuthorizationStatus(request); if (validateStatus != HttpStatusCode.Accepted) { return(new BadRequestObjectResult(validateStatus)); } string requestBody = await new StreamReader(request.Body).ReadToEndAsync(); PushNotification requestData = JsonConvert.DeserializeObject <PushNotification>(requestBody); try { await _notification.SendAsync(requestData); } catch (HttpResponseException ex) { return(new BadRequestObjectResult(ex)); } return(new OkObjectResult(new { message = "Push notification send successfully." })); }
/// <summary> /// Send notifications to specified tags. /// </summary> /// <param name="service">Instance of <see cref="IPushNotificationService"/>.</param> /// <param name="title">Message of notification.</param> /// <param name="body">Body of notification.</param> /// <param name="tags">Tags are used to route notifications to the correct set of device handles.</param> /// <param name="data">Data passed to mobile client, not visible to notification toast.</param> /// <param name="classification">The notification's type.</param> public static Task SendAsync(this IPushNotificationService service, string title, string body, IList <string> tags, string data = null, string classification = null) => service.SendAsync(title, body, tags, data, classification);
/// <summary> /// Send notifications to devices registered to userId with payload data and classification. /// </summary> /// <typeparam name="TData">The type of data sent in the notification payload.</typeparam> /// <param name="service">Instance of <see cref="IPushNotificationService"/>.</param> /// <param name="title">Message of notification.</param> /// <param name="body">Body of notification.</param> /// <param name="data">Data passed to mobile client, not visible to notification toast.</param> /// <param name="userTag">UserId to be passed as tag.</param> /// <param name="classification">The type of the Push Notification.</param> /// <param name="tags">Optional tag parameters.</param> public static Task SendAsync <TData>(this IPushNotificationService service, string title, string body, TData data, string userTag, string classification = null, params string[] tags) where TData : class => service.SendAsync(title, body, data != null ? JsonSerializer.Serialize(data, JsonSerializerOptionDefaults.GetDefaultSettings()) : null, userTag, classification, tags);
/// <summary> /// Send notifications to devices registered to userId with payload data and classification. /// </summary> /// <param name="service">Instance of <see cref="IPushNotificationService"/>.</param> /// <param name="title">Message of notification.</param> /// <param name="body">Body of notification.</param> /// <param name="data">Data passed to mobile client, not visible to notification toast.</param> /// <param name="userTag">UserId to be passed as tag.</param> /// <param name="classification">The type of the Push Notification.</param> /// <param name="tags">Optional tag parameters.</param> public static Task SendAsync(this IPushNotificationService service, string title, string body, string data, string userTag, string classification = null, params string[] tags) => service.SendAsync(title, body, new string[] { userTag }.Concat(tags ?? Array.Empty <string>()).ToList(), data, classification);
/// <summary> /// Sends a notification to all registered devices. /// </summary> /// <param name="service">Instance of <see cref="IPushNotificationService"/>.</param> /// <param name="title">Message of notification.</param> /// <param name="body">Body of notification.</param> /// <param name="data">Data passed to mobile client, not visible to notification toast.</param> /// <param name="classification">The type of the Push Notification.</param> public static Task BroadcastAsync(this IPushNotificationService service, string title, string body, string data, string classification = null) => service.SendAsync(title, body, new List <string>(), data, classification);
/// <summary> /// Send notifications to devices registered to userId. /// </summary> /// <param name="service">Instance of <see cref="IPushNotificationService"/>.</param> /// <param name="message">Message of notification.</param> /// <param name="data">Data passed to mobile client, not visible to notification toast.</param> /// <param name="userId">UserId to be passed as tag.</param> /// <param name="tags">Optional tag parameters.</param> public static async Task SendAsync(this IPushNotificationService service, string message, string data, string userId, params string[] tags) => await service.SendAsync(message, new string[] { userId }.Concat(tags ?? new string[0]).ToList(), data);
public async Task NotifyUpcomingAppointment() { try { //await _pushNotificationService.SendAsync("fLP2irJ-VeY:APA91bH04EsECWoZJ__E2yTl6bT6x2mA7WNZBJdQ88VYu_LMgaC2YrOT6cSRev3yTiZTVGoU038mLR4g2rfidFJX0-Ksl874ZOtPfQKh-dxzoCB4ZtG9kuBzeMGbReTXk_lJkmgHDPCo", new FcmPayloadNotification //{ // Data = new FcmDataNotification // { // Id = "1", // AppointmentId = "1", // NotificationDate = DateTime.Now.ToString() // }, // Notification = new FcmNotification // { // Title = "test", // Body = "test" // } //}); var reminderAppointments = await _unitOfWork.AppointmentRepository.GetReminderAppointments(); if (reminderAppointments.Length > 0) { var notifications = reminderAppointments.ConvertArray(x => new DbNotificationProjection { UserId = x.UserId, Title = "Nhắc nhở lịch hẹn", Content = $"Bạn có lịch hẹn với bác sĩ {x.DoctorName} vào lúc {x.AppointmentDate.ToString("HH:mm dd/MM/yyyy")}.", Image = x.DoctorImage, NotificationDate = DateTime.Now, HasRead = false, Devices = x.Devices, AppointmentId = x.AppointmentId }); await _unitOfWork.NotificationRepository .AddRangeAsync(notifications) .ContinueWith(x => _unitOfWork.Complete()); foreach (var notification in notifications) { foreach (var device in notification.Devices) { await _pushNotificationService.SendAsync(device.DeviceToken, new FcmPayloadNotification { Notification = new FcmNotification { Title = notification.Title, Body = notification.Content }, Data = new FcmDataNotification { Id = notification.Id.ToString(), Image = notification.Image, NotificationDate = notification.NotificationDate.ToString("yyyy-MM-ddTHH:mm:ssZ"), AppointmentId = notification.AppointmentId.ToString() } }); } } } } catch (System.Exception) { throw; } }
public async Task SendNotification(PushNotificationModel notification) { await _pushNotificationService.SendAsync(notification); }
/// <inheritdoc /> public async Task <TotpResult> Send(ClaimsPrincipal principal, string message, TotpDeliveryChannel channel = TotpDeliveryChannel.Sms, string purpose = null, string securityToken = null, string phoneNumberOrEmail = null) { var totpResult = ValidateParameters(principal, securityToken, phoneNumberOrEmail); if (!totpResult.Success) { return(totpResult); } User user = null; var hasPrincipal = principal != null; if (hasPrincipal) { user = await _userManager.GetUserAsync(principal); if (user?.PhoneNumberConfirmed == false || string.IsNullOrEmpty(user?.PhoneNumber)) { return(TotpResult.ErrorResult(_localizer["Cannot send SMS. User's phone number is not verified."])); } } purpose ??= TotpConstants.TokenGenerationPurpose.StrongCustomerAuthentication; var token = string.Empty; var hasSecurityToken = !string.IsNullOrEmpty(securityToken); if (hasSecurityToken) { var modifier = GetModifier(purpose, phoneNumberOrEmail); var encodedToken = Encoding.Unicode.GetBytes(securityToken); token = _rfc6238AuthenticationService.GenerateCode(encodedToken, modifier).ToString("D6", CultureInfo.InvariantCulture); } if (hasPrincipal) { token = await _userManager.GenerateUserTokenAsync(user, TokenOptions.DefaultPhoneProvider, purpose); } var userName = user?.UserName ?? "Anonymous"; var cacheKey = $"totp{(hasPrincipal ? $":{user.Id}" : string.Empty)}:{channel}:{token}:{purpose}"; if (await CacheKeyExists(cacheKey)) { _logger.LogInformation($"User: '******' - Last token has not expired yet. Throttling."); return(TotpResult.ErrorResult(_localizer["Last token has not expired yet. Please wait a few seconds and try again."])); } _logger.LogInformation($"User: '******' - Token generated successfully."); switch (channel) { case TotpDeliveryChannel.Sms: case TotpDeliveryChannel.Viber: var smsService = _smsServiceFactory.Create(channel.ToString()); await smsService.SendAsync(user?.PhoneNumber ?? phoneNumberOrEmail, _localizer["OTP"], _localizer[message, token]); break; case TotpDeliveryChannel.Email: case TotpDeliveryChannel.Telephone: case TotpDeliveryChannel.EToken: throw new NotSupportedException($"EToken delivery channel {channel} is not implemented."); case TotpDeliveryChannel.PushNotification: if (_pushNotificationService == null) { throw new ArgumentNullException(nameof(_pushNotificationService), $"Cannot send push notification since there is no implementation of {nameof(IPushNotificationService)}."); } await _pushNotificationService.SendAsync(_localizer[message, token], token, user.Id); break; default: break; } await AddCacheKey(cacheKey); return(TotpResult.SuccessResult); }