Beispiel #1
0
        public async Task Push(string message, NotificationType type = NotificationType.Other)
        {
            var notification = Notification.Create(message, httpContextReader.CurrentUserId, type);

            database.NotificationRepository.Add(notification);

            if (await database.Complete())
            {
                await hubManager.Invoke(SignalrActions.ON_NOTIFICATION_SENT, httpContextReader.CurrentUserId,
                                        mapper.Map <NotificationDto>(notification));
            }
        }
Beispiel #2
0
        public async Task <AddReportSubscriberResponse> Handle(AddReportSubscriberRequest request,
                                                               CancellationToken cancellationToken)
        {
            var report =
                await reportValidationHub.ValidateAndReturnReport(request.ReportId, ReportPermission.AddComment)
                ?? throw new NoPermissionsException(ErrorMessages.NotAllowedMessage);

            var addedReportSubscriber = await reportSubscriberService.AddSubscriber(report, request.UserId) ??
                                        throw new CrudException("Adding report subscriber failed");

            if (ReportStatusTypeSmartEnum.FromValue(report.Status)
                .ShouldBeOpened(report, httpContextReader.CurrentUserId))
            {
                await reportManager.ChangeStatus(ReportStatusType.Opened, report);
            }

            var notification = await notifier.Push(
                $"You were added to subscribers in report: {report.Subject}",
                request.UserId);

            await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, request.UserId,
                                    mapper.Map <NotificationDto>(notification));

            return((AddReportSubscriberResponse) new AddReportSubscriberResponse
            {
                ReportSubscriber = mapper.Map <ReportSubscriberDto>(addedReportSubscriber)
            }.LogInformation(
                       $"Assignee #{httpContextReader.CurrentUserId} has added subscriber #{request.UserId} in report #{report.Id}"));
        }
        public async Task <MoveReportAssignmentResponse> Handle(MoveReportAssignmentRequest request,
                                                                CancellationToken cancellationToken)
        {
            var report =
                await reportValidationHub.ValidateAndReturnReport(request.ReportId, ReportPermission.MoveAssignment)
                ?? throw new NoPermissionsException(ErrorMessages.NotAllowedMessage);

            if (!(await reportManager.GetReportsAllowedAssignees((ReportCategoryType)report.CategoryType,
                                                                 isPrivate: report.Private)).Any(a => a.Id == request.NewAssigneeId))
            {
                throw new NoPermissionsException(ErrorMessages.NotAllowedMessage);
            }

            if (await reportManager.MoveReportAssignment(report, request.NewAssigneeId))
            {
                var membersGroup = new List <int> {
                    report.CreatorId, request.NewAssigneeId
                };

                var notifications = await notifier.PushToGroup(
                    $"Report {report.Subject} assignment has been moved to another admin",
                    membersGroup);

                foreach (var memberId in membersGroup)
                {
                    await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, memberId,
                                            mapper.Map <IEnumerable <NotificationDto> >(notifications));
                }

                return((MoveReportAssignmentResponse) new MoveReportAssignmentResponse().LogInformation(
                           $"Assignee #{httpContextReader.CurrentUserId} move report #{report.Id} assignment to user #{request.NewAssigneeId}"));
            }

            throw new CrudException("Toggling private status of report failed");
        }
Beispiel #4
0
        public async Task <SetOrderApprovalStateResponse> Handle(SetOrderApprovalStateRequest request,
                                                                 CancellationToken cancellationToken)
        {
            var hasOrderReviewed =
                await orderService.SetOrderApprovalState(request.OrderId, request.ApprovalState, request.AdminNote);

            if (!hasOrderReviewed.IsSucceeded)
            {
                throw new PremiumOperationException("Setting approval state of order failed");
            }

            var notification = await notifier.Push(
                $"Approval state of order #{request.OrderId} has been change to {Enum.GetName(request.ApprovalState)}",
                hasOrderReviewed.UserId);

            await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, hasOrderReviewed.UserId,
                                    mapper.Map <NotificationDto>(notification));

            //TODO: Call LUA

            return((SetOrderApprovalStateResponse) new SetOrderApprovalStateResponse
            {
                CurrentApprovalState = request.ApprovalState
            }
                   .LogInformation(
                       $"Admin #{httpContextReader.CurrentUserId} set order #{request.OrderId} approval state to: {(int) request.ApprovalState}"));
        }
