コード例 #1
0
 public void UpdateExemptsForGuildAsync(ulong gid)
 {
     using TheGodfatherDbContext db = this.dbb.CreateContext();
     this.guildExempts[gid]         = new ConcurrentHashSet <ExemptedEntity>(
         db.ExemptsMention.Where(ee => ee.GuildIdDb == (long)gid)
         );
 }
コード例 #2
0
        public async Task ScheduleAsync(ScheduledTask task)
        {
            ScheduledTaskExecutor?texec = null;

            try {
                using TheGodfatherDbContext db = this.dbb.CreateContext();
                if (task is Reminder rem)
                {
                    db.Reminders.Add(rem);
                    await db.SaveChangesAsync();
                }
                else if (task is GuildTask gt)
                {
                    db.GuildTasks.Add(gt);
                    await db.SaveChangesAsync();
                }
                else
                {
                    throw new ArgumentException("Unknown scheduled task type");
                }

                if (DateTimeOffset.Now + task.TimeUntilExecution <= this.LastReloadTime + this.ReloadSpan)
                {
                    texec = this.CreateTaskExecutor(task);
                }
            } catch (Exception e) {
                texec?.Dispose();
                Log.Warning(e, "Scheduling tasks failed");
                throw;
            }
        }
コード例 #3
0
        public async Task <IReadOnlyList <BankAccount> > GetTopAccountsAsync(ulong?gid = null, int amount = 10)
        {
            List <BankAccount> topAccounts;

            using TheGodfatherDbContext db = this.dbb.CreateContext();
            topAccounts = await
                              (gid is { } ? db.BankAccounts.Where(a => a.GuildIdDb == (long)gid) : db.BankAccounts)
コード例 #4
0
        public async Task UnregisterGuildAsync(ulong gid)
        {
            this.gcfg.TryRemove(gid, out _);
            using TheGodfatherDbContext db = this.dbb.CreateContext();
            GuildConfig gcfg = await db.Configs.FindAsync((long)gid);

            if (gcfg is { })
コード例 #5
0
        public async Task ModifyBankAccountAsync(ulong gid, ulong uid, Func <long, long> balanceModifier)
        {
            using TheGodfatherDbContext db = this.dbb.CreateContext();

            bool created = false;

            BankAccount?account = await this.GetAsync(gid, uid);

            if (account is null)
            {
                account = new BankAccount {
                    GuildId = gid,
                    UserId  = uid
                };
                created = true;
            }

            account.Balance = balanceModifier(account.Balance);
            if (account.Balance < 0)
            {
                account.Balance = 0;
            }

            if (created)
            {
                db.BankAccounts.Add(account);
            }
            else
            {
                db.BankAccounts.Update(account);
            }

            await db.SaveChangesAsync();
        }
コード例 #6
0
 private void UpdateEmojiReactionCount(TheGodfatherDbContext db)
 {
     this.erCount = this.erCount.ToDictionary(
         kvp => kvp.Key,
         kvp => db.EmojiReactions.Count(er => er.GuildIdDb == (long)MockData.Ids[kvp.Key])
         );
 }
コード例 #7
0
        public static async Task <RelationalDataReader> ExecuteSqlQueryAsync(this DatabaseFacade databaseFacade,
                                                                             string sql,
                                                                             TheGodfatherDbContext db,
                                                                             params object[] parameters)
        {
            IConcurrencyDetector concurrencyDetector = databaseFacade.GetService <IConcurrencyDetector>();

            using (concurrencyDetector.EnterCriticalSection()) {
                RawSqlCommand rawSqlCommand = databaseFacade
                                              .GetService <IRawSqlCommandBuilder>()
                                              .Build(sql, parameters);

                return(await rawSqlCommand
                       .RelationalCommand
                       .ExecuteReaderAsync(
                           new RelationalCommandParameterObject(
                               databaseFacade.GetService <IRelationalConnection>(),
                               parameterValues : rawSqlCommand.ParameterValues,
                               readerColumns : null,
                               context : db,
                               logger : null
                               )
                           ));
            }
        }
コード例 #8
0
        private void AssertSingleAndTest(TheGodfatherDbContext db, int index, string regex, bool match, params string[] tests)
        {
            if (tests is null || !tests.Any())
            {
                Assert.Fail("No tests provided to assert function.");
                return;
            }

            ForbiddenName filter = this.Service.GetGuildForbiddenNames(MockData.Ids[index]).Single(f => string.Compare(f.RegexString, regex, true) == 0);

            Assert.IsNotNull(filter);

            ForbiddenName dbf = db.ForbiddenNames
                                .Where(f => f.GuildIdDb == (long)MockData.Ids[index])
                                .AsEnumerable()
                                .Single(f => string.Compare(f.RegexString, regex, true) == 0);

            Assert.IsNotNull(dbf);

            foreach (string test in tests)
            {
                if (match)
                {
                    Assert.IsTrue(filter.Regex.IsMatch(test));
                }
                else
                {
                    Assert.IsFalse(filter.Regex.IsMatch(test));
                }
            }
        }
コード例 #9
0
 private static void SeedGuildData()
 {
     using TheGodfatherDbContext context = Database.CreateContext();
     context.Configs.AddRange(MockData.Ids.Select(id => new GuildConfig {
         GuildId = id
     }));
     context.SaveChanges();
 }
コード例 #10
0
        public async Task ExemptAsync(ulong gid, ExemptedEntityType type, IEnumerable <ulong> ids)
        {
            using TheGodfatherDbContext db = this.dbb.CreateContext();
            db.ExemptsMention.AddExemptions(gid, type, ids);
            await db.SaveChangesAsync();

            this.UpdateExemptsForGuildAsync(gid);
        }
コード例 #11
0
        public async Task <GuildConfig> GetConfigAsync(ulong gid)
        {
            GuildConfig?gcfg = null;

            using (TheGodfatherDbContext db = this.dbb.CreateContext())
                gcfg = await db.Configs.FindAsync((long)gid);
            return(gcfg ?? new GuildConfig());
        }
コード例 #12
0
 private void UpdateFilterCount(TheGodfatherDbContext db)
 {
     this.filterCount = this.filterCount.ToDictionary(
         kvp => kvp.Key,
         kvp => db.Filters
         .Count(f => f.GuildIdDb == (long)MockData.Ids[kvp.Key])
         );
 }
コード例 #13
0
 private void SetMockGuildConfig(TheGodfatherDbContext db)
 {
     foreach (KeyValuePair <ulong, GuildConfig> kvp in this.gcfg)
     {
         db.Attach(kvp.Value);
         db.Configs.Update(kvp.Value);
     }
 }
コード例 #14
0
 private void UpdateForbiddenNameCount(TheGodfatherDbContext db)
 {
     this.fnamesCount = this.fnamesCount.ToDictionary(
         kvp => kvp.Key,
         kvp => db.ForbiddenNames
         .Count(f => f.GuildIdDb == (long)MockData.Ids[kvp.Key])
         );
 }
コード例 #15
0
        public async Task <IReadOnlyList <Reminder> > GetRemindTasksForChannelAsync(ulong cid)
        {
            List <Reminder> reminders;

            using (TheGodfatherDbContext db = this.dbb.CreateContext())
                reminders = await db.Reminders.Where(r => r.ChannelIdDb == (long)cid).ToListAsync();
            return(reminders.AsReadOnly());
        }
コード例 #16
0
 private void AddMockData(TheGodfatherDbContext db)
 {
     db.PrivilegedUsers.Add(new PrivilegedUser {
         UserId = MockData.Ids[0]
     });
     db.PrivilegedUsers.Add(new PrivilegedUser {
         UserId = MockData.Ids[1]
     });
 }
コード例 #17
0
        public async Task <IReadOnlyList <ExemptedBackupEntity> > GetExemptsAsync(ulong gid)
        {
            List <ExemptedBackupEntity> exempts;

            using TheGodfatherDbContext db = this.dbb.CreateContext();
            exempts = await db.ExemptsBackup.Where(ex => ex.GuildIdDb == (long)gid).ToListAsync();

            return(exempts.AsReadOnly());
        }
コード例 #18
0
        public override Task <bool> ExecuteCheckAsync(CommandContext ctx, bool help)
        {
            if (ctx.Client.IsOwnedBy(ctx.User))
            {
                return(Task.FromResult(true));
            }

            using TheGodfatherDbContext db = ctx.Services.GetRequiredService <DbContextBuilder>().CreateContext();
            return(Task.FromResult(db.PrivilegedUsers.Find((long)ctx.User.Id) is { }));
コード例 #19
0
        private void AssertGuildForbiddenNameCount(TheGodfatherDbContext db, int index, int count)
        {
            Assert.AreEqual(count, db.ForbiddenNames.Count(f => f.GuildIdDb == (long)MockData.Ids[index]));
            IReadOnlyCollection <ForbiddenName> fs = this.Service.GetGuildForbiddenNames(MockData.Ids[index]);

            Assert.AreEqual(count, fs.Count);
            CollectionAssert.AllItemsAreUnique(fs.Select(f => f.Id));
            Assert.AreEqual(count, fs.Select(f => f.Regex.ToString()).Distinct().Count());
        }
コード例 #20
0
        public async Task UnexemptAsync(ulong gid, ExemptedEntityType type, IEnumerable <ulong> ids)
        {
            using TheGodfatherDbContext db = this.dbb.CreateContext();
            db.ExemptsMention.RemoveRange(
                db.ExemptsMention.Where(ex => ex.GuildId == gid && ex.Type == type && ids.Any(id => id == ex.Id))
                );
            await db.SaveChangesAsync();

            this.UpdateExemptsForGuildAsync(gid);
        }
コード例 #21
0
        public async Task <RssFeed?> GetByUrlAsync(string url)
        {
            url = url.ToLowerInvariant();
            RssFeed?feed = null;

            using TheGodfatherDbContext db = this.dbb.CreateContext();
            feed = await db.RssFeeds.SingleOrDefaultAsync(f => f.Url == url);

            return(feed);
        }
コード例 #22
0
 public void LoadData()
 {
     using TheGodfatherDbContext db = this.dbb.CreateContext();
     this.xps = new ConcurrentDictionary <ulong, ConcurrentDictionary <ulong, int> >(
         db.XpCounts
         .AsEnumerable()
         .GroupBy(xpc => xpc.GuildId)
         .ToDictionary(g => g.Key, g => new ConcurrentDictionary <ulong, int>(g.ToDictionary(g1 => g1.UserId, g1 => g1.Xp)))
         );
 }
コード例 #23
0
 public bool IsNameForbidden(ulong gid, string name, out ForbiddenName?match)
 {
     match = null;
     using (TheGodfatherDbContext db = this.dbb.CreateContext()) {
         match = this.InternalGetForbiddenNamesForGuild(db, gid)
                 .AsEnumerable()
                 .FirstOrDefault(fn => fn.Regex.IsMatch(name))
         ;
     }
     return(match is { });
コード例 #24
0
        public async Task DatabaseQuery(CommandContext ctx,
                                        [RemainingText, Description("desc-sql")] string query)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                throw new InvalidCommandUsageException(ctx, "cmd-err-dbq-sql-none");
            }

            var res = new List <IReadOnlyDictionary <string, string> >();

            using (TheGodfatherDbContext db = ctx.Services.GetRequiredService <DbContextBuilder>().CreateContext())
                using (RelationalDataReader dr = await db.Database.ExecuteSqlQueryAsync(query, db)) {
                    DbDataReader reader = dr.DbDataReader;
                    while (await reader.ReadAsync())
                    {
                        var dict = new Dictionary <string, string>();

                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            dict[reader.GetName(i)] = reader[i] is DBNull ? "NULL" : reader[i]?.ToString() ?? "NULL";
                        }

                        res.Add(new ReadOnlyDictionary <string, string>(dict));
                    }
                }

            if (!res.Any() || !res.First().Any())
            {
                await ctx.ImpInfoAsync(this.ModuleColor, Emojis.Information, "str-dbq-none");

                return;
            }

            int maxlen = 1 + res
                         .First()
                         .Select(r => r.Key)
                         .OrderByDescending(r => r.Length)
                         .First()
                         .Length;

            await ctx.PaginateAsync(
                "str-dbq-res",
                res.Take(25),
                row => {
                var sb = new StringBuilder();
                foreach ((string col, string val) in row)
                {
                    sb.Append(col).Append(new string(' ', maxlen - col.Length)).Append("| ").AppendLine(val);
                }
                return(Formatter.BlockCode(sb.ToString()));
            },
                this.ModuleColor,
                1
                );
        }
コード例 #25
0
        public async Task UpdateAsync(IEnumerable <Chicken> chickens)
        {
            if (!chickens.Any())
            {
                return;
            }

            using TheGodfatherDbContext db = this.dbb.CreateContext();
            db.UpdateRange(chickens);
            await db.SaveChangesAsync();
        }
コード例 #26
0
 private async Task<int> InternalRemoveByPredicateAsync(ulong gid, Func<Filter, bool> predicate)
 {
     using TheGodfatherDbContext db = this.dbb.CreateContext();
     var filters = this.InternalGetFiltersForGuild(db, gid)
         .AsEnumerable()
         .Where(predicate)
         .ToList();
     db.Filters.RemoveRange(filters);
     await db.SaveChangesAsync();
     return this.filters.GetValueOrDefault(gid)?.RemoveWhere(predicate) ?? 0;
 }
コード例 #27
0
        private async Task <IReadOnlyList <GameStats> > GetOrderedInternalAsync <T>(int amount, Func <GameStats, T> orderBy, Func <GameStats, T>?thenBy = null)
        {
            // FIXME inefficient - try to use IQueryable with LINQ Expressions ?
            List <GameStats> top;

            using (TheGodfatherDbContext db = this.dbb.CreateContext()) {
                List <GameStats> stats = await db.GameStats.ToListAsync();

                IOrderedEnumerable <GameStats> orderedStats = stats
                                                              .OrderByDescending(orderBy)
                ;
                if (thenBy is { })
コード例 #28
0
        public async Task <Chicken?> GetCompleteAsync(ulong gid, ulong uid)
        {
            Chicken?chicken = null;

            using (TheGodfatherDbContext db = this.dbb.CreateContext()) {
                chicken = await db.Chickens
                          .Include(c => c.Upgrades)
                          .ThenInclude(u => u.Upgrade)
                          .FirstOrDefaultAsync(c => c.GuildIdDb == (long)gid && c.UserIdDb == (long)uid);
            }
            return(chicken);
        }
コード例 #29
0
            public async Task <IReadOnlyList <PurchasedItem> > GetAllCompleteAsync(ulong uid)
            {
                List <PurchasedItem> res;

                using (TheGodfatherDbContext db = this.dbb.CreateContext()) {
                    DbSet <PurchasedItem> set = this.DbSetSelector(db);
                    res = await this.GroupSelector(set, uid)
                          .Include(i => i.Item)
                          .ToListAsync();
                }
                return(res.AsReadOnly());
            }
コード例 #30
0
 public void LoadData()
 {
     Log.Debug("Loading blocked entities");
     try {
         using TheGodfatherDbContext db = this.dbb.CreateContext();
         this.bChannels = new ConcurrentHashSet <ulong>(db.BlockedChannels.Select(c => c.Id));
         this.bUsers    = new ConcurrentHashSet <ulong>(db.BlockedUsers.Select(u => u.Id));
         this.bGuilds   = new ConcurrentHashSet <ulong>(db.BlockedGuilds.Select(g => g.Id));
     } catch (Exception e) {
         Log.Error(e, "Loading blocked entities failed");
     }
 }