Exemple #1
0
 private Func <Task> getRegisterUserAction(CommandContext ctx)
 {
     return(new Func <Task>(async() =>
     {
         var discordId = ctx.User.Id.ToString();
         var serverId = ctx.Guild.Id.ToString();
         var users = UserDbService.GetUsers();
         var servers = ServerDbService.GetServers(users);
         var server = servers[serverId];
         var config = LeagueConfigDbService.GetLeagueConfig(server.LeagueConfigId);
         if (!users.ContainsKey(discordId))
         {
             UserDbService.CreateUser(discordId, serverId, config);
         }
         if (!server.Users.Select(x => x.Id).Contains(discordId))
         {
             ServerDbService.AddUserToServer(discordId, serverId, false, false);
         }
         else
         {
             throw new Exception("You are already registered in this server");
         }
         ulong roleId = Convert.ToUInt64(server.LeagueRoleId);
         if (!ctx.Guild.Roles.ContainsKey(roleId))
         {
             throw new Exception("Error: League role not found");
         }
         await ctx.Member.GrantRoleAsync(ctx.Guild.Roles[roleId], "registering for riichi league");
         await ctx.RespondAsync($"<@{ctx.User.Id}> has been registered");
     }));
 }
Exemple #2
0
        private Func <Task> getListAction(CommandContext ctx)
        {
            return(new Func <Task>(async() =>
            {
                var users = UserDbService.GetUsers();
                var servers = ServerDbService.GetServers(users);
                var discordId = ctx.User.Id.ToString();
                var serverDiscordId = ctx.Guild.Id.ToString();

                int i = 1;
                StringBuilder sb = new StringBuilder();
                sb.Append($"Users registered in {ctx.Guild.Name}:\n");
                foreach (var user in servers[serverDiscordId].Users)
                {
                    sb.Append($"<@{user.Id}> majsoulName: {user.MahjsoulName} {(user.Id == discordId ? " <<< you" : "")}\n");
                    i++;
                }
                if (ctx != null && ctx.Member == null)
                {
                    await ctx.RespondAsync(sb.ToString());
                }
                else
                {
                    await ctx.Member.SendMessageAsync(sb.ToString());
                }
            }));
        }
Exemple #3
0
        private Func <Task> getDisplayLeagueConfigAction(CommandContext ctx, string inputServerId)
        {
            return(new Func <Task>(async() =>
            {
                var serverId = inputServerId;
                if (serverId == null && ctx.Guild == null)
                {
                    return;
                }
                if (serverId == null)
                {
                    serverId = ctx.Guild.Id.ToString();
                }
                var userId = ctx.User.Id.ToString();
                var allUsers = UserDbService.GetUsers();
                if (!allUsers.ContainsKey(userId))
                {
                    throw new Exception("You not registered in any server");
                }
                var allServers = ServerDbService.GetServers(allUsers);
                if (!allServers.ContainsKey(serverId))
                {
                    throw new Exception($"Server with id {serverId} does not exist");
                }
                var server = allServers[serverId];
                var configId = server.LeagueConfigId;
                var config = LeagueConfigDbService.GetLeagueConfig(configId);
                var sb = new StringBuilder();
                sb.AppendLine($"countPoints: {(config.CountPoints ? "Yes" : "No")}");
                sb.AppendLine($"startingPoints: {config.StartingPoints}");
                sb.AppendLine($"allowSanma: {(config.AllowSanma ? "Yes" : "No")}");
                sb.AppendLine($"uma3p1: {config.Uma3p1}");
                sb.AppendLine($"uma3p2: {config.Uma3p2}");
                sb.AppendLine($"uma3p3: {config.Uma3p3}");
                sb.AppendLine($"uma4p1: {config.Uma4p1}");
                sb.AppendLine($"uma4p2: {config.Uma4p2}");
                sb.AppendLine($"uma4p3: {config.Uma4p3}");
                sb.AppendLine($"uma4p4: {config.Uma4p4}");
                sb.AppendLine($"oka: {config.Oka}");
                sb.AppendLine($"penaltyLast: {config.PenaltyLast}");

                sb.AppendLine($"useEloSystem: {(config.UseEloSystem? "Yes" : "No")}");
                sb.AppendLine($"initialElo: {config.InitialElo}");
                sb.AppendLine($"minElo: {config.MinElo}");
                sb.AppendLine($"baseEloChangeDampening: {config.BaseEloChangeDampening}");
                sb.AppendLine($"eloChangeStartRatio: {config.EloChangeStartRatio}");
                sb.AppendLine($"eloChangeEndRatio: {config.EloChangeEndRatio}");
                sb.AppendLine($"trialPeriodDuration: {config.TrialPeriodDuration}");

                if (ctx.Member != null)
                {
                    await ctx.Member.SendMessageAsync(sb.ToString());
                }
                else
                {
                    await ctx.RespondAsync(sb.ToString());
                }
            }));
        }
