예제 #1
0
        // "main" scene constructor. The constructor is called by the server when the scene is created.
        //
        public Main(ISceneHost scene)
        {
            _scene = scene;
            _env = _scene.GetComponent<IEnvironment>();
            _log = _scene.GetComponent<ILogger>();
            _log.Debug("server", "starting configuration");

            // we configure the functions that will be called by the Connecting, Connected and Disconnected events.
            // Connecting is called when a client tries to connect to the server. Please use this event to prevent player form accessing the server.
            // Connected is called when a client is already connected.
            // Disconnected is called when a client is already disconnected.
            _scene.Connecting.Add(OnConnecting);
            _scene.Connected.Add(OnConnected);
            _scene.Disconnected.Add(OnDisconnect);

            // We configure the routes and procedure the client can use.
            // A route is used for "one-shot" messages that don't need response such as position updates.
            // Produres send a response to the client. It's better to use them when client have to wait for a response from the server such as being hit.
            // Procedures use more bandwidth than regular routes.
            //
            // In our case, the server mostly has procedures as the client always needs to wait for a response from the server since it controls the game.
            _scene.AddProcedure("play", OnPlay);
            _scene.AddProcedure("click", OnClick);
            _scene.AddProcedure("update_leaderBoard", OnUpdateLeaderBoard);

            // this route is only used by the client to disconnect from the game (not the server) because it doesn't have to wait for the server to stop playing.
            _scene.AddRoute("exit", OnExit);

            //The starting and shutdown event are called when the scene is launched and shut down. these are useful if you need to initiate the server logic or save the game state before going down.
            _scene.Starting.Add(OnStarting);
            _scene.Shuttingdown.Add(OnShutdown);

            _log.Debug("server", "configuration complete");
        }
 public StickyPlatformsServer(ISceneHost scene)
 {
     mScene = scene;
     scene.AddProcedure("joinGame", joinGameProcedure);
     scene.AddProcedure("getPlayerList", ctx =>
     {
         ctx.SendValue(mPlayers.Values.Where(player => player.hp > 0));
         return(Task.FromResult(true));
     });
     scene.Disconnected.Add(onDisconnect);
     scene.AddRoute("spawn", onPlayerSpawn, _ => _);
     scene.AddRoute("updateHp", updateHp, _ => _);
     scene.AddRoute("updatePhysics", updatePhysics, _ => _);
     scene.AddRoute("updateKeys", updateKeys, _ => _);
 }
예제 #3
0
        private void SceneCreated(ISceneHost scene)
        {
            string kind;

            if (scene.Metadata.TryGetValue(METADATA_KEY, out kind))
            {
                var logger = scene.DependencyResolver.Resolve <ILogger>();
                try
                {
                    var config = Configs[kind];


                    var matchmakingService = scene.DependencyResolver.Resolve <IMatchmakingService>();
                    matchmakingService.Init(scene);

                    scene.Disconnected.Add(args => matchmakingService.CancelMatch(args.Peer));
                    scene.AddProcedure("match.find", matchmakingService.FindMatch);
                    scene.AddRoute("match.ready.resolve", matchmakingService.ResolveReadyRequest, r => r);
                    scene.AddRoute("match.cancel", matchmakingService.CancelMatch, r => r);

                    //Start matchmaking
                    scene.RunTask(matchmakingService.Run);
                }
                catch (Exception ex)
                {
                    logger.Log(LogLevel.Error, "plugins.matchmaking", $"An exception occured when creating scene {scene.Id}.", ex);
                    throw;
                }
            }
        }
