Exemple #1
0
            public BotDbContext CreateDbContext()
            {
                var context = new BotDbContext(CreateNewContextOptions());

                context.Database.EnsureDeleted();
                return(context);
            }
Exemple #2
0
        public async Task TestRegAppAsync()
        {
            string          testResultPath  = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ApiResults", "ValidApplicationResult.json");
            string          json            = File.ReadAllText(testResultPath);
            var             mocks           = Utils.CreateDefaultGraphApiMock(json);
            BotDbContext    db              = Utils.CreateMemoryDbContext();
            DefaultGraphApi defaultGraphApi = new DefaultGraphApi(db, mocks.Item1, mocks.Item2);

            BindHandler bindHandler = new BindHandler(db, defaultGraphApi);

            long   userId       = 123456;
            string userName     = "******";
            string email        = "*****@*****.**";
            Guid   clientId     = Guid.NewGuid();
            string clientSecret = "741852963";
            string appName      = "app1";

            await bindHandler.RegAppAsync(userId, userName, email, clientId.ToString(), clientSecret, appName);

            await db.DisposeAsync();

            db = Utils.CreateMemoryDbContext();
            AzureApp azureApp = await db.AzureApps.Include(azureApp => azureApp.TelegramUser).FirstAsync();

            Assert.AreEqual(userId, azureApp.TelegramUserId);
            Assert.AreEqual(userName, azureApp.TelegramUser.UserName);
            Assert.AreEqual(email, azureApp.Email);
            Assert.AreEqual(clientId, azureApp.Id);
            Assert.AreEqual(clientSecret, azureApp.Secrets);
            Assert.AreEqual(appName, azureApp.Name);
        }
Exemple #3
0
 public UpdateService(BotDbContext dbContext, IBotService botService, IOpenDotaService dotaService, ILogger <UpdateService> logger)
 {
     _dbContext   = dbContext;
     _botService  = botService;
     _logger      = logger;
     _dotaService = dotaService;
 }
Exemple #4
0
        public async Task TestUpdateAuthAsync()
        {
            string token = await Utils.GetTestToken();

            string  authResponsePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ApiResults", "ValidAuthResponse.json");
            string  authResponse     = File.ReadAllText(authResponsePath);
            string  testResultPath   = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ApiResults", "GetTokenSuccessResult.json");
            string  json             = File.ReadAllText(testResultPath);
            JObject jObject          = JObject.Parse(json);

            jObject["access_token"] = token;
            json = JsonConvert.SerializeObject(jObject);
            Guid clientId = Guid.NewGuid();
            var  mocks    = Utils.CreateDefaultGraphApiMock(json);
            await Utils.SetOneValueDbContextAsync(clientId);

            BotDbContext    db = Utils.CreateMemoryDbContext();
            DefaultGraphApi defaultGraphApi = new DefaultGraphApi(db, mocks.Item1, mocks.Item2);
            Guid            authId          = (await db.AppAuths.AsQueryable().FirstAsync(item => item.AzureAppId == clientId)).Id;

            BindHandler bindHandler = new BindHandler(db, defaultGraphApi);
            await bindHandler.UpdateAuthAsync(authId.ToString(), authResponse);

            await db.DisposeAsync();

            db = Utils.CreateMemoryDbContext();
            Assert.AreEqual(1, await db.AppAuths.AsQueryable().CountAsync());
            Assert.IsTrue(await db.AppAuths.AsQueryable().AnyAsync(appAuth => appAuth.Id == authId && appAuth.RefreshToken == jObject["refresh_token"].ToString()));
        }
