public async Task <List <AndroidNotification> > Send(IEnumerable <AndroidToken> androidTokens, Notification notification, object data, ILogger logger) { List <AndroidNotification> responseList = new List <AndroidNotification>(); AndroidTokenRepository androidTokenRepository = new AndroidTokenRepository(); AndroidNotificationRepository androidNotificationRepository = new AndroidNotificationRepository(); foreach (var androidToken in androidTokens) { AndroidNotification androidNotification = new AndroidNotification { TokenId = androidToken.Id, NotificationId = notification.Id }; try { await SendPushAndroidAsync(androidNotification, notification, androidToken, data, androidTokenRepository); } finally { responseList.Add(androidNotification); try { await androidNotificationRepository.CreateNotification(androidNotification); } catch (Exception ex) { logger.LogError(ex.Message); } } } return(responseList); }
public async Task <IActionResult> Create( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "AndroidTokens")] [RequestBodyType(typeof(AndroidToken), "Criar um novo token")] HttpRequest request, ILogger logger) { try { AndroidTokenRepository androidTokenRepository = new AndroidTokenRepository(); string requestBody = await new StreamReader(request.Body).ReadToEndAsync(); var input = JsonConvert.DeserializeObject <AndroidToken>(requestBody); input.ApplicationId = 2; var validator = new AndroidTokenValidator(); var validationResult = validator.Validate(input); if (!validationResult.IsValid) { return(new BadRequestObjectResult(validationResult.Errors.Select(e => new { Field = e.PropertyName, Error = e.ErrorMessage }))); } var notification = await androidTokenRepository.GetNotificationByKey(input.Id, input.CompanyId, input.UserId, input.ApplicationId); if (notification != null) { if (notification.DeletedAt != null) { notification.DeletedAt = null; await androidTokenRepository.UpdateNotification(notification); } return(new OkResult()); } else if (await androidTokenRepository.CreateNotification(input) == 1) { return(new OkResult()); } return(new BadRequestObjectResult("Token não foi gravado, favor enviar os dados corretamente.")); } catch (Exception ex) { logger.LogError(ex.Message); return(new BadRequestObjectResult(ex.Message)); } }
public async Task <IActionResult> GetTokens( [HttpTrigger(AuthorizationLevel.Function, "get", Route = "AndroidTokens")] HttpRequest request, ILogger logger) { try { AndroidTokenRepository androidTokenRepository = new AndroidTokenRepository(); return(new OkObjectResult(await androidTokenRepository.GetNotifications())); } catch (Exception ex) { logger.LogError(ex.Message); return(new BadRequestObjectResult(ex.Message)); } }
public async Task <IActionResult> Create( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "v1/AndroidTokens")] [RequestBodyType(typeof(AndroidToken), "Criar um novo token")] HttpRequest request, ILogger logger) { try { var form = await request.GetJsonBody <AndroidToken, AndroidTokenValidator>(); if (!form.IsValid) { logger.LogInformation($"Invalid form data."); return(form.ToBadRequest()); } var input = form.Value; AndroidTokenRepository androidTokenRepository = new AndroidTokenRepository(); var notification = await androidTokenRepository.GetNotificationByKey(input.Id, input.CompanyId, input.UserId, input.ApplicationId); if (notification != null) { if (notification.DeletedAt != null) { notification.DeletedAt = null; await androidTokenRepository.UpdateNotification(notification); } return(new OkResult()); } else if (await androidTokenRepository.CreateNotification(input) == 1) { return(new OkResult()); } return(new BadRequestObjectResult("Token não foi gravado, favor enviar os dados corretamente.")); } catch (Exception ex) { logger.LogError(ex.Message); return(new BadRequestObjectResult(ex.Message)); } }
private async Task SendPushAndroidAsync(AndroidNotification androidNotification, Notification notification, AndroidToken androidToken, object data, AndroidTokenRepository androidTokenRepository) { dynamic model = new ExpandoObject(); if (data != null) { model = data; model.UserId = androidToken.UserId; model.CompanyId = androidToken.CompanyId; } //Analisar necessidade de setar a messagem em mais atributos //string alert; string body = notification.Message; string title = notification.Title; string to = androidNotification.TokenId; //int badge = 1; //string sound = "default"; //string vibrate = "true"; // Get the server key from FCM console var serverKey = string.Format("key={0}", Config.GetEnvironmentVariable("Firebase_ServerKey")); // Get the sender id from FCM console var senderId = string.Format("id={0}", Config.GetEnvironmentVariable("Firebase_SenderId")); object payLoad; if (data is null) { payLoad = new { to, notification = new { title, body } }; } else { payLoad = new { to, notification = new { title, body }, data = new { model } }; } var client = new RestClient("https://fcm.googleapis.com/fcm/send"); var request = new RestSharp.RestRequest(Method.POST); IRestResponse response; request.JsonSerializer = new NewtonsoftJsonSerializer(); request.RequestFormat = DataFormat.Json; request.AddHeader("Authorization", serverKey); request.AddHeader("Sender", senderId); request.AddHeader("Content-Type", "application/json"); request.AddJsonBody(payLoad); response = client.Execute(request); try { FcmResponse resposta = new FcmResponse(); resposta = JsonConvert.DeserializeObject <FcmResponse>(response.Content); if (resposta.Results != null && resposta.Results.Count() > 0) { androidNotification.Message_Id = resposta.Results.FirstOrDefault().Message_id; } androidNotification.Multicast_Id = resposta.Multicast_id; androidNotification.Success = resposta.Success; if (androidNotification.Success == 0) { try { androidToken.DeletedAt = DateTime.UtcNow; await androidTokenRepository.UpdateNotification(androidToken); } catch { } } } catch (Exception) { androidToken.DeletedAt = DateTime.UtcNow; await androidTokenRepository.UpdateNotification(androidToken); } }
public async Task <IActionResult> Send( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "v1/Notifications")] [RequestBodyType(typeof(SendNotification), "Enviar push notification")] HttpRequest request, ILogger logger, Microsoft.Azure.WebJobs.ExecutionContext context) { try { var form = await request.GetJsonBody <SendNotification, SendNotificationValidator>(); if (!form.IsValid) { logger.LogInformation($"Invalid form data."); return(form.ToBadRequest()); } var input = form.Value; AndroidTokenRepository androidTokenRepository = new AndroidTokenRepository(); IOSTokenRepository iOSTokenRepository = new IOSTokenRepository(); IOSNotificationRepository iOSNotificationRepository = new IOSNotificationRepository(); NotificationRepository notificationRepository = new NotificationRepository(); AndroidNotificationService androidNotificationService = new AndroidNotificationService(); var androidTokens = await androidTokenRepository.GetNotificationByUsers(input.UserIds, input.CompanyId, input.ApplicationId); var iOSTokens = await iOSTokenRepository.GetNotificationByUsers(input.UserIds, input.CompanyId); if (androidTokens.Count() < 1 && iOSTokens.Count() < 1) { return(new BadRequestObjectResult("Nenhum usuário cadastrado.")); } Notification notification = new Notification { ApplicationId = input.ApplicationId, Title = input.Title, Message = input.Message }; notification.Id = await notificationRepository.CreateNotification(notification); var responseList = await androidNotificationService.Send(androidTokens, notification, input.Data, logger); //Adicionar código quando tiver algo do IOS //List<IOSNotification> responseListIOS = new List<IOSNotification>(); //foreach (var iOSToken in iOSTokens) //{ // IOSNotification iOSNotification = new IOSNotification // { // TokenId = iOSToken.Id, // NotificationId = notification.Id // }; // try // { // await SendPushIOSAsync(iOSNotification, notification, iOSToken, input.Data, context); // } // finally // { // responseListIOS.Add(iOSNotification); // try // { // await iOSNotificationRepository.CreateNotification(iOSNotification); // } // catch (Exception ex) // { // logger.LogError(ex.Message); // } // } //} return(new OkObjectResult(responseList)); } catch (Exception ex) { logger.LogError(ex.Message); return(new BadRequestObjectResult(ex.Message)); } }
public async Task <IActionResult> Send( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "Notifications")] [RequestBodyType(typeof(SendNotification), "Enviar push notification")] HttpRequest request, ILogger logger, Microsoft.Azure.WebJobs.ExecutionContext context) { try { string requestBody = await new StreamReader(request.Body).ReadToEndAsync(); var input = JsonConvert.DeserializeObject <SendNotification>(requestBody); input.ApplicationId = 2; var validator = new SendNotificationValidator(); var validationResult = validator.Validate(input); if (!validationResult.IsValid) { return(new BadRequestObjectResult(validationResult.Errors.Select(e => new { Field = e.PropertyName, Error = e.ErrorMessage }))); } AndroidTokenRepository androidTokenRepository = new AndroidTokenRepository(); IOSTokenRepository iOSTokenRepository = new IOSTokenRepository(); IOSNotificationRepository iOSNotificationRepository = new IOSNotificationRepository(); NotificationRepository notificationRepository = new NotificationRepository(); AndroidNotificationService androidNotificationService = new AndroidNotificationService(); var androidTokens = await androidTokenRepository.GetNotificationByUsers(input.UserIds, input.CompanyId, input.ApplicationId); var iOSTokens = await iOSTokenRepository.GetNotificationByUsers(input.UserIds, input.CompanyId); if (androidTokens.Count() < 1 && iOSTokens.Count() < 1) { return(new BadRequestObjectResult("Nenhum usuário cadastrado.")); } Notification notification = new Notification { ApplicationId = input.ApplicationId, Title = input.Title, Message = input.Message }; notification.Id = await notificationRepository.CreateNotification(notification); var responseList = await androidNotificationService.Send(androidTokens, notification, input.Data, logger); //Adicionar código quando tiver algo do IOS //List<IOSNotification> responseListIOS = new List<IOSNotification>(); //foreach (var iOSToken in iOSTokens) //{ // IOSNotification iOSNotification = new IOSNotification // { // TokenId = iOSToken.Id, // NotificationId = notification.Id // }; // try // { // await SendPushIOSAsync(iOSNotification, notification, iOSToken, input.Data, context); // } // finally // { // responseListIOS.Add(iOSNotification); // try // { // await iOSNotificationRepository.CreateNotification(iOSNotification); // } // catch (Exception ex) // { // logger.LogError(ex.Message); // } // } //} return(new OkObjectResult(responseList)); } catch (Exception ex) { logger.LogError(ex.Message); return(new BadRequestObjectResult(ex.Message)); } }