Beispiel #5
0
        public async Task <ReceiveFriendResponse> Handle(ReceiveFriendRequest request,
                                                         CancellationToken cancellationToken)
        {
            var receiveResult =
                await friendService.Receive(request.SenderId, request.RecipientId, accepted : request.Accepted);

            var friendUpdated = receiveResult?.Friend != null?mapper.Map <FriendDto>(receiveResult.Friend) : null;

            string currentUserId = httpContextReader.CurrentUserId;

            if (receiveResult != null)
            {
                await hubManager.Invoke(SignalrActions.ON_FRIEND_RECEIVED,
                                        currentUserId == request.SenderId?request.RecipientId : request.SenderId, request);

                if (request.Accepted)
                {
                    await notifier.Push(currentUserId == friendUpdated.SenderId
                                        ?NotificationMessages.FriendAcceptedNotification(friendUpdated.RecipientName)
                                        : NotificationMessages.FriendAcceptedNotification(friendUpdated.SenderName),
                                        currentUserId == friendUpdated.SenderId
                                        ?friendUpdated.RecipientId
                                        : friendUpdated.SenderId,
                                        NotificationType.FriendAccepted);
                }

                return(new ReceiveFriendResponse
                {
                    FriendAccepted = receiveResult.FriendAccepted, Friend = friendUpdated
                });
            }

            throw new CrudException("Friend invite has not been accepted");
        }
        public async Task <ArchiveReportResponse> Handle(ArchiveReportRequest request,
                                                         CancellationToken cancellationToken)
        {
            var report =
                await reportValidationHub.ValidateAndReturnReport(request.ReportId, ReportPermission.ArchiveReport)
                ?? throw new NoPermissionsException(ErrorMessages.NotAllowedMessage);

            if (await reportManager.ArchiveReport(report))
            {
                var membersGroup =
                    ReportManagerUtils.GenerateReportMembersGroup(report, httpContextReader.CurrentUserId);

                var notifications = await notifier.PushToGroup(
                    $"Report {report.Subject} has been archived",
                    membersGroup);

                foreach (var memberId in membersGroup)
                {
                    await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, memberId,
                                            mapper.Map <IEnumerable <NotificationDto> >(notifications));
                }

                return((ArchiveReportResponse) new ArchiveReportResponse().LogInformation(
                           $"Report #{report.Id} has been archived"));
            }

            throw new CrudException("Archiving report failed");
        }
Beispiel #7
0
        public async Task <BlockAccountResponse> Handle(BlockAccountRequest request, CancellationToken cancellationToken)
        {
            bool isBlocked = await adminService.BlockAccount(request.UserId);

            await hubManager.Invoke(SignalrActions.REFRESH_USER_DATA, request.UserId);

            return(new BlockAccountResponse {
                IsBlocked = isBlocked
            });
        }
Beispiel #8
0
        public async Task <DeleteMessageResponse> Handle(DeleteMessageRequest request, CancellationToken cancellationToken)
        {
            if (await messenger.Delete(request.MessageId))
            {
                await hubManager.Invoke(SignalrActions.ON_MESSAGE_DELETED, request.RecipientId, request.MessageId);

                return(new DeleteMessageResponse());
            }

            throw new CrudException("Message has not been deleted");
        }
Beispiel #9
0
        public async Task <DeleteFriendResponse> Handle(DeleteFriendRequest request, CancellationToken cancellationToken)
        {
            if (await friendService.DeleteFriend(request.FriendId))
            {
                await hubManager.Invoke(SignalrActions.ON_FRIEND_DELETED, request.FriendId,
                                        httpContextReader.CurrentUserId);

                return(new DeleteFriendResponse());
            }

            throw new CrudException("Friend has not been deleted");
        }
