Пример #1
0
        public void ProcessFissures(List <NotificationState> states, List <Fissure> fissures)
        {
            if (fissures == null)
            {
                return;
            }

            if (states == null || !states.Any())
            {
                var newFissureStates = fissures.Select(f => new NotificationState {
                    WfStatId = f.Id, WfStatType = nameof(WFStatType.Fissure)
                });
                NewNotificationStates.AddRange(newFissureStates);
                return;
            }


            var expiredFissures = states.Where(s => !fissures.Any(f => f.Id == s.WfStatId));
            var newFissures     = fissures.Where(f => !states.Any(s => s.WfStatId == f.Id));

            if (expiredFissures.Any())
            {
                ExpiredNotificationStates.AddRange(expiredFissures);
            }

            foreach (var fissure in newFissures)
            {
                NewNotificationStates.Add(new NotificationState
                {
                    WfStatId   = fissure.Id,
                    WfStatType = nameof(WFStatType.Fissure)
                });

                var ttl   = fissure.TimeLeft;
                var topic = YawsNotification.Topic.Info;
                if (fissure.TierNum == 1)
                {
                    topic = YawsNotification.Topic.FissureLith;
                }
                else if (fissure.TierNum == 2)
                {
                    topic = YawsNotification.Topic.FissureMeso;
                }
                else if (fissure.TierNum == 3)
                {
                    topic = YawsNotification.Topic.FissureNeo;
                }
                else if (fissure.TierNum == 4)
                {
                    topic = YawsNotification.Topic.FissureAxi;
                }
                else if (fissure.TierNum == 5)
                {
                    topic = YawsNotification.Topic.FissureRequiem;
                }

                var message = FCM.CreateMessage($"{fissure.Tier} {fissure.MissionType} on {fissure.Node}", $"Expired in {fissure.TimeLeft.ToFormattedString()}", platform, topic, nameof(Fissure), ttl);
                NotificationMessages.Add(message);
            }
        }
