Ejemplo n.º 1
0
        public async Task <IActionResult> CallShooter(CallShooterRequest request)
        {
            // For a real application, generate your own
            var currentUserId = PlatformUtils.GetIdentityUserId(User);
            var existingUser  = AuthorizationLayer.GetUserById(currentUserId);

            if (existingUser == null)
            {
                return(NotFound());
            }

            var subscriptions = BasicLayer.FetchNotificationSubscriptionsByUserId(request.ShooterId);

            var vapidDetails = new VapidDetails($"mailto:{_vapidUser}", _publicKey, _privateKey);


            var pushSubscriptions = subscriptions.Select(x => new PushSubscription(x.Url, x.P256dh, x.Auth)).ToList();
            var webPushClient     = new WebPushClient();

            try
            {
                var message = string.Empty;
                switch ((int)request.Context)
                {
                case (int)CallShooterContextEnum.MatchDirector:
                    var userStage = BasicLayer.GetSOStage(request.MatchId, existingUser.Id);
                    message = $"{existingUser.FirstName} {existingUser.LastName} ti sta cercando allo stage {userStage.Index}:{userStage.Name}!";
                    break;

                default:
                    message = $"{existingUser.FirstName} {existingUser.LastName} ti sta cercando!";
                    break;
                }
                var payload = JsonSerializer.Serialize(new
                {
                    message,
                    url = string.Empty,
                });
                if (pushSubscriptions.Count == 0)
                {
                    return(Ok(new OkResponse {
                        Status = false, Errors = new List <string> {
                            "NoSubscriptions"
                        }
                    }));
                }
                var tasks = pushSubscriptions.Select(pushSubscription => webPushClient.SendNotificationAsync(pushSubscription, payload, vapidDetails)).ToList();
                await Task.WhenAll(tasks);

                return(Ok(new OkResponse()
                {
                    Status = true
                }));
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Error sending push notification: " + ex.Message);
                return(Ok(ex));
            }
        }