예제 #4
0
        public void RegisterControllers()
        {
            var type = typeof(T);

            foreach (var method in type.GetMethods())
            {
                var procedureName = GetProcedureName(type, method);
                if (IsRawAction(method))
                {
                    var ctxParam        = Expression.Parameter(typeof(RequestContext <IScenePeerClient>), "ctx");
                    var controllerParam = Expression.Parameter(typeof(T), "controller");
                    var callExpr        = Expression.Call(controllerParam, method, ctxParam);

                    var action = Expression.Lambda <Func <T, RequestContext <IScenePeerClient>, Task> >(callExpr, controllerParam, ctxParam).Compile();
                    _scene.AddProcedure(procedureName, ctx => ExecuteRpcAction(ctx, action, procedureName));
                }
                else if (IsRawRoute(method))
                {
                    var ctxParam        = Expression.Parameter(typeof(Packet <IScenePeerClient>), "ctx");
                    var controllerParam = Expression.Parameter(typeof(T), "controller");
                    var callExpr        = Expression.Call(controllerParam, method, ctxParam);

                    var action = Expression.Lambda <Func <T, Packet <IScenePeerClient>, Task> >(callExpr, controllerParam, ctxParam).Compile();
                    _scene.AddRoute(procedureName, packet => ExecuteRouteAction(packet, action, procedureName), _ => _);
                }
            }
        }
        public InAppNotificationProvider(ISceneHost scene, ISerializer serializer, ILogger logger, IConfiguration configuration, IUserSessions userSessions, InAppNotificationRepository repository)
        {
            _scene          = scene;
            this.serializer = serializer;
            _logger         = logger;
            _repository     = repository;

            configuration.SettingsChanged += (_, settings) => ApplyConfig(settings);
            ApplyConfig(configuration.Settings);

            _userSessions = userSessions;


            _scene.Connected.Add(OnConnected);

            _scene.AddProcedure("inappnotification.acknowledgenotification", async(RequestContext <IScenePeerClient> ctx) =>
            {
                var notificationId = ctx.ReadObject <string>();

                if (string.IsNullOrEmpty(notificationId))
                {
                    throw new ClientException("Bad notificationId.");
                }

                await AcknowledgeNotification(notificationId);
            });
        }
        public Test(ISceneHost scene)
        {
            _scene = scene;
            _scene.GetComponent<ILogger>().Debug("server", "starting configuration");

            _scene.AddProcedure("test_rpc", onTest);
               _scene.GetComponent<ILogger>().Debug("server", "configuration complete");
        }
예제 #7
0
        public GameScene(ISceneHost scene)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debugger.Break();
            }
            _scene = scene;

            _scene.Connected.Add(OnConnected);
            _scene.Disconnected.Add(OnDisconnected);
            _scene.AddRoute("position.update", OnPositionUpdate);
            _scene.AddProcedure("getShipInfos", OnGetShipInfos);
            _scene.AddProcedure("ship.killCount", OnGetShipKillCount);
            _scene.AddProcedure("skill", UseSkill);
            _scene.Starting.Add(OnStarting);
            _scene.Shuttingdown.Add(OnShutdown);
        }
예제 #8
0
 public ChatServer(ISceneHost scene)
 {
     _scene = scene;
     _env   = _scene.GetComponent <IEnvironment>();
     _scene.AddProcedure("GetUsersInfos", OnGetUsersInfos);
     _scene.AddRoute("UpdateInfo", OnUpdateInfo);
     _scene.AddRoute("chat", OnMessageReceived);
     _scene.Connected.Add(OnConnected);
     _scene.Disconnected.Add(OnDisconnected);
 }
 public ChatServer(ISceneHost scene)
 {
     _scene = scene;
     _env = _scene.GetComponent<IEnvironment>();
     _scene.AddProcedure("GetUsersInfos", OnGetUsersInfos);
     _scene.AddRoute("UpdateInfo", OnUpdateInfo);
     _scene.AddRoute("chat", OnMessageReceived);
     _scene.Connected.Add(OnConnected);
     _scene.Disconnected.Add(OnDisconnected);
 }