Пример #2
0
        public void Hide(Guid id)
        {
            var n = NotificationMessages.SingleOrDefault(x => x.Id == id);

            if (n?.InvokeHideAnimation == null)
            {
                return;
            }

            n.InvokeHideAnimation();

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(200);
            }).ContinueWith(t =>
            {
                NotificationMessages.Remove(n);

                if (NotificationMessages.Any() == false)
                {
                    InternalStopTimer();
                    IsOpen = false;
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Пример #3
0
        public async Task <bool> SetModerator(string groupId, string userId, bool isModerator = true)
        {
            var currentUser = await profileService.GetCurrentUser();

            var group = await database.GroupRepository.FindById(groupId) ??
                        throw new EntityNotFoundException("Group not found");

            if (currentUser.Id != group.AdminId)
            {
                throw new NoPermissionsException("You are not allowed to manage this group");
            }

            var member = GetMember(userId, group);

            if (!member.IsAccepted)
            {
                throw new NoPermissionsException("This user is not member of this group");
            }

            member.SetIsModerator(isModerator);

            if (await database.Complete())
            {
                await notifier.Push(
                    isModerator
                    ?NotificationMessages.GroupModeratorGrantedNotification(group.Name)
                    : NotificationMessages.GroupModeratorRevokedNotification(group.Name),
                    userId,
                    isModerator?NotificationType.GroupModeratorGranted : NotificationType.GroupModeratorRevoked);

                return(true);
            }

            return(false);
        }
Пример #4
0
        private void RegisterPhasedWork()
        {
            // RegisterIntentHandler uses the intent manager, which is only
            // available after login. Queue this registration for the
            // RegisterSpokes phase.
            mApplicationPhases.QueueSynchronousWork(
                phase: ApplicationPhase.RegisterSpokes,
                action: RegisterIntentHandler,
                exceptionMapper: x => NotificationMessages.GetErrorMessage(x, NotificationMessageKeys.ApplicationInitialization));

            // Use the ExtensibilityHelper to add a button into the header bar.
            mApplicationPhases.QueueSynchronousWork(
                phase: ApplicationPhase.AfterUIPresented,
                action: CreateHeaderCommand,
                exceptionMapper: x => NotificationMessages.GetErrorMessage(x, NotificationMessageKeys.ApplicationInitialization));

            // Add an event listener to the hosting web page that uses the
            // IJsonSubsetMessageHandler to process JSON messages sent to it.
            mApplicationPhases.QueueSynchronousWork(
                phase: ApplicationPhase.AfterUIPresented,
                action: InjectPostMessageToHandlerToHostPage,
                exceptionMapper: x => NotificationMessages.GetErrorMessage(x, NotificationMessageKeys.ApplicationInitialization));

            // LoginViaBrowserStack uses the IUserCredentials, which is only
            // available after login. Queue this login for the
            // RegisterSpokes phase.
            mApplicationPhases.QueueAsynchronousWork(
                phase: ApplicationPhase.RegisterSpokes,
                action: LoginViaBrowserStack);
        }
Пример #5
0
        private void RemoveNotificationsTimer_OnTick(object sender, EventArgs eventArgs)
        {
            var timer = sender as DispatcherTimer;

            if (timer == null)
            {
                return;
            }

            // Stop the timer and cleanup for GC
            timer.Tick += RemoveNotificationsTimer_OnTick;
            timer.Stop();

            var n = timer.Tag as NotificationViewModel;

            if (n == null)
            {
                return;
            }

            NotificationMessages.Remove(n);

            if (NotificationMessages.Any())
            {
                return;
            }

            InternalStopTimer();
            IsOpen = false;
        }
Пример #6
0
        public void Show(string message, NotificationType type)
        {
            if (NotificationMessages.Any() == false)
            {
                InternalStartTimer();
                IsOpen = true;
            }

            if (MaximumNotificationCount != UnlimitedNotifications)
            {
                if (NotificationMessages.Count >= MaximumNotificationCount)
                {
                    int removeCount = (int)(NotificationMessages.Count - MaximumNotificationCount) + 1;

                    var itemsToRemove = NotificationMessages.OrderBy(x => x.CreateTime)
                                        .Take(removeCount)
                                        .Select(x => x.Id)
                                        .ToList();
                    foreach (var id in itemsToRemove)
                    {
                        Hide(id);
                    }
                }
            }

            NotificationMessages.Add(new NotificationViewModel
            {
                Message = message,
                Type    = type
            });
        }
Пример #7
0
        public NotificationsResponse CreateNotificationsResponse(List <CampaignEN> pNotifications)
        {
            NotificationsResponse response = new NotificationsResponse();
            NotificationMessages  messages = new NotificationMessages();

            messages.userNotifications = new List <NotificationItem>();

            try
            {
                foreach (var item in pNotifications)
                {
                    NotificationItem notif = new NotificationItem();
                    notif.trackingID     = item.NotificationID;
                    notif.notificationID = item.CampaignID;
                    notif.title          = item.NotificationTitle;
                    notif.message        = item.NotificationMessage;
                    notif.seen           = item.Read;

                    messages.userNotifications.Add(notif);
                }

                response.notifications = messages;
                response.count         = messages.userNotifications.Count;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
            }

            return(response);
        }
Пример #8
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");
        }
Пример #9
0
        public async Task <CreatePostResponse> Handle(CreatePostRequest request, CancellationToken cancellationToken)
        {
            var createdPost = await postService.CreatePost(mapper.Map <Domain.Entities.Post.Post>(request), photo : request.Photo) ??
                              throw new CrudException("Post has not been created");

            if (createdPost.Group != null && httpContextReader.CurrentUserId != createdPost.AuthorId)
            {
                var allMembersIds = createdPost.Group.GroupMembers
                                    .Where(m => m.IsAccepted && m.UserId != createdPost.AuthorId).Select(m => m.UserId);

                await notifier.Push(
                    NotificationMessages.NewGroupPostNotification(createdPost.Author.Username, createdPost.Group.Name),
                    createdPost.Group.AdminId, NotificationType.NewGroupPost);

                foreach (var memberId in allMembersIds)
                {
                    await notifier.Push(
                        NotificationMessages.NewGroupPostNotification(createdPost.Author.Username,
                                                                      createdPost.Group.Name), memberId, NotificationType.NewGroupPost);
                }
            }

            return(new CreatePostResponse {
                Post = mapper.Map <PostDto>(createdPost)
            });
        }
Пример #10
0
        private static bool LoginFailure(Action <Notification> callback,
                                         Exception exception, bool presentedToUser)
        {
            if (!presentedToUser)
            {
                callback(NotificationMessages.GetErrorMessage(exception,
                                                              NotificationMessageKeys.ApplicationInitialization));
            }

            return(true);
        }
        private void TimerOnTick(object sender, EventArgs eventArgs)
        {
            var currentTime = DateTime.Now;

            var itemsToRemove = NotificationMessages.Where(x => currentTime - x.CreateTime >= NotificationLifeTime).Select(x => x.Id).ToList();

            foreach (var id in itemsToRemove)
            {
                Hide(id);
            }
        }
Пример #12
0
        public void ProcessSentientOutpost(NotificationState state, SentientOutpost so)
        {
            var sendFCM = ProcessSingleExpirable(state, so, so.StatType);

            if (sendFCM && so.Expiry != null && so.Mission != null)
            {
                var ttl     = so.TimeLeft;
                var message = FCM.CreateMessage("Sentient Anomaly", $"{so.Mission.Node}", platform, YawsNotification.Topic.SentientOutpost, nameof(SentientOutpost), ttl);
                NotificationMessages.Add(message);
            }
        }
Пример #13
0
        public void ProcessArbitration(NotificationState state, Arbitration arbi)
        {
            var sendFCM = ProcessSingleExpirable(state, arbi, arbi.StatType);

            if (sendFCM)
            {
                var ttl     = arbi.TimeLeft;
                var message = FCM.CreateMessage($"Arbitration: {arbi.Enemy} {arbi.Type}", $"Expired in {ttl.ToFormattedString()}", platform, YawsNotification.Topic.Arbitration, nameof(Arbitration), ttl);
                NotificationMessages.Add(message);
            }
        }
Пример #14
0
        public void ProcessEarthCycle(NotificationState state, EarthCycle earth)
        {
            var sendFCM = ProcessSingleExpirable(state, earth, earth.StatType);

            if (sendFCM)
            {
                var ttl     = earth.TimeLeft;
                var message = FCM.CreateMessage($"{earth.State.ToUpperFirst()} on Earth", $"{earth.TimeLeft.ToFormattedString()} left", platform, YawsNotification.Topic.EarthCycle, nameof(EarthCycle), ttl);
                NotificationMessages.Add(message);
            }
        }
Пример #15
0
        public void ProcessVallisCycle(NotificationState state, VallisCycle vallis)
        {
            var sendFCM = ProcessSingleExpirable(state, vallis, vallis.StatType);

            if (sendFCM)
            {
                var ttl     = vallis.TimeLeft;
                var message = FCM.CreateMessage($"Orb Vallis {vallis.State.ToUpperFirst()}", vallis.ShortString, platform, YawsNotification.Topic.VallisCycle, nameof(VallisCycle), ttl);
                NotificationMessages.Add(message);
            }
        }
Пример #16
0
 public ScheduleJob(ModelsContext context)
 {
     _context             = context;
     _notificationMessage = new NotificationMessages(context);
     updateAwardTimer     = new Timer(
         callback: new TimerCallback(RunAwardUserJob),
         state: "",
         dueTime: 10000, //run RunAwardUserJob after 10s of this object creation
         period: 0
         );
 }
Пример #17
0
        public void ProcessCetusCycle(NotificationState state, CetusCycle cetus)
        {
            var sendFCM = ProcessSingleExpirable(state, cetus, cetus.StatType);

            if (sendFCM)
            {
                var ttl     = cetus.TimeLeft;
                var message = FCM.CreateMessage($"{cetus.State.ToUpperFirst()} in Cetus", cetus.ShortString, platform, YawsNotification.Topic.CetusCycle, nameof(CetusCycle), ttl);
                NotificationMessages.Add(message);
            }
        }
Пример #18
0
        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");
        }
Пример #19
0
        private void RegisterPhasedWork()
        {
            // IntentManager is only available after we're logged in.
            mApplicationPhases.QueueSynchronousWork(
                phase: ApplicationPhase.RegisterSpokes,
                action: RegisterIntentHandler,
                exceptionMapper: x => NotificationMessages.GetErrorMessage(x, NotificationMessageKeys.ApplicationInitialization));

            // Use the ExtensibilityHelper to add a button into the header bar.
            mApplicationPhases.QueueSynchronousWork(
                phase: ApplicationPhase.AfterUIPresented,
                action: CreateHeaderCommand,
                exceptionMapper: x => NotificationMessages.GetErrorMessage(x, NotificationMessageKeys.ApplicationInitialization));
        }
Пример #20
0
        private int SendRequestToSave()
        {
            try
            {
                _objUser = new UserDetail();

                int result = 0;
                _objUser.Email      = txtEmail.Text.Trim();
                _objUser.MobileNo   = txtMobileNo.Text.Trim();
                _objUser.FirstName  = txtFirstName.Text.Trim();
                _objUser.LastName   = txtLastName.Text.Trim();
                _objUser.Password   = CommonBiz.GetSwcSH1(txtPassword.Text.Trim()); //Password encrypted by SHA1 algorithm
                _objUser.RoleTypeID = Convert.ToChar(ddlAccountType.SelectedValue);


                _objUser.Status = false;

                result = _objUserBiz.Save(_objUser);
                if (result == 1 && (!string.IsNullOrEmpty(_objUser.Email) || !string.IsNullOrWhiteSpace(_objUser.Email)))
                {
                    _objMessages = new NotificationMessages();
                    _objMessages.ClassificationID   = 1;
                    _objMessages.NotificationTypeID = 1;
                    string path = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/" + "UserActivationByEmail.aspx?email=" + _objUser.Email;//Request.Url.GetLeftPart(UriPartial.Authority);
                    _objNotificationBiz = new NotificationBiz();

                    string body = "Hello " + _objUser.FirstName + ",";
                    body += "<br /><br />Please click the following link to activate your account";
                    body += "<br /> <a href='" + path + "' >Click here to activate your account. </a> <br /><br />Thanks";

                    _objNotificationBiz.SendEmail(_objMessages, _objUser.Email, body);
                    succesMessage = "Signup Successful";
                }
                else if (result == 2)
                {
                    succesMessage = "User already Exists!";
                }

                else
                {
                    succesMessage = "Registration Failed";
                }
                return(result);
            }
            catch (Exception exception)
            {
                MessageBox(exception.Message);
                return(0);
            }
        }
Пример #21
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)
            });
        }
        public async Task <NotificationMessages> Insert(NotificationMessages tblNotificationMessage)
        {
            try
            {
                tblNotificationMessage.CreatedDate = DateTime.Now;
                context.Add(tblNotificationMessage);
                await context.SaveChangesAsync();

                return(tblNotificationMessage);
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #23
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)
            });
        }