Exemple #4
0
 private Func <Task> getSetTargetChannelAction(CommandContext ctx)
 {
     return(new Func <Task>(async() =>
     {
         var serverDiscordId = ctx.Guild.Id.ToString();
         ServerDbService.SetTargetChannel(serverDiscordId, ctx.Channel.Id.ToString());
         await ctx.RespondAsync($"<#{ctx.Channel.Id}> has been registered as scoring channel");
     }));
 }
Exemple #5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDeveloperExceptionPage();

            app.UseRouting();

            //Doklejal do odpowiedzi naglowek http
            app.Use(async(context, c) =>
            {
                context.Response.Headers.Add("Secret", "1234");
                await c.Invoke();
            });
            app.Use(async(context, next) =>
            {
                if (!context.Request.Headers.ContainsKey("Index"))
                {
                    context.Response.StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status401Unauthorized;
                    await context.Response.WriteAsync("Nie podales loginu i hasla");
                    return;
                }

                string index           = context.Request.Headers["Index"].ToString();
                IStudentsDbService dbs = new ServerDbService();

                if (!dbs.StudentExist(index))
                {
                    context.Response.StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status401Unauthorized;
                    await context.Response.WriteAsync("blendny login lub chaslo");
                    return;
                }



                await next();
            }

                    );

            app.UseMiddleware <LogginMiddleware>();

            //app.UseHttpsRedirection;

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
        private Func <Task> GetSubmitLogAction(CommandContext ctx, string gameId)
        {
            return(new Func <Task>(async() =>
            {
                var serverId = ctx.Guild.Id.ToString();
                var allUsers = UserDbService.GetUsers();
                var servers = ServerDbService.GetServers(allUsers);
                var server = servers[serverId];
                var serverUsers = server.Users;
                var log = await LogService.Instance.GetLog(gameId, 2);

                var users = await GetUsersFromLog(log, serverUsers, ctx);
                var gameResult = PrintGameResult(log, ctx.Client, users);
                var gameMsg = await ctx.RespondAsync($"I need all players to :o: or :x: to record or cancel this game\n{gameResult}");
                await context.AddPendingGame(ctx, gameMsg, new PendingGame(users.Select(x => x.Id.ToString()).ToArray(), server, log));
            }));
        }
Exemple #7
0
        private Func <Task> getSetOwnerAction(CommandContext ctx, DiscordUser targetDiscordUser, bool flag)
        {
            return(new Func <Task>(async() =>
            {
                var allUsers = UserDbService.GetUsers();
                var allServers = ServerDbService.GetServers(allUsers);
                var serverId = ctx.Guild.Id.ToString();
                var server = allServers[serverId];
                var userId = ctx.Member.Id.ToString();
                if (!server.Owners.Contains(allUsers[userId]))
                {
                    throw new Exception("You are not a owner of this bot");
                }
                var targetId = targetDiscordUser.Id.ToString();

                ServerDbService.SetIsOwner(serverId, targetId, flag);
                await Task.FromResult(false);
            }));
        }
Exemple #8
0
 private Func <Task> getRegisterUserAction(CommandContext ctx)
 {
     return(new Func <Task>(async() =>
     {
         var discordId = ctx.User.Id.ToString();
         var serverDiscordId = ctx.Guild.Id.ToString();
         var server = ServerDbService.GetServer(serverDiscordId);
         var config = LeagueConfigDbService.GetLeagueConfig(server.LeagueConfigId);
         UserDbService.CreateUser(discordId, serverDiscordId, config);
         ServerDbService.AddUserToServer(discordId, serverDiscordId, false, false);
         ulong roleId = Convert.ToUInt64(server.LeagueRoleId);
         if (!ctx.Guild.Roles.ContainsKey(roleId))
         {
             throw new Exception("Error: League role not found");
         }
         await ctx.Member.GrantRoleAsync(ctx.Guild.Roles[roleId], "registering for riichi league");
         await ctx.RespondAsync($"<@{ctx.User.Id}> has been registered");
     }));
 }