Beispiel #10
0
        public async Task <RevokeRoleResponse> Handle(RevokeRoleRequest request, CancellationToken cancellationToken)
        {
            if (await adminService.RevokeRole(request.UserId, request.Role))
            {
                await notifier.Push(NotificationMessages.AdminRevokedNotification, request.UserId, NotificationType.AdminRevoked);

                await hubManager.Invoke(SignalrActions.REFRESH_USER_DATA, request.UserId);

                return(new RevokeRoleResponse());
            }

            throw new AdminActionException("Role has not been revoked");
        }
        public async Task <PurchaseOrderResponse> Handle(PurchaseOrderRequest request, CancellationToken cancellationToken)
        {
            if (!await balanceValidationService.HasEnoughFunds(httpContextReader.CurrentUserId, request.TotalAmount))
            {
                throw new PaymentException("Insufficient funds to complete transaction");
            }

            var order = await orderService.PurchaseOrder(request);

            var orderOfferItems = order.Items.Where(i => i.Type == OrderType.Offer);
            var offersData      = orderOfferItems.Select(i => new { OwnerId = i.OptionalData, Amount = (decimal)i.Amount / Constants.MoneyMultiplier });

            foreach (var item in orderOfferItems)
            {
                var notification = await notifier.Push(NotificationMessages.OfferBoughtMessage(order.User.UserName, item.ProductName), item.OptionalData);

                await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, item.OptionalData, mapper.Map <NotificationDto>(notification));
            }

            var premiumOrder = order.Items.FirstOrDefault(i => i.Type == OrderType.Premium);

            if (premiumOrder != null && !await rolesManager.AdmitRole(RoleName.Premium, order.User))
            {
                throw new PaymentException("Upgrading account to premium status failed");
            }

            if (order != null)
            {
                foreach (var offerData in offersData)
                {
                    await balanceService.AddBalance(offerData.OwnerId, offerData.Amount);

                    await balanceService.AddBalance(order.UserId, -offerData.Amount);
                }

                string token = default(string);

                if (premiumOrder != null)
                {
                    await balanceService.AddBalance(order.UserId, -(decimal)premiumOrder.Amount / Constants.MoneyMultiplier);

                    token = await jwtAuthorizationTokenGenerator.GenerateToken(order.User);
                }

                return(new PurchaseOrderResponse {
                    Order = mapper.Map <OrderDto>(order), Token = token
                });
            }

            throw new PaymentException("Purchasing order failed");
        }
Beispiel #12
0
        public async Task <SendMessageResponse> Handle(SendMessageRequest request, CancellationToken cancellationToken)
        {
            var messageSent = await messenger.SendMessage(request.Text, request.RecipientId);

            if (messageSent != null)
            {
                await hubManager.Invoke(SignalrActions.MESSAGE_RECEIVED, request.RecipientId, mapper.Map <MessageDto>(messageSent));

                return(new SendMessageResponse {
                    Message = mapper.Map <MessageDto>(messageSent)
                });
            }

            throw new CrudException("Sending message failed");
        }
Beispiel #13
0
        public async Task <FollowUserResponse> Handle(FollowUserRequest request, CancellationToken cancellationToken)
        {
            var(isFollowed, follow) = await userService.FollowUser(request.UserId);

            if (isFollowed)
            {
                var notification = await notifier.Push(NotificationMessages.UserFollowMessage(follow.Follower.UserName), request.UserId);

                await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, request.UserId, mapper.Map <NotificationDto>(notification));
            }

            return(new FollowUserResponse {
                IsFollowed = isFollowed, Follow = mapper.Map <UserFollowDto>(follow)
            });
        }
Beispiel #14
0
        public async Task <LikeOfferResponse> Handle(LikeOfferRequest request, CancellationToken cancellationToken)
        {
            var(isLiked, like) = await favoritesService.LikeOffer(request.OfferId);

            if (isLiked)
            {
                var notification = await notifier.Push(NotificationMessages.OfferFollowMessage(like.User.UserName, request.OfferId), like.Offer.OwnerId);

                await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, like.Offer.OwnerId, mapper.Map <NotificationDto>(notification));
            }

            return(new LikeOfferResponse {
                IsLiked = isLiked, Like = mapper.Map <OfferLikeDto>(like)
            });
        }
Beispiel #15
0
        public async Task <CleanAccountResponse> Handle(CleanAccountRequest request, CancellationToken cancellationToken)
        {
            if (await userManager.CleanAccount(request.UserId))
            {
                var notification = await notifier.Push(
                    $"Admin has cleaned your account",
                    request.UserId);

                await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, request.UserId,
                                        mapper.Map <NotificationDto>(notification));

                return((CleanAccountResponse) new CleanAccountResponse().LogInformation(
                           $"Admin #{httpContextReader.CurrentUserId} cleaned account of user #{request.UserId}"));
            }

            throw new CrudException($"Cleaning account #{request.UserId} failed");
        }