Пример #24
0
        public async Task <IActionResult> InsertNotificationMessage([FromBody] NotificationMessages tblNotificationMessage)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var entity = await notificationMessagesService.Insert(tblNotificationMessage);

            if (entity == null)
            {
                return(BadRequest());
            }
            return(CreatedAtAction("GetNotificationMessageByID", new { id = tblNotificationMessage.NotificationMessageId }, tblNotificationMessage));
        }
Пример #25
0
        public async Task <SendReplyResponse> Handle(SendReplyRequest request, CancellationToken cancellationToken)
        {
            var reply = await replyManager.SendReply(request.Content, request.ReportId, request.Files) ??
                        throw new CrudException("Reply sending failed");

            if (reply.Report.ReporterId != null && httpContextReader.CurrentUserId != reply.Report.ReporterId)
            {
                await notifier.Push(NotificationMessages.SupportReplyNotification(reply.Report.Subject),
                                    reply.Report.ReporterId, NotificationType.SupportReply);
            }

            return(new SendReplyResponse {
                Reply = mapper.Map <ReplyDto>(reply)
            });
        }
Пример #26
0
        public async Task <CreateCommentResponse> Handle(CreateCommentRequest request,
                                                         CancellationToken cancellationToken)
        {
            var createdComment = await commentService.CreateComment(request.Content, request.PostId) ??
                                 throw new CrudException("Comment has not been created");

            if (httpContextReader.CurrentUserId != createdComment.UserId)
            {
                await notifier.Push(
                    NotificationMessages.NewCommentNotification(createdComment.User.Username,
                                                                createdComment.Post.Title), createdComment.Post.AuthorId, NotificationType.NewComment);
            }

            return(new CreateCommentResponse {
                Comment = mapper.Map <CommentDto>(createdComment)
            });
        }
