Ejemplo n.º 1
0
        protected override void OnOpen()
        {
            using var db = Program.Services.GetRequiredService <ChessDbContext>();
            try
            {
                if (!Handler.findToken(Context.CookieCollection[AuthToken.SessionToken].Value, out var bUser, out _))
                {
                    Context.WebSocket.Close(CloseStatusCode.Normal, "Authentication failed.");
                    return;
                }
                Player = db.Players.FirstOrDefault(x => x.DiscordAccount == ChessService.cast(bUser.Id));
            } catch
            {
                Context.WebSocket.Close(CloseStatusCode.Normal, "Forbidden - must authenticate.");
                return;
            }
            var id = Guid.Parse(Context.QueryString.Get("id"));

            if (ChessService.TimedGames.TryGetValue(id, out var g))
            {
                Game = g;
                Game.ListeningWS.Add(this);
            }
            if (Game.White.Id == Player.Id)
            {
                Changeable = PlayerSide.White;
            }
            else if (Game.Black.Id == Player.Id)
            {
                Changeable = PlayerSide.Black;
            }
            SendStatus(((DateTimeOffset)DateTime.UtcNow).ToUnixTimeSeconds(), true);
        }
Ejemplo n.º 2
0
        public override PreconditionResult Check(APIContext context)
        {
            if (context.User == null)
            {
                throw new RedirectException("/login", "You must be logged in");
            }
            using var db = Program.Services.GetRequiredService <ChessDbContext>();
            var player = db.Players.FirstOrDefault(x => x.DiscordAccount == ChessService.cast(context.User.Id));

            if (player == null)
            {
                return(PreconditionResult.FromError("Either no connected account, or not found"));
            }
            string newline = context.WantsHTML ? "<br/>" : "\n";

            if (DirectCompare)
            {
                return(player.Permission == _perm?PreconditionResult.FromSuccess() : PreconditionResult.FromError($"Permission failure." + newline +
                                                                                                                  $"You have: {player.Permission}" + newline +
                                                                                                                  $"Requires exactly: {_perm}"));
            }
            return(player.Permission.HasFlag(_perm) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError($"Permission failure." + newline +
                                                                                                                      $"You have: {player.Permission}" + newline +
                                                                                                                      $"Requires: {_perm}"));
        }
Ejemplo n.º 3
0
 public ChessBase(APIContext c, string path) : base(c, path)
 {
     DB = Program.Services.GetRequiredService <ChessDbContext>();
     if (c.User != null)
     {
         SelfPlayer = DB.Players.FirstOrDefault(x => x.DiscordAccount == ChessService.cast(c.User.Id));
     }
 }
Ejemplo n.º 4
0
 public ChessEngineResult Get(string fen, int depth)
 {
     try
     {
         Console.WriteLine("{0} - parsing fen\n{1}", DateTime.Now, fen);
         var service      = new ChessService();
         var moveResponse = service.GetMoveResponse(fen, depth);
         Console.WriteLine("{0} - generated move:{1}", DateTime.Now, moveResponse);
         return(ChessEngineResult.New(moveResponse));
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
         return(new ChessEngineResult {
             ErrorMessage = e.Message
         });
     }
 }
Ejemplo n.º 5
0
 public ChessController(ChessDataProvider db, ChessService serv)
 {
     _DB   = db;
     _Serv = serv;
 }
Ejemplo n.º 6
0
 public PlayAIController(ChessContext context, ChessService chessService)
 {
     this.context      = context;
     this.chessService = chessService;
 }
Ejemplo n.º 7
0
 public ChessModule(ChessService chessService, ChessHelper chessHelper)
 {
     _chessHelper  = chessHelper;
     _chessService = chessService;
 }
Ejemplo n.º 8
0
 public ChessServiceFixture()
 {
     _sut = new ChessService();
 }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            var data = new ChessDataProvider();
            var cs   = new ChessService(data);

            var valid  = cs.IsMoveValid(PieceType.Pawn, null, new Point(0, -1));
            var valid2 = cs.IsMoveValid(PieceType.Pawn, null, new Point(0, 1));
            var valid3 = cs.IsMoveValid(PieceType.Pawn, null, null);


            //var p = new Point(0, 0);
            var board = new Tile[8, 8];

            for (int y = 0; y < 8; y++)
            {
                for (int x = 0; x < 8; x++)
                {
                    board[x, y] = new Tile();
                }
            }
            Action <int> resetBoard = (int val) =>
            {
                for (int y = 0; y < 8; y++)
                {
                    for (int x = 0; x < 8; x++)
                    {
                        board[x, y].Value = val;
                    }
                }
                board[4, 4].Value = 5;
            };

            resetBoard(0);

            //var ks = new[,] { { -2, 1 }, { -2, -1 } };
            //
            //st.Value = 5;

            Console.WriteLine("CLEAR");
            Console.WriteLine(RenderDim(board));

            //foreach (var p in pcs)
            //{

            //    foreach (var item in p.MoveToPoints)
            //    {
            //        var x = (4 + item.X);
            //        var y = (4 + item.Y);
            //        if (x.InRange(0,7) && y.InRange(0, 7))
            //        {
            //            board[x, y].Value = 1;
            //        }
            //    }
            //    Console.WriteLine(p.Type.ToString().ToUpper());
            //    Console.WriteLine(RenderDim(board));
            //    resetBoard(0);
            //}

            //board[].Value = 2;
            //MoveK(board, ks);
            //board[2, 4].Value = 1;



            Console.ReadKey();
        }