Beispiel #16
0
        public async Task <InviteFriendResponse> Handle(InviteFriendRequest request, CancellationToken cancellationToken)
        {
            var friendCreated = await friendService.Invite(request.RecipientId);

            if (friendCreated != null)
            {
                var friendToReturn = mapper.Map <FriendDto>(friendCreated);

                await hubManager.Invoke(SignalrActions.ON_FRIEND_INVITED, request.RecipientId, friendToReturn);

                return(new InviteFriendResponse {
                    Friend = friendToReturn
                });
            }

            throw new CrudException("Friend invite has not been sent");
        }
        public async Task <CreateOfferAuctionResponse> Handle(CreateOfferAuctionRequest request, CancellationToken cancellationToken)
        {
            var offerAuction = await auctionManager.CreateAuction(request.NewPrice, request.OfferId);

            if (offerAuction != null)
            {
                var notification = await notifier.Push(NotificationMessages.NewOfferPriceProposedMessage(request.NewPrice, request.OfferId), offerAuction.Offer.OwnerId);

                await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, offerAuction.Offer.OwnerId, mapper.Map <NotificationDto>(notification));

                return(new CreateOfferAuctionResponse {
                    OfferAuction = mapper.Map <OfferAuctionDto>(offerAuction)
                });
            }

            throw new CrudException("Creating offer auction failed");
        }
        public async Task <BlockAccountResponse> Handle(BlockAccountRequest request, CancellationToken cancellationToken)
        {
            if (await userManager.BlockAccount(request))
            {
                var notification = await notifier.Push(
                    $"Your account has been blocked",
                    request.AccountId);

                await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, request.AccountId,
                                        mapper.Map <NotificationDto>(notification));

                return((BlockAccountResponse) new BlockAccountResponse().LogInformation(
                           $"Admin #{httpContextReader} has blocked user #{request.AccountId}"));
            }

            throw new CrudException("Blocking user account failed");
        }
Beispiel #19
0
        public async Task <AddCreditsResponse> Handle(AddCreditsRequest request, CancellationToken cancellationToken)
        {
            var result = await userManager.AddCredits(request.Credits, request.UserId);

            var notification = await notifier.Push(
                $"Account credits amount {(request.Credits > 0 ? "increased by" : "decreased by")} {Math.Abs(request.Credits)}, current balance: {result.CurrentCreditsCount}",
                request.UserId);

            await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, request.UserId,
                                    mapper.Map <NotificationDto>(notification));

            return((AddCreditsResponse) new AddCreditsResponse {
                CreditsCount = result.CurrentCreditsCount
            }
                   .LogInformation(
                       $"Admin #{httpContextReader.CurrentUserId} added {request.Credits} to user #{request.UserId}"));
        }
Beispiel #20
0
        public async Task <AddOpinionResponse> Handle(AddOpinionRequest request, CancellationToken cancellationToken)
        {
            var opinionAdded = await opinionService.AddOpinion(request.Text, request.Rating, request.UserId);

            if (opinionAdded != null)
            {
                var notification = await notifier.Push(NotificationMessages.NewOpinionAdded(opinionAdded.Creator.UserName), opinionAdded.UserId);

                await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, opinionAdded.UserId, mapper.Map <NotificationDto>(notification));

                return(new AddOpinionResponse {
                    Opinion = mapper.Map <OpinionDto>(opinionAdded), NewRating = RatingUtils.CalculateRating(opinionAdded.User)
                });
            }

            throw new CrudException("Adding opinion failed");
        }
        public async Task <ReviewRPTestResponse> Handle(ReviewRPTestRequest request, CancellationToken cancellationToken)
        {
            var result = await rpTestManager.ReviewRPTest(request.ApplicationId, request.Note, request.StateType);

            if (result.IsSucceeded)
            {
                var notification = await notifier.Push(
                    "Status of your RP test has been changed",
                    result.UserId);

                await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, result.UserId,
                                        mapper.Map <NotificationDto>(notification));

                return((ReviewRPTestResponse) new ReviewRPTestResponse().LogInformation(
                           $"Reviewer #{httpContextReader.CurrentUserId} review application test #{request.ApplicationId} and set state to: {(int) request.StateType}"));
            }

            throw new ServerException("Processing RP test failed");
        }
Beispiel #22
0
        public async Task <AddOfferResponse> Handle(AddOfferRequest request, CancellationToken cancellationToken)
        {
            var createdOffer = await offerService.AddOffer(request);

            if (createdOffer != null)
            {
                var followersIds = FollowersUtils.GetFollowersIds(createdOffer.Owner);

                foreach (var followerId in followersIds)
                {
                    var notification = await notifier.Push(NotificationMessages.NewOfferByFollowedUserAddedMessage(createdOffer.Owner.UserName), followerId);

                    await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, followerId, mapper.Map <NotificationDto>(notification));
                }

                return(new AddOfferResponse {
                    Offer = mapper.Map <OfferDto>(createdOffer)
                });
            }

            throw new CrudException("Adding offer failed");
        }