Пример #27
0
        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");
        }
Пример #28
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");
        }
Пример #29
0
 internal Response <bool> DeleteNotificationBatch(NotificationMessages messages, long auditUserId, string auditWorkstation)
 {
     try
     {
         return(new Response <bool>(_notificationservice.DeleteNotificationBatch(messages, auditUserId, auditWorkstation),
                                    ResponseType.SUCCESSFUL,
                                    "",
                                    ""));
     }
     catch (Exception ex)
     {
         log.Error(ex);
         return(new Response <bool>(false,
                                    ResponseType.ERROR,
                                    "Error when processing request.",
                                    log.IsDebugEnabled || log.IsTraceEnabled ? ex.Message : ""));
     }
 }
Пример #30
0
 internal Response <List <notification_branchResult> > GetNotificationBranch(NotificationMessages messages, long auditUserId, string auditWorkstation)
 {
     try
     {
         return(new Response <List <notification_branchResult> >(_notificationservice.GetNotificationBranch(messages, auditUserId, auditWorkstation),
                                                                 ResponseType.SUCCESSFUL,
                                                                 "",
                                                                 ""));
     }
     catch (Exception ex)
     {
         log.Error(ex);
         return(new Response <List <notification_branchResult> >(null,
                                                                 ResponseType.ERROR,
                                                                 "Error when processing request.",
                                                                 log.IsDebugEnabled || log.IsTraceEnabled ? ex.Message : ""));
     }
 }