コード例 #1
0
        public async Task GivenInvalidType_ReturnException()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            // init DB for test
            var context     = _factory.InitializeDbForTests();
            var validUserId = new Guid("66EDB7C7-11BF-40A5-94AB-75A3364FEF60");
            var command     = new CreateNotificationCommand()
            {
                MessageContent = "message 2 @USER2",
                ConversationId = "b73477a4-f61d-46fa-873c-7d71c01dfbdf",
                MessageId      = "b73477a4-f61d-46fa-873c-7d71c01dfbdf",
                RegUserName    = "******",
                isRead         = false,
                ToUser         = new List <UserModel>()
                {
                    new UserModel {
                        UserId = new Guid("66edb7c7-11bf-40a5-94ab-75a3364fef60"), DisplayName = "USER2"
                    }
                },
                Type = "123ABC"
            };
            var content = IntegrationTestHelper.GetRequestContent(command);

            var response = await client.PostAsync($"/api/Notifications/", content);

            response.StatusCode.ShouldBe(System.Net.HttpStatusCode.InternalServerError);

            // release DB
            _factory.DisposeDbForTests(context);
        }
コード例 #2
0
        public async Task <AuthResponse> Login(AuthRequest authRequest)
        {
            _logger.LogInformation("Login Request", authRequest.Email, authRequest.Organization, authRequest.Source);

            var login = await _authRepository.Login(authRequest.Email, authRequest.Password, authRequest.Organization);

            DateTime expireDate;
            var      fullName     = login.FirstName + " " + (!String.IsNullOrEmpty(login.MiddleName) ? login.MiddleName + " " : "") + login.LastName;
            var      token        = this.GenerateToken(login, out expireDate, fullName);
            var      authResponse = new AuthResponse()
            {
                Email     = login.Email,
                FullName  = fullName,
                idToken   = token,
                localId   = login.Id.ToString(),
                Mobile    = "",
                expiresIn = expireDate.Subtract(DateTime.Now).Milliseconds,
                Role      = ((UserRoleType)login.Role).ToString()
            };

            var createNotificationCommand = new CreateNotificationCommand(
                "Successful login",
                "Successful login for " + login.Email, login.Email, "IStudent",
                new List <string>(),
                null
                );

            await _bus.SendCommand(createNotificationCommand);

            return(authResponse);
        }
コード例 #3
0
        public async Task CreateNotificationAsync(CreateNotificationCommand createNotificationCommand, CancellationToken cancellationToken)
        {
            Notification notification = new Notification(createNotificationCommand.NotificationCorrelationId,
                                                         createNotificationCommand.Username,
                                                         createNotificationCommand.NotificationTitle,
                                                         createNotificationCommand.NotificationContent,
                                                         createNotificationCommand.OperationDate);

            var notificationRepository = _repositoryFactory.Generate <INotificationRepository>();

            try
            {
                await notificationRepository.GetNotificationAsync(createNotificationCommand.Username, createNotificationCommand.NotificationCorrelationId, cancellationToken);

                throw new NotificationAlreadyExistException(createNotificationCommand.NotificationCorrelationId);
            }
            catch (NotFoundException <Notification> )
            {
                // continue
            }

            await notificationRepository.AddAsync(notification, cancellationToken);

            try
            {
                await _busControl.Publish(new NotificationCreatedEvent(notification.CorrelationId.ToString(), notification.Username.ToString(), notification.Title.ToString(), notification.Content.ToString(), notification.OperationDate, notification.IsSeen), cancellationToken);
            }
            catch (Exception)
            {
                // Exception is swallowed
            }
        }
コード例 #4
0
        public async Task <Unit> Handle(FollowUserCommand request, CancellationToken cancellationToken)
        {
            var entity = _mapper.Map <Following>(request);

            _context.Followings.Add(entity);

            if (await _context.SaveChangesAsync(cancellationToken) > 0)
            {
                var setting = _context.UserNotificationSettings
                              .Where(x => x.UserId == entity.FollowerId)
                              .FirstOrDefault()
                              .UserFollowings;

                if (setting)
                {
                    if (entity.FollowerId != entity.UserId)
                    {
                        var command = new CreateNotificationCommand
                        {
                            UserId           = entity.FollowerId,
                            RecipientId      = entity.UserId,
                            NotificationType = NotificationType.UserFollowing
                        };

                        await _mediator.Send(command);
                    }
                }
            }

            return(Unit.Value);
        }
