Esempio n. 1
0
        public async Task SendAsync(CreateSendRequest model, IValidator <CreateSendRequest> validator)
        {
            ValidateAndThrow(model, validator);

            var sendRequests = new List <SendRequest>();

            foreach (int recipientId in model.RecipientsIds)
            {
                var(canSend, alreadySent) = CheckSendRequest(model.RecipeId, recipientId, model.UserId);
                if (!canSend || alreadySent)
                {
                    continue;
                }

                var recipeSendRequest = new SendRequest
                {
                    UserId   = recipientId,
                    RecipeId = model.RecipeId
                };
                sendRequests.Add(recipeSendRequest);
            }

            var now = DateTime.UtcNow;

            foreach (SendRequest request in sendRequests)
            {
                request.CreatedDate = request.ModifiedDate = now;
            }

            await _recipesRepository.CreateSendRequestsAsync(sendRequests);
        }
        public async Task <IActionResult> Send([FromBody] CreateSendRequest dto)
        {
            if (dto == null)
            {
                return(BadRequest());
            }

            try
            {
                dto.UserId = IdentityHelper.GetUserId(User);
            }
            catch (UnauthorizedAccessException)
            {
                return(Unauthorized());
            }

            await _recipeService.SendAsync(dto, _createSendRequestValidator);

            // Notify
            var usersToBeNotified = await _userService.GetToBeNotifiedOfRecipeSentAsync(dto.RecipeId);

            if (usersToBeNotified.Any())
            {
                var currentUser = await _userService.GetAsync(dto.UserId);

                RecipeToNotify recipe = await _recipeService.GetAsync(dto.RecipeId);

                foreach (var user in usersToBeNotified)
                {
                    CultureInfo.CurrentCulture = new CultureInfo(user.Language, false);
                    var message = _localizer["SentRecipeNotification", IdentityHelper.GetUserName(User), recipe.Name];

                    var pushNotification = new PushNotification
                    {
                        SenderImageUri = currentUser.ImageUri,
                        UserId         = user.Id,
                        Application    = "Cooking Assistant",
                        Message        = message,
                        OpenUrl        = $"{_urls.CookingAssistant}/inbox"
                    };

                    _senderService.Enqueue(pushNotification);
                }
            }

            return(StatusCode(201, null));
        }