Exemple #5
0
        public async Task ShowMoreIntent(IDialogContext context, IAwaitable <IMessageActivity> activity, LuisResult result)
        {
            var db = new BotDbContext();

            var task     = db.OnboardingTasks.FirstOrDefault();
            var nextTask = 0;

            //var msg = string.Format("{0}", tasks[nextTask].TaskName);

            var message = context.MakeMessage();

            message.TextFormat = TextFormatTypes.Plain;
            message.Text       = string.Format("{0} - {1}", task.TaskName, task.TaskDescription);

            message.SuggestedActions = new SuggestedActions()
            {
                Actions = new List <CardAction> {
                    new CardAction {
                        Title = "Click here", Type = ActionTypes.OpenUrl, Value = "https://rbauction.sharepoint.com/it/pg/sf/_layouts/15/DocIdRedir.aspx?ID=U7JYW44APTCC-399-36&e=827f8be4cf294b5587983221312d20fb"
                    }
                }
            };
            //message.


            message.ReplyToId = context.Activity.Id;


            await context.PostAsync(message);

            context.Wait(MessageReceived);
        }
Exemple #6
0
        public async Task FetchNextIntent(IDialogContext context, IAwaitable <IMessageActivity> activity, LuisResult result)
        {
            var db = new BotDbContext();

            var tasks    = db.OnboardingTasks.ToList();
            var nextTask = 0;

            var msg = string.Format("{0}", tasks[nextTask].TaskName);

            var message = context.MakeMessage();

            message.TextFormat       = TextFormatTypes.Plain;
            message.Text             = msg;
            message.SuggestedActions = new SuggestedActions()
            {
                Actions = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Show me more", Type = ActionTypes.PostBack, Value = "Show Me More", Text = "ShowMore"
                    }
                }
            };

            message.ReplyToId = context.Activity.Id;


            await context.PostAsync(message);

            context.Wait(MessageReceived);
        }
        /// <summary>Populates database with unused addresses.</summary>
        private void PregenerateAddresses(BotDbContext context)
        {
            this.logger.Trace("()");
            this.logger.Info("Database was not prefilled with unused addresses. Starting.");

            this.logger.Info("Generating {0} addresses.", this.settings.PregeneratedAddressesCount);

            try
            {
                var unusedAddressResult = blockCoreNodeAPI.GetUnusedAddresses(settings.PregeneratedAddressesCount).Result;

                foreach (string address in unusedAddressResult)
                {
                    context.UnusedAddresses.Add(new AddressModel()
                    {
                        Address = address
                    });
                }

                context.SaveChanges();
                this.logger.Info("Addresses generated.");
            }
            catch (Exception ex)
            {
                this.logger.Error(ex.ToString);
            }
            this.logger.Trace("(-)");
        }
        /// <inheritdoc />
        public void Initialize()
        {
            this.logger.Trace("()");

            // Unlock wallet.
            if (this.coinService.IsWalletEncrypted())
            {
                this.coinService.WalletPassphrase(this.walletPassword, int.MaxValue);
            }

            using (BotDbContext context = this.contextFactory.CreateContext())
            {
                int addressesCount = context.UnusedAddresses.Count();

                // Generate addresses when running for the first time.
                if (addressesCount == 0)
                {
                    this.PregenerateAddresses(context);
                }
            }

            this.StartCheckingDepositsContinously();

            this.logger.Trace("(-)");
        }
Exemple #9
0
        private static void AddOneChatWithTwoForbiddenWordsAndOnePromotedMember(BotDbContext context)
        {
            var chat = new Chat(ChatId)
            {
                ChatId         = ChatId,
                ForbiddenWords = new List <ForbiddenChatWord>
                {
                    new ForbiddenChatWord {
                        Id = 1, Word = "abcd"
                    },
                    new ForbiddenChatWord {
                        Id = 2, Word = "1234"
                    },
                }
            };

            context.Chats.Add(chat);
            context.SaveChanges();

            var chatPromotedMember = new ChatToPromotedMember
            {
                Chat = chat,
                PromotedChatMember = context.PromotedMembers.Single(pm => pm.UserId == 1)
            };

            chat.PromotedMembers.Add(chatPromotedMember);
            context.SaveChanges();
        }