コード例 #5
0
 public ChangeDepartmentCommand(IUserInfoProvider userInfoProvider, IRepository <User> userRepository, IRepository <Department> departmentRepository, CreateNotificationCommand createNotificationCommand)
 {
     this.userRepository            = userRepository;
     this.departmentRepository      = departmentRepository;
     this.createNotificationCommand = createNotificationCommand;
     this.userInfoProvider          = userInfoProvider;
 }
コード例 #6
0
        public async Task GivenValidRequest_ShouldCreateNotification()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            // init DB for test
            var context     = _factory.InitializeDbForTests();
            var validUserId = new Guid("66EDB7C7-11BF-40A5-94AB-75A3364FEF60");
            var command     = new CreateNotificationCommand()
            {
                MessageContent = "message 2 @USER2",
                ConversationId = Guid.NewGuid().ToString(),
                MessageId      = Guid.NewGuid().ToString(),
                RegUserName    = "******",
                isRead         = false,
                ToUser         = new List <UserModel>()
                {
                    new UserModel {
                        UserId = new Guid("66edb7c7-11bf-40a5-94ab-75a3364fef60"), DisplayName = "USER2"
                    }
                },
                Type = "Mention"
            };
            var content = IntegrationTestHelper.GetRequestContent(command);

            var response = await client.PostAsync($"/api/Notifications/", content);

            response.EnsureSuccessStatusCode();

            // release DB
            _factory.DisposeDbForTests(context);
        }
コード例 #7
0
        public async Task <CommandExecutionResult> HandleAsync(CreateNotificationCommand command)
        {
            var notificationEntity = command.Adapt <NotificationEntity>();

            await _repository.InsertAsync(notificationEntity);

            return(CommandExecutionResult.Success);
        }
コード例 #8
0
 public NotificationsController(GetNewNotificationsQuery getNewNotificationsQuery, CheckForNewNotificationsQuery checkForNewNotificationsQuery, CreateNotificationCommand createNotificationCommand, MarkNotificationAsSeenCommand markNotificationAsSeenCommand, GetNotificationsQuery getNotificationsQuery, TaskExecutor.TaskExecutor taskExecutor)
 {
     this.getNotificationsQuery         = getNotificationsQuery;
     this.getNewNotificationsQuery      = getNewNotificationsQuery;
     this.createNotificationCommand     = createNotificationCommand;
     this.markNotificationAsSeenCommand = markNotificationAsSeenCommand;
     this.checkForNewNotificationsQuery = checkForNewNotificationsQuery;
     this.taskExecutor = taskExecutor;
 }
コード例 #9
0
        public async Task Handle(OrderShipped notification, CancellationToken cancellationToken)
        {
            var createNotificationCommand = new CreateNotificationCommand {
                Title = "تم شجن الطلب", Content = "تم شحن الطلب الخاص بك", EntityId = notification.Order.Id.ToString(), NotificationType = 0, CustomerId = notification.Order.CustomerId
            };

            await _mediator.Send(createNotificationCommand);

            _logger.LogInformation("Brimo API EventHandelr: {Name} {@UserId} {@UserName} {@Request}", nameof(OrderShipped), _currentUserService.UserId, _currentUserService.Name, notification);
        }
コード例 #10
0
        public ActionResult Create(CreateNotificationCommand command)
        {
            if (ModelState.IsValid)
            {
                var result = _commandBus.Send(command);
                return(JsonMessage(result));
            }

            return(View("Create"));
        }
コード例 #11
0
 private async Task SendCreateNotificationCommandAsync(CreateNotificationCommand createNotificationCommand)
 {
     try
     {
         await _notificationService.CreateNotificationAsync(createNotificationCommand, CancellationToken.None);
     }
     catch (NotificationAlreadyExistException)
     {
         // continue
     }
 }
コード例 #12
0
        public async Task GiveWrongType_ShouldRaiseNotTypeExceptionAsync()
        {
            var sut = new CreateNotificationCommandHandler(_context, _mapper);

            var command = new CreateNotificationCommand()
            {
                Type = "WRONG TYPE"
            };

            await Should.ThrowAsync <NotTypeException>(() =>
                                                       sut.Handle(command, CancellationToken.None));
        }
