Esempio n. 1
0
        public Operation <Post> PublishPost(long id)
        => _auth.AuthorizeAccess(this.PermissionProfile <IPostService>(UserContext.CurrentUser()), () =>
        {
            var post = _query.GetPostById(id).ThrowIfNull("Invalid post");

            post.Status = PostStatus.Published;
            return(_pcommand
                   .Update(post)
                   .Then(opr =>
            {
                //notify everyone.
                //NOTE: this should be made asynchroneous, and possibly done with a bulk insert.
                _query.AllBitMembers().ForAll((cnt, next) =>
                {
                    _notifier.NotifyUser(new Notification
                    {
                        TargetId = next.UserId,
                        Type = NotificationType.Info,
                        Title = "New Post",
                        Message = $"Check out this <a href='/posts/index#!/details/{opr.Result.Id}'>new post</a> by Admin."
                    });
                });

                return opr;
            }));
        });
Esempio n. 2
0
 public void RegisterUser(string userName, string userEmail)
 {
     _userValidator.ValidateUserName(userName);
     _userValidator.ValidateUserEmail(userEmail);
     _userRepository.SaveUser(userName, userEmail);
     _userNotifier.NotifyUser(userName, userEmail);
 }
Esempio n. 3
0
 public void OnNext(HomeAd value)
 {
     if (_filter(value))
     {
         _notifier.NotifyUser(value);
     }
 }
Esempio n. 4
0
        public async Task<Order> CreateOrder(int customerId, int salesPersonId, List<Tuple<string, int>> productsQuantities)
        {
            var order = _orderRepo.Create(new NewOrderInformation()
            {
                CustomerId = customerId,
                SalesPersonId = salesPersonId,
                products = productsQuantities.Select(p =>
                {
                    return new ProductOrderInformation()
                    {
                        ProductCode = p.Item1,
                        Quantity = p.Item2,
                        Price = GetPriceWithDiscounts(p.Item1, p.Item2)
                    };
                }).ToList()
            });

            await _context.SaveChangesAsync();
            _userNotifier.NotifyUser(customerId);
            return order;
        }
Esempio n. 5
0
        public void Start()
        {
            _stoped = false;
            TrackTask trackTask = null;

            while (!_stoped)
            {
                trackTask = _taskProvider.GetPlannedTask();

                if (trackTask != null)
                {
                    //if we have enough resources to execute task
                    if (_runningTasks.Count() < _tasksMaximum || trackTask.Track.ServiceUser.Subscripe.Priority != Priority.Low)
                    {
                        _taskProvider.UpdateTaskStatus(trackTask.Id, TrackTaskStatus.Started);
                        TaskUpdated?.Invoke(this, trackTask);
                        //Async execute task
                        var executingTask = trackTask;
                        var task          = _taskFactory.StartNew(async() =>
                        {
                            //Execute task
                            var status = await _taskExecutor.ExecuteTask(executingTask);
                            _taskProvider.UpdateTaskStatus(executingTask.Id, status);
                            _taskProvider.UpdateTargetContent(executingTask.Id, executingTask.Track.TargetContent);
                            //User must knows about his track
                            _userNotifier.NotifyUser(executingTask);
                            TaskUpdated?.Invoke(this, executingTask);
                        });
                        _runningTasks.Add(task);
                        task.ContinueWith((t) =>
                        {
                            _runningTasks.Remove(t);
                        });
                    }
                }
            }
        }