예제 #10
0
        public static TesterBehavior AddTesterBehaviorToScene(ISceneHost scene)
        {
            var result = new TesterBehavior(scene);

            scene.Starting.Add(result.OnStarting);

            scene.Connected.Add(result.OnConnected);
            scene.Disconnected.Add(result.OnDisconnected);

            scene.AddRoute("echo", result.OnEcho);
            scene.AddRoute("transfert", result.OnTransfert);
            scene.AddRoute("broadcast", result.OnBroadcast);

            scene.AddProcedure("rpc", result.OnRpc);
            scene.AddProcedure("rpcping", result.OnRpcPing);

            scene.Shuttingdown.Add(result.OnShutDown);

            return result;
        }
 public void Init(ISceneHost scene)
 {
     _scene = scene;
     _env = _scene.GetComponent<IEnvironment>();
     _log = _scene.GetComponent<ILogger>();
     _scene.AddProcedure("RegisterObject", OnRegisterObject);
     _scene.AddRoute("RemoveObject", OnRemoveObject);
     _scene.AddRoute("UpdateSynchedObject", OnUpdateObject);
     _scene.Connected.Add(OnClientConnected);
     _scene.Disconnected.Add(OnClientDisconnected);
 }
예제 #12
0
        public static TesterBehavior AddTesterBehaviorToScene(ISceneHost scene)
        {
            var result = new TesterBehavior(scene);

            scene.Starting.Add(result.OnStarting);

            scene.Connected.Add(result.OnConnected);
            scene.Disconnected.Add(result.OnDisconnected);

            scene.AddRoute("echo", result.OnEcho);
            scene.AddRoute("transfert", result.OnTransfert);
            scene.AddRoute("broadcast", result.OnBroadcast);

            scene.AddProcedure("rpc", result.OnRpc);
            scene.AddProcedure("rpcping", result.OnRpcPing);

            scene.Shuttingdown.Add(result.OnShutDown);

            return(result);
        }
        private void AuthenticatorSceneFactory(ISceneHost scene)
        {
            scene.AddProcedure("login", async p =>
            {
                scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Logging in an user.", null);

                var accessor = scene.DependencyResolver.Resolve<Management.ManagementClientAccessor>();
                var authenticationCtx = p.ReadObject<Dictionary<string, string>>();
                var result = new LoginResult();
                var userService = scene.DependencyResolver.Resolve<IUserService>();

                foreach (var provider in _config.AuthenticationProviders)
                {
                    var authResult = await provider.Authenticate(authenticationCtx, userService);
                    if (authResult == null)
                    {
                        continue;
                    }

                    if (authResult.Success)
                    {
                        scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Authentication successful.", authResult);

                        result.Success = true;
                        var client = await accessor.GetApplicationClient();
                        result.Token = await client.CreateConnectionToken(_config.OnRedirect(authResult), _config.UserDataSelector(authResult));
                        userService.SetUid(p.RemotePeer, authResult.AuthenticatedId);
                        break;
                    }
                    else
                    {
                        scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Authentication failed.", authResult);

                        result.ErrorMsg = authResult.ReasonMsg;
                        break;
                    }
                }
                if (!result.Success)
                {
                    if (result.ErrorMsg == null)
                    {
                        result.ErrorMsg = "No authentication provider able to handle these credentials were found.";
                    }
                }

                if (result.Success)
                {
                    scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "User logged in.", null);
                }
                else
                {
                    scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "User failed to log in.", null);
                }
                p.SendValue(result);
            });

            foreach (var provider in _config.AuthenticationProviders)
            {
                provider.AdjustScene(scene);
            }
        }