コード例 #13
0
        public async Task Consume(ConsumeContext <OrderShippedEvent> context)
        {
            OrderShippedEvent orderShippedEvent = context.Message;

            NotificationCorrelationId notificationCorrelationId = new NotificationCorrelationId($"{orderShippedEvent.Username}-{orderShippedEvent.OrderId}-{orderShippedEvent.ShipmentId}");
            Username            username            = new Username(orderShippedEvent.Username);
            NotificationTitle   notificationTitle   = new NotificationTitle($"Order Shipped");
            NotificationContent notificationContent = new NotificationContent($"#{orderShippedEvent.OrderId} order is shipped at {orderShippedEvent.ShipmentDate}");

            CreateNotificationCommand createNotificationCommand = new CreateNotificationCommand(notificationCorrelationId, username, notificationTitle, notificationContent, orderShippedEvent.ShipmentDate);

            await SendCreateNotificationCommandAsync(createNotificationCommand);
        }
コード例 #14
0
 public bool Create(CreateNotificationCommand command)
 {
     _beawreContext.Relationship.Add(new Relationship()
     {
         FromType = ObjectType.User,
         ToType   = ObjectType.Notification,
         FromId   = command.UserId.FirstOrDefault(),
         ToId     = Guid.Empty,
         Payload  = JsonConvert.SerializeObject(command.Payload)
     });
     _beawreContext.SaveChanges();
     return(true);
 }
コード例 #15
0
        public async Task <IActionResult> GetNavbarAsync([FromServices] IUnitOfWorkFactory unitOfWorkFactory,
                                                         [FromServices] ICommandHandlerDispatcher commandHandlerDispatcher,
                                                         [FromServices] IQueryHandlerDispatcher queryHandlerDispatcher)
        {
            var unitOfWork = unitOfWorkFactory.Create();

            var cmd = new CreateNotificationCommand("xact", "notif-" + Guid.NewGuid().ToString(), 1, "subject1", "content1", "reference1", DateTime.UtcNow);

            commandHandlerDispatcher.Handle(cmd);

            var query = new GetUnreadNotificationReceiversByUserIdQuery("xact", "system-administrator", "", 1, 10, "", true);
            var dto   = queryHandlerDispatcher.Handle <GetUnreadNotificationReceiversByUserIdQuery, PaginatedNotificationReceiverDto>(query);


            //var items = await notificationService.GetUnreadNotificationsAsync(UserId);
            //var notifications = items.OrderByDescending(p => p.Notification.DateSent).Take(15).ToList();

            ////var items2 = await messageService.GetUnreadMessagesAsync(UserId);
            ////var msgHeaders = items2.Take(15).ToList();

            //var chats = await appDbContext
            //    .ChatReceiverMessages
            //    .Include(p => p.ChatMessage)
            //        .ThenInclude(p => p.Sender)
            //            .ThenInclude(p => p.User)
            //    //.Include(p => p.ChatReceiver)
            //    .Where(p => p.ChatReceiver.ReceiverId == UserId && p.IsRead == false)
            //    .Take(15)
            //    .ToListAsync();

            ////  trigger populate
            ////var chatReceivers = await appDbContext
            ////    .ChatReceivers
            ////    .Where(p => p.ReceiverId == UserId)
            ////    .ToListAsync();


            //var model = new NavbarInfo
            //{
            //    Username = User.Identity.Name,
            //    NotificationReceivers = notifications,
            //    MessageReceiverMessages = chats
            //};


            //return Ok(model);
            unitOfWork.Commit();

            return(Ok(dto));
        }
コード例 #16
0
        public async Task <BaseDto <NotifInput> > Handle(CreateNotificationCommand request, CancellationToken cancellationToken)
        {
            var recieved = BackgroundJob.Enqueue(() => Subscriber.Recieved());

            var Data = request.data.attributes;

            // Add Notification Data
            var notificationData = new Notification_Model
            {
                title   = Data.title,
                message = Data.message
            };

            _context.notifications.Add(notificationData);
            await _context.SaveChangesAsync(cancellationToken);

            // Get Id for notification_id in notification logs
            var Id = await _context.notifications.ToListAsync();

            var userData = await _context.users.FindAsync(Data.from);

            // Add Notification Log Data
            foreach (var logs in Data.targets)
            {
                _context.notificationLogs.Add(new NotificationLogs
                {
                    notification_id   = Id.Last().id,
                    type              = Data.type,
                    from              = Data.from,
                    target            = logs.id,
                    email_destination = logs.email_destination
                });
                await _context.SaveChangesAsync();

                if (logs.email_destination != null)
                {
                    BackgroundJob.Enqueue(() => EmailSender.Send(notificationData.title, notificationData.message, userData.address, userData.name, logs.email_destination));
                }

                BackgroundJob.Enqueue(() => FCM.SendAsync(notificationData.title, notificationData.message));
            }

            return(new BaseDto <NotifInput>
            {
                message = "Success add Notification Data",
                success = true,
                data = Data
            });
        }