Esempio n. 6
0
        public Operation <User> RegisterUser(string targetUser, string referrer, Credential secretCredential)
        => _authorizer.AuthorizeAccess(UserContext.CurrentPPP(), () =>
        {
            var user = _query.GetUserById(targetUser);

            if (user != null)
            {
                throw new Exception($"{targetUser} already exists");
            }

            else if (secretCredential == null)
            {
                throw new Exception("user registration must contain a credential");
            }

            else
            {
                if (referrer == null)
                {
                    referrer = _query.GetRefNode(_query.GetUserById(Constants.SystemUsers_Apex)).ReferenceCode;
                }
                else if (_query.GetRefNode(referrer) == null)
                {
                    throw new Exception("invalid referer specified");
                }

                #region Create user
                user = new User
                {
                    UserId = targetUser,
                    Status = (int)AccountStatus.InActive
                };
                #endregion
                return(_pcommand

                       #region Add user
                       .Add(user) //add user
                       #endregion

                       #region Assign Credentials
                       .Then(opr =>
                {
                    #region Assign credentials (password)
                    //assign credentials
                    //load all credential expiration dates from settings
                    var passwordExpiration = _settingsManager.GetSetting(Constants.Settings_DefaultPasswordExpirationTime)
                                             .Resolve()
                                             .ParseData <TimeSpan>();

                    secretCredential.ExpiresIn = null;     //<-- never expires

                    return _credentialAuth.AssignCredential(targetUser, secretCredential);

                    #endregion
                })
                       #endregion

                       #region Assign role
                       .Then(opr =>
                {
                    return _authorizer.AssignRole(user, Constants.Roles_BitMemberRole);
                })
                       #endregion

                       #region Place the user in the referal hierarchy
                       .Then(opr =>
                {
                    return _refManager.AffixNewUser(user.UserId, referrer);
                })
                       #endregion

                       #region Request context verification
                       .Then(opr =>
                {
                    return RequestUserActivation(user.UserId);
                })
                       #endregion

                       #region Notify User
                       //welcome notification
                       .Then(opr => _notifier.NotifyUser(new Notification
                {
                    TargetId = user.UserId,
                    Title = "Welcome to the BitDiamond Family!",
                    Message = "Us here at BitDiamond warmly welcome you to our family of wealth growers and investors.",
                    Type = NotificationType.Info
                }))

                       //Add a Bitcoin Address
                       .Then(_opr => _notifier.NotifyUser(new Notification
                {
                    TargetId = user.UserId,
                    Type = NotificationType.Info,
                    Title = "Get a Bitcoin Address",
                    Message =
                        @"Already have a Bitcoin address? then go right ahead and add that address <a href='/bit-level/index#!/bitcoin-addresses'>Here</a><br/>
If you dont have one, you can create one with any of the popular Bitcoin Wallet services. 
"
                }))

                       //Add a Bitcoin Address
                       .Then(_opr => _notifier.NotifyUser(new Notification
                {
                    TargetId = user.UserId,
                    Type = NotificationType.Info,
                    Title = "Biodata request",
                    Message = @"Visit your <a href='/profile/index#!/home'>Profile Page</a> to supply your biodata information."
                }))
                       #endregion

                       .Then(opr => user));
            }
        });