예제 #14
0
        public RTypeMainLobby(ISceneHost scene)
        {
            m_scene = scene;
            m_log = m_scene.GetComponent<ILogger>();
            m_env = m_scene.GetComponent<IEnvironment>();
            connectClientAPI();

            m_scene.Connecting.Add(onConnecting);
            m_scene.Connected.Add(onConnected);
            m_scene.Shuttingdown.Add(onShuttingDown);
            m_scene.Disconnected.Add(onDisconnected);

            m_scene.AddProcedure("GetListGames", onGetListGames);
            m_scene.AddProcedure("JoinGame", onJoinGame);
            m_scene.AddRoute("UpdateGame", onUpdateGame);
            m_scene.AddRoute("GetReady", onGetReady);
            m_scene.AddRoute("CreateGame", onCreateGame);
            m_scene.AddRoute("DestroyGame", onDestroyGame);
            m_scene.AddRoute("QuitGame", onQuitGame);
        }
 public void AdjustScene(ISceneHost scene)
 {
     scene.AddProcedure("provider.loginpassword.createAccount", p => CreateAccount(p, scene));
 }
예제 #16
0
 public void Initialize(ISceneHost scene)
 {
     scene.AddProcedure("provider.loginpassword.createAccount", p => CreateAccount(p, scene));
     scene.AddProcedure("provider.loginpassword.requestPasswordRecovery", p => RequestPasswordRecovery(p, scene));
     scene.AddProcedure("provider.loginpassword.resetPassword", p => ChangePassword(p, scene));
 }
        private void AuthenticatorSceneFactory(ISceneHost scene)
        {
            scene.AddProcedure("login", async p =>
            {
                try
                {
                    //scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Logging in an user.", null);

                    var accessor          = scene.DependencyResolver.Resolve <Management.ManagementClientAccessor>();
                    var authenticationCtx = p.ReadObject <Dictionary <string, string> >();
                    //scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Authentication context read.", authenticationCtx);
                    var result       = new LoginResult();
                    var userService  = scene.DependencyResolver.Resolve <IUserService>();
                    var userSessions = scene.DependencyResolver.Resolve <IUserSessions>();
                    var handled      = false;
                    foreach (var provider in _config.AuthenticationProviders)
                    {
                        var authResult = await provider.Authenticate(authenticationCtx, userService);
                        if (authResult == null)
                        {
                            continue;
                        }
                        handled = true;
                        if (authResult.Success)
                        {
                            //scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Authentication successful.", authResult);
                            var oldPeer = await userSessions.GetPeer(authResult.AuthenticatedUser.Id);
                            if (oldPeer != null)
                            {
                                await oldPeer.DisconnectFromServer("User connected elsewhere");
                            }

                            await userSessions.Login(p.RemotePeer, authResult.AuthenticatedUser, authResult.PlatformId);

                            result.Success  = true;
                            var client      = await accessor.GetApplicationClient();
                            result.UserId   = authResult.AuthenticatedUser.Id;
                            result.Username = authResult.Username;
                            break;
                        }
                        else
                        {
                            //scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Authentication failed.", authResult);

                            result.ErrorMsg = authResult.ReasonMsg;
                            break;
                        }
                    }
                    if (!handled)
                    {
                        scene.DependencyResolver.Resolve <ILogger>().Log(LogLevel.Error, "UsersManagement.login", "Login failed: provider not found ", authenticationCtx);
                        result.ErrorMsg = "No authentication provider able to handle these credentials were found.";
                    }

                    p.SendValue(result);
                    if (!result.Success)
                    {
                        var _ = Task.Delay(2000).ContinueWith(t => p.RemotePeer.DisconnectFromServer("Authentication failed"));
                    }
                }
                catch (Exception ex)
                {
                    scene.DependencyResolver.Resolve <ILogger>().Log(LogLevel.Error, "UsersManagement.login", "an exception occurred while trying to log in a user", ex);
                    throw;
                }
            });

            //scene.AddController<GroupController>();
            scene.AddController <SceneAuthorizationController>();
            scene.Disconnected.Add(async args =>
            {
                await scene.GetComponent <IUserSessions>().LogOut(args.Peer);
            });

            scene.Starting.Add(_ =>
            {
                foreach (var provider in _config.AuthenticationProviders)
                {
                    provider.Initialize(scene);
                }
                return(Task.FromResult(true));
            });
        }