Exemple #9
0
 private Func <Task> getRegisterServerAction(CommandContext ctx)
 {
     return(new Func <Task>(async() =>
     {
         var displayName = ctx.User.Username;
         var discordId = ctx.User.Id.ToString();
         var serverDiscordId = ctx.Guild.Id.ToString();
         var leagueConfigId = LeagueConfigDbService.CreateLeague();
         var roleName = "KandoraLeague";
         ulong roleId = ctx.Guild.Roles.Where(x => x.Value.Name == roleName).Select(x => x.Key).FirstOrDefault();
         if (roleId == 0)
         {
             var role = await ctx.Guild.CreateRoleAsync(name: roleName, mentionable: true);
             roleId = role.Id;
         }
         ServerDbService.AddServer(serverDiscordId, ctx.Guild.Name, roleId.ToString(), roleName, leagueConfigId);
         await ctx.RespondAsync($"A Riichi league has started on {ctx.Guild.Name}!! \n");
     }));
 }
Exemple #10
0
 private Func <Task> getUnRegisterUserAction(CommandContext ctx)
 {
     return(new Func <Task>(async() =>
     {
         var displayName = ctx.User.Username;
         var discordId = ctx.User.Id.ToString();
         var serverDiscordId = ctx.Guild.Id.ToString();
         var users = UserDbService.GetUsers();
         var servers = ServerDbService.GetServers(users);
         var server = servers[serverDiscordId];
         ServerDbService.RemoveUserFromServer(discordId, serverDiscordId);
         ulong roleId = Convert.ToUInt64(server.LeagueRoleId);
         if (!ctx.Guild.Roles.ContainsKey(roleId))
         {
             throw new Exception("Error: League role not found");
         }
         await ctx.Member.RevokeRoleAsync(ctx.Guild.Roles[roleId], "removing from riichi league");
         await ctx.RespondAsync($"<@{ctx.User.Id}> has been removed from league");
     }));
 }
Exemple #11
0
        protected static async Task executeCommand(CommandContext ctx, Func <Task> command, bool userMustBeRegistered = true, bool userMustBeInChannel = true, bool serverMustBeRegistered = true)
        {
            var commandStr = "command";

            try
            {
                if (userMustBeInChannel && (ctx.Channel == null || ctx.Guild == null))
                {
                    throw new Exception("You must be in a text channel for that command.");
                }
                string serverId  = (ctx.Guild.Id.ToString());
                string channelId = (ctx.Channel.Id.ToString());
                string userId    = (ctx.User.Id.ToString());
                Server server    = null;
                if (serverMustBeRegistered || userMustBeInChannel)
                {
                    server = ServerDbService.GetServer(serverId);
                }
                if (userMustBeInChannel && (server == null || server.TargetChannelId != channelId))
                {
                    throw new SilentException();
                }
                if (userMustBeRegistered && !ServerDbService.isUserOnServer(userId, serverId))
                {
                    throw new Exception($"<@{userId}> is not registered yet, use !register to enter the league.");
                }
                DbService.Begin(commandStr);
                await command.Invoke();

                DbService.Commit(commandStr);
            }
            catch (Exception e)
            {
                if (!(e is SilentException))
                {
                    await ctx.RespondAsync(e.Message);
                }
                DbService.Rollback(commandStr);
            }
        }
Exemple #12
0
 private Func <Task> getRegisterDummyAction(CommandContext ctx)
 {
     return(new Func <Task>(async() =>
     {
         var discordId = ctx.User.Id.ToString();
         var serverDiscordId = ctx.Guild.Id.ToString();
         var server = ServerDbService.GetServer(serverDiscordId);
         var config = LeagueConfigDbService.GetLeagueConfig(server.LeagueConfigId);
         var heatiro = "323096688904634377";
         var clubapero = "198974501709414401";
         var Neral = "273192430172372993";
         UserDbService.CreateUser(heatiro, serverDiscordId, config);
         UserDbService.CreateUser(clubapero, serverDiscordId, config);
         UserDbService.CreateUser(Neral, serverDiscordId, config);
         ServerDbService.AddUserToServer(heatiro, serverDiscordId, false, false);   //Heatiro
         ServerDbService.AddUserToServer(clubapero, serverDiscordId, false, false); //clubapero
         ServerDbService.AddUserToServer(Neral, serverDiscordId, false, false);     //Neral
         UserDbService.SetMahjsoulName(heatiro, "heairo");
         UserDbService.SetMahjsoulName(Neral, "Neral");
         UserDbService.SetMahjsoulName(clubapero, "clubapero");
         await Task.FromResult(false);
     }));
 }