Esempio n. 7
0
        /// <summary>
        /// Does both upgrading and recycling
        /// </summary>
        /// <returns></returns>
        public Operation <BitLevel> Upgrade()
        => _authorizer.AuthorizeAccess(UserContext.CurrentProcessPermissionProfile(), () =>
        {
            var maxLevelSettings = _settingsManager.GetSetting(Constants.Settings_MaxBitLevel).Resolve();
            var maxLevel         = (int)maxLevelSettings.ParseData <long>();
            var targetUser       = UserContext.CurrentUser();
            var currentLevel     = _query.CurrentBitLevel(targetUser);

            if (currentLevel != null)
            {
                ConfirmUpgradeDonation().Resolve();
            }

            else
            {
                currentLevel = new BitLevel
                {
                    Level    = maxLevel,
                    Cycle    = 0,
                    Donation = new BlockChainTransaction {
                        Status = BlockChainTransactionStatus.Verified
                    }
                }
            };


            if (currentLevel.Donation.Status == BlockChainTransactionStatus.Unverified)
            {
                throw new Exception("Current level donnation is still unverified");
            }

            var myAddress = _query.GetActiveBitcoinAddress(targetUser)
                            .ThrowIfNull("You do not have a valid block chain transaction address yet.");

            if (currentLevel.Cycle == int.MaxValue && currentLevel.Level == maxLevel)
            {
                throw new Exception("You cannot upgrade past the maximum cycle");
            }

            var nextLevel = (currentLevel.Level + 1) % (maxLevel + 1);
            var nextCycle = nextLevel == 0 ? currentLevel.Cycle + 1 : currentLevel.Cycle;

            var nextUpgradeBeneficiary = NextUpgradeBeneficiary(nextLevel == 0 ? targetUser : currentLevel.Donation.Receiver.Owner, nextLevel, nextCycle).ThrowIfNull("Could not find a valid beneficiary");
            var beneficiaryAddress     = _query.GetActiveBitcoinAddress(nextUpgradeBeneficiary);

            var bl = new BitLevel
            {
                Level         = nextLevel,
                Cycle         = nextCycle,
                DonationCount = 0,
                SkipCount     = 0,
                UserId        = targetUser.UserId
            };
            _pcommand.Add(bl).Resolve();

            var donation = new BlockChainTransaction
            {
                Amount      = nextLevel == maxLevel ? 0 : GetUpgradeAmount(nextLevel + 1),
                LedgerCount = nextLevel == maxLevel ? int.MaxValue : 0,
                CreatedOn   = DateTime.Now,
                Sender      = myAddress,
                Receiver    = beneficiaryAddress,
                ContextType = Constants.TransactionContext_UpgradeBitLevel,
                ContextId   = bl.Id.ToString(),
                Status      = nextLevel == maxLevel ?
                              BlockChainTransactionStatus.Verified :
                              BlockChainTransactionStatus.Unverified
            };
            _pcommand.Add(donation).Resolve();

            bl.DonationId = donation.Id;
            _pcommand.Update(bl);

            bl.Donation = donation;

            //notify user
            _notifier.NotifyUser(new Notification
            {
                Type     = NotificationType.Success,
                TargetId = targetUser.UserId,
                Title    = "Congratulations!",
                Message  = $"Well done, {targetUser.UserId}!! You are now <strong>proudly</strong> at Cycle-{nextCycle} / Level-{nextLevel}, no easy feat!<br/>" +
                           @"Now you can receive even more donations from your downlines. 
                  <p>Remember though, that this is a race to the <strong class='text-primary'>top</strong>, and as such
                  you may miss the donations of any of your downlines who upgrades to levels higher than yours. So dont waste much time here, Upgrade as soon as you can!</p>"
            })
            .Resolve();

            return(bl);
        });
Esempio n. 8
0
        public void DoSearch()
        {
            using (var usersContext = _serviceProvider.GetRequiredService <IUsersContext>())
            {
                var allPrefs = usersContext.Preferences.Include(u => u.User);
                foreach (var prefs in allPrefs)
                {
                    try
                    {
                        if (!ValidForSearch(prefs))
                        {
                            continue;
                        }

                        var keywords     = PrepareKeywords(prefs.Keyword);
                        var wallGeParams = new WallGetParams
                        {
                            Count   = 50,
                            OwnerId = prefs.TargetType == PreferenceType.VkGroup ? -prefs.TargetId : prefs.TargetId
                        };

                        Thread.Sleep(1000);

                        var getResult = _api.Wall.Get(wallGeParams);
                        var posts     = getResult.WallPosts;

                        foreach (var post in posts.Reverse())
                        {
                            var searchResult = _keywordSearcher.LookIntoPost(post, keywords);
                            if (!searchResult.Contains)
                            {
                                continue;
                            }

                            if (post.Date <= prefs.LastNotifiedPostTime)
                            {
                                continue;
                            }

                            prefs.LastNotifiedPostTime = post.Date ?? DateTime.Now;
                            _userNotifier.NotifyUser(prefs, post.Id.Value, searchResult.Word);
                        }
                    }
                    catch (UserAuthorizationFailException ex)
                    {
                        _logger.Error($"UserAuthorizationException. {ex}");
                        //if (!_api.IsAuthorized)
                        {
                            _logger.Info($"VkApi wasn't authorized. Authorizing..");
                            _api.SimpleAuthorize(_settings.Vkontakte);
                            _logger.Info($"SimpleAuthorize passed. New vk auth status = {_api.IsAuthorized}");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(ex, $"Error while fetching VK groups. Pref: {prefs.ToShortString()}. Exception message: {ex}");
                    }
                }
                usersContext.SaveChanges();
            }
        }