コード例 #17
0
        public async Task GiveValidRequest_ShouldCreateNotification1()
        {
            var sut = new CreateNotificationCommandHandler(_context, _mapper);
            List <UserModel> toUserList = new List <UserModel>();

            toUserList.AddRange(new[]
            {
                new UserModel
                {
                    DisplayName = "User1",
                    UserId      = userId1
                },
                new UserModel
                {
                    DisplayName = "User2",
                    UserId      = userId2
                }
            });

            var command = new CreateNotificationCommand()
            {
                Type             = "Mention",
                ConversationId   = conversationId.ToString(),
                isRead           = false,
                MessageContent   = "@User -> test",
                MessageId        = "",
                TeamId           = teamId1.ToString(),
                RegUserId        = "",
                ToUser           = toUserList,
                ConversationName = "",
                URL = ""
            };

            await sut.Handle(command, CancellationToken.None);

            var result = _context.Notifications.Where(q => q.MessageContent == "@User -> test").ToList();

            result.ShouldNotBeNull();
            result.Count.ShouldBe(toUserList.Count());
            foreach (Notification nfc in result)
            {
                nfc.Type.ShouldBe("Mention");
                nfc.TeamId.ShouldBe(teamId1.ToString());
                nfc.isRead.ShouldBeFalse();
                nfc.Title.ShouldContain("mentioned you in a channel");
            }
        }
コード例 #18
0
        public void NotifyNewAssignment(int cardId, string sender, string recipient)
        {
            var  repository = DependencyResolver.Current.GetService <IRedfernRepository>();
            Card card       = repository.Cards.Where(c => c.CardId == cardId).SingleOrDefault();
            CreateNotificationCommand command = new CreateNotificationCommand
            {
                SenderUser        = sender,
                RecipientUser     = recipient,
                Message           = "assigned you a card",
                NotificationType  = NotificationType.AssignCard,
                ObjectType        = "card",
                ObjectId          = String.Format("BoardId={0};CardId={1}", card.BoardId.ToString(), card.CardId.ToString()),
                ObjectDescription = card.Title
            };
            var result = repository.ExecuteCommand(command);

            Clients.Group(recipient).notify(AutoMapper.Mapper.Map <Notification, NotificationViewModel>(result.Data));
        }
コード例 #19
0
        public async Task <Unit> Handle(CreateCommentLikeCommand request, CancellationToken cancellationToken)
        {
            var entity = _mapper.Map <CommentLike>(request);

            entity.UserId = int.Parse(_userService.GetUserId());

            _context.CommentLikes.Add(entity);

            if (await _context.SaveChangesAsync(cancellationToken) > 0)
            {
                var item = _context.CommentLikes
                           .Where(x => x.CommentId == entity.CommentId && x.UserId == entity.UserId)
                           .FirstOrDefault();

                await _wallService.SendCommentLike(entity.UserId, item.Id, item.CommentId);

                var recipientId = _context.Comments.Find(entity.CommentId)?.UserId;

                if (recipientId != null)
                {
                    var setting = _context.UserNotificationSettings
                                  .Where(x => x.UserId == recipientId)
                                  .FirstOrDefault()
                                  .CommentLikes;

                    if (setting)
                    {
                        if (entity.UserId != recipientId)
                        {
                            var command = new CreateNotificationCommand
                            {
                                UserId           = entity.UserId,
                                RecipientId      = recipientId.Value,
                                NotificationType = NotificationType.CommentLike
                            };

                            await _mediator.Send(command);
                        }
                    }
                }
            }

            return(Unit.Value);
        }
コード例 #20
0
        public void NotifyNewCommentPosted(int cardId, string sender)
        {
            var  repository = DependencyResolver.Current.GetService <IRedfernRepository>();
            Card card       = repository.Get <Card>(cardId);

            //send a notification to card assignee that a new comment has been posted
            if (!String.IsNullOrEmpty(card.AssignedToUser) && card.AssignedToUser != sender)
            {
                CreateNotificationCommand command = new CreateNotificationCommand
                {
                    SenderUser        = sender,
                    RecipientUser     = card.AssignedToUser,
                    Message           = "posted comment to your card.",
                    NotificationType  = NotificationType.NewCommentPosted,
                    ObjectType        = "card",
                    ObjectId          = String.Format("BoardId={0};CardId={1}", card.BoardId.ToString(), card.CardId.ToString()),
                    ObjectDescription = card.Title
                };
                var result = repository.ExecuteCommand(command);
                Clients.Group(card.AssignedToUser).notify(AutoMapper.Mapper.Map <Notification, NotificationViewModel>(result.Data));
            }
        }