Exemple #10
0
 public WeatherTask(IWeatherService weatherService, BotDbContext db, IEnumerable <ISender> senders)
 {
     _weatherService = weatherService;
     _db             = db;
     _senders        = senders;
     _logger         = Log.ForContext <WeatherTask>();
 }
        public async Task GrantOrRevokePermission(string discordUserId, int permissionId, Func <string, Permission, BotDbContext, IDMChannel, Task> GrantOrRevoke)
        {
            //TODO: revise that block as it isn't optimal e.g. duplicate command usage is unnecessary
            if (Context.IsPrivate)
            {
                if (await _permManager.IsAllowedAsync(Types.PermissionType.ManagePermissions, Context.User))
                {
                    using (var dbContext = new BotDbContext(_config))
                    {
                        var channel = await Context.User.GetOrCreateDMChannelAsync();

                        var user = await dbContext.Users.FirstOrDefaultAsync(u => u.DiscordUserId == discordUserId);

                        var permission = await dbContext.Permissions.FirstOrDefaultAsync(p => p.Id == permissionId);

                        if (permission != null)
                        {
                            if (user == null)
                            {
                                user = new User()
                                {
                                    DiscordUserId = Context.User.Id.ToString()
                                };
                                await dbContext.Users.AddAsync(user);

                                await channel.SendMessageAsync("User not found. -> User added");
                            }
                            if (user.UserPermissions == null)
                            {
                                user.UserPermissions = new System.Collections.Generic.List <UserPermissions>();
                            }
                            await GrantOrRevoke(discordUserId, permission, dbContext, channel);
                        }
                        else
                        {
                            await channel.SendMessageAsync("Permission not found.");
                        }
                    }
                }
                else
                {
                    await ReplyAsync(AppSettings.PERMISSION_DENIED_RESPONSE);
                }
            }
            else
            {
                var content = Context.Message.Content;
                await Context.Message.DeleteAsync();

                var channel = await Context.User.GetOrCreateDMChannelAsync();

                await channel.SendMessageAsync($"This command is confidential. " +
                                               $"So it is only accepted in private channels. " +
                                               $"I removed your command from the other channel. " +
                                               $"Please try again here. " +
                                               $"Sorry for the inconvenience. " + Environment.NewLine +
                                               $"Your command was: {content}");
            }
        }
Exemple #12
0
 public IActionResult GetHistory()
 {
     using (BotDbContext context = this.contextFactory.CreateContext())
     {
         // Figure out how to do sorting on the database, issues with syntax.
         return(Ok(context.TipsHistory.ToList().OrderByDescending(t => t.CreationTime)));
     }
 }
Exemple #13
0
    public TestBase()
    {
        DefaultUser = new BotUser(1, "Архангельск", 351917, false, true, true, true);
        DefaultUserWithMaxReminds = new BotUser(2, "Архангельск", 351917, false, true, true, true);
        AdminUser = new BotUser(101010, "Архангельск", 351917, true, true, true, true);

        ApplicationContext = GetDbContext();
    }
Exemple #14
0
    public StartupTasks(BotDbContext db, IOptions <MailingOptions> options, IVkApi api)
    {
        _db      = db;
        _api     = api;
        _options = options.Value;

        InitJobsFromDatabase();
    }