Exemple #13
0
        private Func <Task> getChangeLeagueConfigAction(CommandContext ctx, string serverId, string paramName, string value)
        {
            return(new Func <Task>(async() =>
            {
                CfgPrm property = CfgPrm.UNKNOWN;
                try
                {
                    property = (CfgPrm)Enum.Parse(typeof(CfgPrm), paramName);
                } catch {
                    throw new Exception("This is not an existing property");
                }
                var userId = ctx.User.Id.ToString();
                var allUsers = UserDbService.GetUsers();
                var allServers = ServerDbService.GetServers(allUsers);
                if (!allServers.ContainsKey(serverId))
                {
                    throw new Exception($"Server with id {serverId} does not exist");
                }
                var server = allServers[serverId];
                if (!server.Admins.Select(x => x.Id).Contains(userId))
                {
                    throw new Exception("You must be admin of this server to change a league config");
                }
                var configId = server.LeagueConfigId;

                switch (property)
                {
                case CfgPrm.name: LeagueConfigDbService.SetConfigValue(paramName, configId, value); break;

                case CfgPrm.description: LeagueConfigDbService.SetConfigValue(paramName, configId, value); break;

                case CfgPrm.countPoints: LeagueConfigDbService.SetConfigValue(paramName, configId, value.ToLower() == "yes"); break;

                case CfgPrm.allowSanma: LeagueConfigDbService.SetConfigValue(paramName, configId, value.ToLower() == "yes"); break;

                case CfgPrm.startingPoints: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma3p1: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma3p2: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma3p3: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma4p1: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma4p2: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma4p3: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma4p4: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.oka: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.penaltyLast: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.useEloSystem: LeagueConfigDbService.SetConfigValue(paramName, configId, value.ToLower() == "yes"); break;

                case CfgPrm.initialElo: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.minElo: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.baseEloChangeDampening: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.eloChangeStartRatio: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.eloChangeEndRatio: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.trialPeriodDuration: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                default: throw new Exception($"You cannot change {paramName}");
                }
                await ctx.RespondAsync($"Changed param: {paramName}={value}");
            }));
        }
Exemple #14
0
        public async static Task OnPendingGameReaction(DiscordClient sender, DiscordMessage msg, DiscordEmoji emoji, DiscordUser user, bool added)
        {
            var  kanContext = KandoraContext.Instance;
            var  msgId      = msg.Id;
            var  userId     = user.Id.ToString();
            var  game       = kanContext.PendingGames[msgId];
            bool result     = false;
            var  okEmoji    = DiscordEmoji.FromName(sender, Reactions.OK);
            var  noEmoji    = DiscordEmoji.FromName(sender, Reactions.NO);

            if (emoji.Id == okEmoji.Id)
            {
                result = game.TryChangeUserOk(userId, isAdd: added);
            }
            else if (emoji.Id == noEmoji.Id)
            {
                result = game.TryChangeUserNo(userId, isAdd: added);
            }
            if (!result && added)
            {
                await msg.DeleteReactionAsync(emoji, user);
            }
            if (game.IsCancelled)
            {
                await msg.ModifyAsync($"All players have voted {noEmoji}, this log won't be recorded");

                kanContext.PendingGames.Remove(msgId);
            }
            if (game.IsValidated)
            {
                DbService.Begin("recordgame");
                try
                {
                    var serverId     = msg.Channel.GuildId.ToString();
                    var users        = UserDbService.GetUsers();
                    var servers      = ServerDbService.GetServers(users);
                    var server       = servers[serverId];
                    var leagueConfig = LeagueConfigDbService.GetLeagueConfig(server.LeagueConfigId);

                    if (game.Log == null)
                    {
                        ScoreDbService.RecordIRLGame(game.UserIds, game.Scores, server, leagueConfig);
                    }
                    else
                    {
                        ScoreDbService.RecordOnlineGame(game.Log, server);
                    }
                    kanContext.PendingGames.Remove(msgId);
                    await msg.RespondAsync($"All players have voted {okEmoji}, this log has been recorded!");

                    await msg.DeleteReactionsEmojiAsync(okEmoji);

                    await msg.DeleteReactionsEmojiAsync(noEmoji);

                    DbService.Commit("recordgame");
                }
                catch (Exception e)
                {
                    DbService.Rollback("recordgame");
                    await msg.RespondAsync(e.Message);
                }
            }
        }
