예제 #1
0
        private Func <Task> getChangeMeAction(CommandContext ctx, string propertyStr, string value)
        {
            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");
                }
                UserProperty property = UserProperty.Unknown;
                try
                {
                    property = (UserProperty)Enum.Parse(typeof(UserProperty), propertyStr);
                } catch {
                    throw new Exception("This is not an existing or editable property");
                }
                switch (property)
                {
                case UserProperty.MahjsoulName: UserDbService.SetMahjsoulName(userId, value); break;

                case UserProperty.MahjsoulFriendId: UserDbService.SetMahjsoulFriendId(userId, value); break;

                case UserProperty.TenhouName: UserDbService.SetTenhouName(userId, value); break;

                default: throw new Exception($"You can't change your {propertyStr}");
                }
                await ctx.RespondAsync($"<@{ctx.User.Id}>'s {property} has been changed to {value}.");
            }));
        }
예제 #2
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");
     }));
 }
예제 #3
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());
                }
            }));
        }
예제 #4
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());
                }
            }));
        }
예제 #5
0
        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));
            }));
        }
예제 #6
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);
            }));
        }
예제 #7
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");
     }));
 }
예제 #8
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");
     }));
 }
예제 #9
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);
     }));
 }
예제 #10
0
        public int AuthenticateUser(string loginId, string pwd, out string email)
        {
            var exp = new FilterExpression(this.EntityId);

            exp.Add(new FilterExpField("loginid", FilterOperationType.Equal, loginId));
            var data = UserDbService.GetUserInfoForAuth(loginId);

            email = null;

            if (data.Count() > 0)
            {
                var d = data.First();
                email = d.Get("emailid", "");

                var userpwd = Decrypt(d.Get("Password", ""));

                if (pwd == userpwd)
                {
                    return(d.Get("id", 0));
                }
            }

            return(-1);
        }
예제 #11
0
        public static IEnumerable <DbObject> GetUserRoles(int userId)
        {
            var roles = UserDbService.GetUserRoles(userId);

            return(roles);
        }
예제 #12
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}");
            }));
        }
예제 #13
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);
                }
            }
        }
예제 #14
0
        //Checks if a log is compatible with a player base
        private async Task <List <User> > GetUsersFromLog(RiichiGame log, List <User> users, CommandContext ctx)
        {
            int           nbPlayers  = log.Names.Length;
            List <string> notFound   = new List <string>();
            List <User>   foundUsers = new List <User>();

            for (int i = 0; i < nbPlayers; i++)
            {
                User foundUser = null;
                foreach (var user in users)
                {
                    switch (log.GameType)
                    {
                    case GameType.Mahjsoul:
                        bool matchName = user.MahjsoulName != null && user.MahjsoulName == log.Names[i];
                        bool matchId   = user.MahjsoulUserId != null && user.MahjsoulUserId == log.UserIds[i];
                        if (matchId && !matchName)
                        {
                            UserDbService.SetMahjsoulName(user.Id, log.Names[i]);
                            await ctx.RespondAsync($"Detected Bad user name for <@{user.Id}>. Changed from {user.MahjsoulName} to {log.Names[i]}, don't thank me ;)");
                        }
                        if (matchName && !matchId)
                        {
                            UserDbService.SetMahjsoulUserId(user.Id, log.UserIds[i]);
                        }
                        if (matchName || matchId)
                        {
                            foundUser = user;
                        }
                        break;

                    case GameType.Tenhou:
                        if (user.TenhouName != null && user.TenhouName == log.Names[i])
                        {
                            foundUser = user;
                        }
                        break;

                    default:
                        throw new Exception("Unsupported game type");
                    }
                    if (foundUser != null)
                    {
                        break;
                    }
                }
                if (foundUser == null)
                {
                    notFound.Add(log.Names[i]);
                }
                else
                {
                    foundUsers.Add(foundUser);
                }
            }
            if (notFound.Count > 0)
            {
                {
                    throw new Exception($"The log has names that do not match with any players: {string.Join(", ", notFound)}");
                }
            }
            return(foundUsers);
        }
예제 #15
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());
                }
            }));
        }
예제 #16
0
        public static List <DynamicObj> GetEntityAccessData(int masterId, int roleId)
        {
            var data = UserDbService.GetEntityAccessData(masterId, roleId);

            return(data);
        }
예제 #17
0
 public UserController(ILogger <UserController> logger, UserDbService service)
 {
     _logger  = logger;
     _service = service;
 }
예제 #18
0
 public void SetUp()
 {
     userDbService = ServiceBuilder <ChallengeDbContext, UserEntity> .GetService <UserDbService>();
 }