コード例 #21
0
        public async Task <BaseDto <NotifInput> > Handle(CreateNotificationCommand request, CancellationToken cancellationToken)
        {
            var Data = request.data.attributes;

            // Add Notification Data
            var notificationData = new Notification_Model
            {
                title   = Data.title,
                message = Data.message
            };

            _context.notifications.Add(notificationData);
            await _context.SaveChangesAsync(cancellationToken);

            // Get Id for notification_id in notification logs
            var Id = await _context.notifications.ToListAsync();

            // Add Notification Log Data
            foreach (var logs in Data.targets)
            {
                _context.notificationLogs.Add(new NotificationLogs
                {
                    notification_id   = Id.Last().id,
                    type              = Data.type,
                    from              = Data.from,
                    target            = logs.id,
                    email_destination = logs.email_destination
                });
                await _context.SaveChangesAsync();
            }

            return(new BaseDto <NotifInput>
            {
                message = "Success add Notification Data",
                success = true,
                data = Data
            });
        }
コード例 #22
0
        public async Task <Unit> Handle(UnfollowUserCommand request, CancellationToken cancellationToken)
        {
            var entity = _context.Followings
                         .Where(x => x.UserId == request.UserId && x.FollowerId == request.FollowerId)
                         .FirstOrDefault();

            if (entity == null)
            {
                throw new NotFoundException(nameof(Following), $"UserId: { request.UserId }, FollowerId: { request.FollowerId }");
            }

            _context.Followings.Remove(entity);

            if (await _context.SaveChangesAsync(cancellationToken) > 0)
            {
                var setting = _context.UserNotificationSettings
                              .Where(x => x.UserId == entity.FollowerId)
                              .FirstOrDefault()
                              .UserFollowings;

                if (setting)
                {
                    if (entity.FollowerId != entity.UserId)
                    {
                        var command = new CreateNotificationCommand
                        {
                            UserId           = entity.FollowerId,
                            RecipientId      = entity.UserId,
                            NotificationType = NotificationType.UserUnfollowing
                        };

                        await _mediator.Send(command);
                    }
                }
            }

            return(Unit.Value);
        }
コード例 #23
0
        public async Task <IActionResult> CreateNotification(CreateNotificationCommand cmd)
        {
            var notificationId = await _commandDispatcher.SendAsync(cmd);

            return(Created($"notifications/{notificationId}", notificationId));
        }
コード例 #24
0
        public async Task <ActionResult <NotificationCreatedDto> > CreateNotificationAsync([FromBody] CreateNotificationCommand command)
        {
            var result = await Mediator.Send(command);

            if (result.Errors.Any(e => e is StatusProviderNotSupportedError))
            {
                return(new MessageResult(400, "Requested status provider is not supported."));
            }

            if (result.Errors.Any(e => e is UnavailableError))
            {
                return(new MessageResult(503, "Discord API is currently unavailable. Please try again later."));
            }

            if (result.Errors.Any(e => e is WrongCodeError))
            {
                return(new MessageResult(400, "Wrong Discord OAuth2 code provided."));
            }

            throw new NotImplementedException();
        }
コード例 #25
0
        public async Task <IActionResult> PostAsync(CreateNotificationCommand data)
        {
            var result = await _mediatr.Send(data);

            return(Ok(result));
        }
コード例 #26
0
        public async Task <ActionResult> Create(CreateNotificationCommand command)
        {
            await Mediator.Send(command);

            return(NoContent());
        }
コード例 #27
0
 public async Task <ActionResult <CreateNotificationCommandDto> > PostNotif(CreateNotificationCommand yo)
 {
     return(Ok(await _mediatr.Send(yo)));
 }
コード例 #28
0
 public IStatusProvider GetStatusProviderForCommand(CreateNotificationCommand command) => statusProviders.FirstOrDefault(prov => prov.DoesSupport(command.StatusProvider));
コード例 #29
0
 public bool CreateForUsers(CreateNotificationCommand command) => _mediator.Send(command).Result;
コード例 #30
0
 public async Task <IActionResult> Post([FromBody] CreateNotificationCommand payload)
 {
     return(Ok(await _mediator.Send(payload)));
 }