Exemple #15
0
 public StravaService(AppOptions options, BotDbContext dbContext, ILogger <StravaService> logger,
                      IStravaApiClientService stravaApiService)
 {
     _options          = options;
     _logger           = logger;
     _dbContext        = dbContext;
     _stravaApiService = stravaApiService;
 }
        public AnswerToQuizResponseModel AnswerToQuiz(IUser user, string answer)
        {
            this.logger.Trace("({0}:'{1}')", nameof(answer), answer);

            if (answer.Length > 1024)
            {
                // We don't want to hash big strings.
                this.logger.Trace("(-)[ANSWER_TOO_LONG]");
                return(new AnswerToQuizResponseModel()
                {
                    Success = false
                });
            }

            string answerHash = Cryptography.Hash(answer);

            using (BotDbContext context = this.contextFactory.CreateContext())
            {
                foreach (QuizModel quiz in context.ActiveQuizes.ToList())
                {
                    if (DateTime.Now > (quiz.CreationTime + TimeSpan.FromMinutes(quiz.DurationMinutes)))
                    {
                        // Quiz expired but just not deleted yet.
                        continue;
                    }

                    if (quiz.AnswerHash == answerHash)
                    {
                        DiscordUserModel winner = this.GetOrCreateUser(context, user);

                        winner.Balance += quiz.Reward;
                        context.Update(winner);

                        context.ActiveQuizes.Remove(quiz);
                        context.SaveChanges();

                        this.logger.Debug("User {0} solved quiz with hash {1} and received a reward of {2}.", winner, quiz.AnswerHash, quiz.Reward);

                        var response = new AnswerToQuizResponseModel()
                        {
                            Success = true,
                            Reward  = quiz.Reward,
                            QuizCreatorDiscordUserId = quiz.CreatorDiscordUserId,
                            QuizQuestion             = quiz.Question
                        };

                        this.logger.Trace("(-)");
                        return(response);
                    }
                }
            }

            this.logger.Trace("(-)[QUIZ_NOT_FOUND]");
            return(new AnswerToQuizResponseModel()
            {
                Success = false
            });
        }
        /// <summary>
        /// Checks if money were deposited to an address associated with any user who has a deposit address.
        /// When money are deposited user's balance is updated.
        /// </summary>
        private void CheckDeposits(BotDbContext context)
        {
            this.logger.Trace("()");

            List <DiscordUserModel> usersToTrack = context.Users.AsQueryable().Where(x => x.DepositAddress != null).ToList();

            this.logger.Trace("Tracking {0} users.", usersToTrack.Count);
            try
            {
                foreach (DiscordUserModel user in usersToTrack)
                {
                    var addressHistory = blockCoreNodeAPI.GetAddressesHistory(user.DepositAddress).Result;

                    var transactionHistory = addressHistory.history.Where(x => x.accountName == AccountName).SelectMany(x => x.transactionsHistory);

                    var receivedByAddress = transactionHistory.Where(x => x.type == "received");

                    if (receivedByAddress.Count() > 0)
                    {
                        decimal totalRecivedByAddress = receivedByAddress.Sum(x => x.amount);

                        decimal balance = Money.FromUnit(totalRecivedByAddress, MoneyUnit.Satoshi).ToUnit(MoneyUnit.BTC);

                        if (balance > user.LastCheckedReceivedAmountByAddress)
                        {
                            decimal recentlyReceived = balance - user.LastCheckedReceivedAmountByAddress;

                            // Prevent users from spamming small amounts of coins.
                            // Also keep in mind if you'd like to change that- EF needs to be configured to track such changes.
                            // https://stackoverflow.com/questions/25891795/entityframework-not-detecting-changes-to-decimals-after-a-certain-precision
                            if (recentlyReceived < 0.01m)
                            {
                                this.logger.Trace("Skipping dust {0} for user {1}.", recentlyReceived, user);
                                continue;
                            }

                            this.logger.Debug("New value for received by address is {0}. Old was {1}. Address is {2}.", receivedByAddress, user.LastCheckedReceivedAmountByAddress, user.DepositAddress);

                            user.LastCheckedReceivedAmountByAddress = balance;
                            user.Balance += recentlyReceived;

                            context.Attach(user);
                            context.Entry(user).Property(x => x.Balance).IsModified = true;
                            context.Entry(user).Property(x => x.LastCheckedReceivedAmountByAddress).IsModified = true;
                            context.SaveChanges();

                            this.logger.Info("User '{0}' deposited {1}!. New balance is {2}.", user, recentlyReceived, user.Balance);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.logger.Error(ex.ToString);
            }

            this.logger.Trace("(-)");
        }
Exemple #18
0
        private static BotDbContext GetContextWithEmptyChat()
        {
            var context = new BotDbContext(CreateNewContextOptions());

            context.Database.EnsureDeleted();
            context.Chats.Add(new Chat(ChatId));
            context.SaveChanges();
            return(context);
        }
        private bool UserExists(BotDbContext context, ulong discordUserId)
        {
            this.logger.Trace("({0}:{1})", nameof(discordUserId), discordUserId);

            bool userExists = context.Users.Any(x => x.DiscordUserId == discordUserId);

            this.logger.Trace("(-):{0}", userExists);
            return(userExists);
        }
Exemple #20
0
        public static BotDbContext CreateMemoryDbContext()
        {
            var options = new DbContextOptionsBuilder <BotDbContext>()
                          .UseInMemoryDatabase("TestDb")
                          .Options;
            BotDbContext db = new BotDbContext(options);

            return(db);
        }
Exemple #21
0
 public CommandsService(IEnumerable <ITextCommand> textCommands,
                        IEnumerable <IKeyboardCommand> keyboardCommands,
                        BotDbContext context)
 {
     _textCommands     = textCommands;
     _keyboardCommands = keyboardCommands;
     _context          = context;
     _logger           = Log.ForContext <CommandsService>();
 }
        public void Setup()
        {
            _context = new BotDbContext();
            _context.Database.EnsureCreated();
            var piter = new Human("Piter", 19);

            _context.Add(piter);
            _context.SaveChanges();
        }
Exemple #23
0
        private static BotDbContext GetContextWithFilledChat()
        {
            var context = new BotDbContext(CreateNewContextOptions());

            context.Database.EnsureDeleted();
            AddOnePromotedChatMember(context);
            AddOneChatWithTwoForbiddenWordsAndOnePromotedMember(context);
            return(context);
        }
        public void WithdrawsSuccessfully()
        {
            this.testContext.CommandsManager.Withdraw(this.caller, 0.5m, "Addr");

            using (BotDbContext dbContext = this.testContext.CreateDbContext())
            {
                Assert.True(dbContext.Users.First().Balance == 9.5m);
            }
        }
Exemple #25
0
        public async Task TestCheckIsAdminNoUser()
        {
            BotDbContext db = Utils.CreateMemoryDbContext();

            TelegramHandler telegramHandler = new TelegramHandler(logger, configuration, db);
            bool            result          = await telegramHandler.CheckIsAdminAsync(123456789);

            Assert.IsFalse(result);
        }
Exemple #26
0
        public async Task TestAuthCountAsync()
        {
            await Utils.SetDefaultValueDbContextAsync();

            BotDbContext db = Utils.CreateMemoryDbContext();

            TelegramHandler telegramHandler = new TelegramHandler(logger, configuration, db);

            Assert.AreEqual(1, await telegramHandler.AuthCountAsync(123456789));
        }
 /// <summary>
 /// Перед обработкой сообщения проверяем, что пользователь есть в базе данных.
 /// </summary>
 /// <param name="chatId"></param>
 public static void CheckUserBeforeMessageProcessig(long chatId)
 {
     using (BotDbContext db = new BotDbContext(HelperDataBase.DB_OPTIONS))
     {
         if (IsUserInDatabase(db, chatId) == false)
         {
             AddUserToDb(db, chatId);
         }
     }
 }
        public async Task TestGenerateMenuCommandsAsyncNoAuth()
        {
            BotDbContext             db = Utils.CreateMemoryDbContext();
            TelegramHandler          telegramHandler = new TelegramHandler(logger, configuration, db);
            TelegramCommandGenerator telegramCommand = new TelegramCommandGenerator(telegramHandler);

            int count = (await telegramCommand.GenerateMenuCommandsAsync(123456789)).Count();

            Assert.AreEqual(3, count);
        }
        public async Task TestGenerateMenuCommandsAsyncNoAdmin()
        {
            BotDbContext             db = Utils.CreateMemoryDbContext();
            TelegramHandler          telegramHandler = new TelegramHandler(logger, configuration, db);
            TelegramCommandGenerator telegramCommand = new TelegramCommandGenerator(telegramHandler);

            var result = await telegramCommand.GenerateMenuCommandsAsync(123456789);

            Assert.AreEqual(1, result.Where(items => items.Item1 == TelegramCommand.AddAdminPermission).Count());
        }
Exemple #30
0
 public ScoreService(
     IConfiguration configuration,
     ILogger <ScoreService> logger,
     BotDbContext dbContext
     )
 {
     this.configuration = configuration;
     this.logger        = logger;
     this.dbContext     = dbContext;
 }