Ejemplo n.º 10
0
        public static string getUrl(ulong id, Action <MSScopeOptions> action = null)
        {
            var msScope = new MSScopeOptions();

            if (action == null)
            {
                action = x =>
                {
                    x.OpenId    = true;
                    x.User_Read = true;
                }
            }
            ;
            action(msScope);
            string stateValue = id.ToString();

            stateValue += "." + Program.ToBase64(msScope.ToString());
            var ru  = new RequestUrl($"https://login.microsoftonline.com/{Program.Configuration["ms_auth:tenant_id"]}/oauth2/v2.0/authorize");
            var url = ru.CreateAuthorizeUrl(
                clientId: Program.Configuration["ms_auth:client_id"],
                responseType: "id_token code",
                responseMode: "form_post",
                redirectUri: Handler.LocalAPIUrl + "/login/msoauth",
                nonce: DateTime.Now.DayOfYear.ToString(),
                state: stateValue,
                scope: msScope.GetScopes());

            Console.WriteLine(url);
            return(url);
        }

        bool actOnUserProfile(TokenResponse response, HttpClient client)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");

            request.Headers.Add("Authorization", "Bearer " + response.AccessToken);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var identityResponse = client.SendAsync(request).Result;

            if (!identityResponse.IsSuccessStatusCode)
            {
                RespondRaw("Could not complete Oauth", identityResponse.StatusCode);
                return(false);
            }
            var content = identityResponse.Content.ReadAsStringAsync().Result;
            var jobj    = JObject.Parse(content);

            Context.User.VerifiedEmail = jobj["mail"].ToObject <string>();
            Context.User.IsVerified    = true;
            if (string.IsNullOrWhiteSpace(Context.User.Name) || Context.User.Name == Context.User.Id.ToString())
            {
                Context.User.OverrideName = jobj["displayName"].ToObject <string>();
            }
            var service = Program.Services.GetRequiredService <ChessService>();

            if (service != null && !Context.User.ServiceUser && !Context.User.GeneratedUser)
            {
                using var db = Program.Services.GetRequiredService <ChessDbContext>();
                string name     = $"{jobj["givenName"]} {jobj["surname"].ToObject<string>()[0]}";
                var    existing = db.Players.AsQueryable().FirstOrDefault(x => x.Name == name && !x.IsBuiltInAccount);
                if (existing != null)
                {
                    existing.ConnectedAccount = Context.User.Id;
                }
                else
                {
                    var chs = db.Players.AsQueryable().FirstOrDefault(x => x.DiscordAccount == ChessService.cast(Context.User.Id) && !x.IsBuiltInAccount);
                    if (chs != null)
                    {
                        chs.Name = name;
                    }
                }
                service.OnSave();
            }
            return(true);
        }

        bool actOnTeams(TokenResponse response, HttpClient client)
        {
            var teamsRequest = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/joinedTeams");

            teamsRequest.Headers.Add("Authorization", "Bearer " + response.AccessToken);
            teamsRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var teamsResponse = client.SendAsync(teamsRequest).Result;

            if (!teamsResponse.IsSuccessStatusCode)
            {
                RespondRaw("Could not retrieve your teams information", teamsResponse.StatusCode);
                return(false);
            }
            var content    = teamsResponse.Content.ReadAsStringAsync().Result;
            var jobj       = JObject.Parse(content);
            var jvalue     = jobj["value"];
            var teamsArray = (JArray)jvalue;
            Dictionary <string, string> classes = new Dictionary <string, string>();

            foreach (JToken jTeam in teamsArray)
            {
                var name  = jTeam["displayName"].ToObject <string>();
                var split = name.Split('-');
                if (split.Length != 2)
                {
                    continue;
                }
                // class - Subject
                // eg
                // 1Mt3 - Maths
                classes[split[0].Trim()] = split[1].Trim();
            }
            Context.User.Classes = classes;
            return(true);
        }