Exemple #15
0
        public IActionResult EnrollmentsController(Student s)
        {
            IStudentsDbService service = new ServerDbService();

            return(null);
        }
Exemple #16
0
        private Func <Task> getDisplayMeAction(CommandContext ctx)
        {
            return(new Func <Task>(async() =>
            {
                var userId = ctx.User.Id.ToString();
                var allUsers = UserDbService.GetUsers();
                if (!allUsers.ContainsKey(userId))
                {
                    throw new Exception("You are not registered in any server");
                }
                var user = allUsers[userId];
                var allServers = ServerDbService.GetServers(allUsers);
                var servers = allServers.Values.Where(x => x.Users.Contains(user));
                var sb = new StringBuilder();

                sb.AppendLine("Mahjsoul info:");
                sb.AppendLine($"\t{UserProperty.MahjsoulName}: {(user.MahjsoulName == null ? "N/A" : user.MahjsoulName)} (can be changed)");
                sb.AppendLine($"\t{UserProperty.MahjsoulFriendId}: {(user.MahjsoulFriendId == null ? "N/A" : user.MahjsoulFriendId)} (can be changed)");
                sb.AppendLine($"\tMahjsoulInternalUserId: {(user.MahjsoulUserId == null ? "N/A" : user.MahjsoulUserId)}");
                sb.AppendLine($"\tLast known rank: N/A"); // TODO
                sb.AppendLine("Tenhou info:");
                sb.AppendLine($"\t{UserProperty.TenhouName}: {(user.TenhouName == null ? "N/A" : user.TenhouName)} (can be changed)");
                sb.AppendLine($"\tLast known rank: N/A"); // TODO
                sb.AppendLine($"DiscordId: {user.Id}");
                sb.AppendLine($"Leagues you are registered in:");
                foreach (var server in servers)
                {
                    var rankings = RankingDbService.GetServerRankings(server.Id);
                    var playersRank = new Dictionary <string, float>();
                    var playersTime = new Dictionary <string, DateTime>();
                    //Get the last ranking for each player by iterating through the whole list
                    foreach (var ranking in rankings)
                    {
                        var playerId = ranking.UserId;
                        float rank;
                        DateTime time;
                        if (!playersRank.TryGetValue(playerId, out rank) || !playersTime.TryGetValue(playerId, out time))
                        {
                            playersRank.Add(playerId, ranking.NewRank);
                            playersTime.Add(playerId, ranking.Timestamp);
                        }
                        else
                        {
                            if (ranking.Timestamp.CompareTo(time) > 0)
                            {
                                playersRank[playerId] = ranking.NewRank;
                                playersTime[playerId] = ranking.Timestamp;
                            }
                        }
                    }

                    //Sort the list and compute the user's rank and ELO
                    List <KeyValuePair <string, float> > flatRanksSorted = playersRank.ToList();
                    flatRanksSorted.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value));
                    var nbPlayers = server.Users.Count;
                    var userRank = 1;
                    float userElo = -1;
                    foreach (var rank in flatRanksSorted)
                    {
                        if (rank.Key == userId)
                        {
                            userElo = rank.Value;
                            break;
                        }
                        else
                        {
                            userRank++;
                        }
                    }
                    sb.AppendLine($"\t{server.LeagueName}({server.DisplayName}): {userRank}/{nbPlayers} (R{userElo})");
                }
                if (ctx != null && ctx.Member == null)
                {
                    await ctx.RespondAsync(sb.ToString());
                }
                else
                {
                    await ctx.Member.SendMessageAsync(sb.ToString());
                }
            }));
        }