Beispiel #23
0
        public async Task <DenyOfferAuctionResponse> Handle(DenyOfferAuctionRequest request, CancellationToken cancellationToken)
        {
            var offer = await offerService.GetOffer(request.OfferId) ?? throw new EntityNotFoundException("Offer not found");

            var denied = await auctionManager.DenyAuction(request.AuctionId, request.OfferId);

            if (denied)
            {
                var followersIds = FollowersUtils.GetFollowersIds(offer.Owner);

                foreach (var followerId in followersIds)
                {
                    var notification = await notifier.Push(NotificationMessages.OfferAuctionDenied(request.OfferId), followerId);

                    await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, followerId, mapper.Map <NotificationDto>(notification));
                }

                return(new DenyOfferAuctionResponse());
            }

            throw new CrudException("Deny offer auction failed");
        }
        public async Task <RemoveReportSubscriberResponse> Handle(RemoveReportSubscriberRequest request,
                                                                  CancellationToken cancellationToken)
        {
            var report =
                await reportValidationHub.ValidateAndReturnReport(request.ReportId, ReportPermission.AddComment)
                ?? throw new NoPermissionsException(ErrorMessages.NotAllowedMessage);

            if (await reportSubscriberService.RemoveSubscriber(report, request.UserId))
            {
                var notification = await notifier.Push(
                    $"You were removed from subscribers in report: {report.Subject}",
                    request.UserId);

                await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, request.UserId,
                                        mapper.Map <NotificationDto>(notification));

                return((RemoveReportSubscriberResponse) new RemoveReportSubscriberResponse().LogInformation(
                           $"Assignee #{httpContextReader.CurrentUserId} has removed subscriber #{request.UserId} in report #{report.Id}"));
            }

            throw new CrudException("Removing report subscriber failed");
        }
Beispiel #25
0
        public async Task <ToggleBlockCharacterResponse> Handle(ToggleBlockCharacterRequest request,
                                                                CancellationToken cancellationToken)
        {
            var blockCharacterResult = await characterManager.ToggleBlockCharacter(request.CharacterId);

            if (blockCharacterResult.IsSucceeded)
            {
                var notification = await notifier.Push(
                    $"Character {blockCharacterResult.CharacterName} has been blocked",
                    blockCharacterResult.AccountId);

                await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, blockCharacterResult.AccountId,
                                        mapper.Map <NotificationDto>(notification));

                return((ToggleBlockCharacterResponse) new ToggleBlockCharacterResponse
                {
                    IsBlocked = blockCharacterResult.IsBlocked
                }.LogInformation(
                           $"Admin #{httpContextReader.CurrentUserId} blocked character #{request.CharacterId}"));
            }

            throw new CrudException("Toggling block character status failed");
        }
        public async Task <AddReportCommentResponse> Handle(AddReportCommentRequest request,
                                                            CancellationToken cancellationToken)
        {
            var report =
                await reportValidationHub.ValidateAndReturnReport(request.ReportId, ReportPermission.AddComment)
                ?? throw new NoPermissionsException(ErrorMessages.NotAllowedMessage);

            var addedReportComment = await reportCommentService.AddComment(request with {
                IsPrivate = report.Private
            })
                                     ?? throw new CrudException("Adding report comment failed");

            if (ReportStatusTypeSmartEnum.FromValue(report.Status)
                .ShouldBeOpened(report, addedReportComment.UserId))
            {
                await reportManager.ChangeStatus(ReportStatusType.Opened, report);
            }

            var membersGroup = ReportManagerUtils.GenerateReportMembersGroup(report, addedReportComment.UserId);

            var notifications = await notifier.PushToGroup(
                $"Someone responded to your report: {report.Subject}", membersGroup);

            foreach (var memberId in membersGroup)
            {
                await hubManager.Invoke(SignalrActions.NOTIFICATION_RECEIVED, memberId,
                                        mapper.Map <IEnumerable <NotificationDto> >(notifications));
            }

            return((AddReportCommentResponse) new AddReportCommentResponse
            {
                ReportComment = mapper.Map <ReportCommentDto>(addedReportComment)
            }
                   .LogInformation(
                       $"Member #{addedReportComment.UserId} of report #{report.Id} added comment #{addedReportComment.Id}"));
        }