Пример #1
0
        public async Task <GameServersProviderResponseParameters> ProvideGameServers(IYield yield)
        {
            var responseParameters = await ServerPeerHandler.SendOperation <EmptyParameters, GameServersProviderResponseParameters>
                                         (yield, (byte)GameServerProviderOperations.ProvideGameServers, new EmptyParameters(), MessageSendOptions.DefaultReliable());

            return(responseParameters);
        }
Пример #2
0
        protected async Task Connect(IYield yield, ServerConnectionInformation serverConnectionInformation, bool authorize = true)
        {
            serviceBase = GetServiceBase();

            OnPreConnection();

            var connectionStatus = ConnectionStatus.Failed;

            try
            {
                connectionStatus = await serviceBase.ServiceConnectionHandler.Connect(yield, CoroutinesExecutor, serverConnectionInformation);
            }
            catch (ServerConnectionFailed exception)
            {
                LogUtils.Log(exception.Message, LogMessageType.Error);
            }

            if (connectionStatus == ConnectionStatus.Failed)
            {
                OnConnectionFailed();
                return;
            }

            if (authorize)
            {
                serviceBase.SetPeerLogic <AuthorizationPeerLogic, AuthorizationOperations, EmptyEventCode>();
            }
            else
            {
                SetPeerLogicAfterAuthorization();
            }

            SubscribeToDisconnectionNotifier();
            OnConnectionEstablished();
        }
        private async Task Connect(IYield yield, PeerConnectionInformation connectionInformation)
        {
            isConnecting = true;

            try
            {
                outboundServerPeer = await serverConnectorProvider.GetServerConnector().Connect(yield, connectionInformation);
            }
            catch (CouldNotConnectToPeerException exception)
            {
                if (exception.Message != string.Empty && !exception.Message.Equals(exceptionMessage))
                {
                    LogUtils.Log($"Failed connect to {connectionInformation.Ip}:{connectionInformation.Port}. Details: {exception.Message}");
                    exceptionMessage = exception.Message;
                }
            }
            finally
            {
                if (IsConnected())
                {
                    SetNetworkTrafficState(NetworkTrafficState.Flowing);

                    connectContinuously?.Dispose();
                    onConnected?.Invoke(outboundServerPeer);
                }
            }

            isConnecting = false;
        }
Пример #4
0
        private async Task ProvideGameServerList(IYield yield)
        {
            await yield.Return(new WaitForSeconds(0.5f));

            var gameServerProviderPeerLogic = ServiceContainer.GameServerProviderService.GetPeerLogic <IGameServerProviderPeerLogicAPI>().AssertNotNull();
            var responseParameters          = await gameServerProviderPeerLogic.ProvideGameServers(yield);

            foreach (var gameServerInformation in responseParameters.GameServerInformations)
            {
                var gameServerName = gameServerInformation.Name;
                if (gameServerInformations.ContainsKey(gameServerName))
                {
                    LogUtils.Log(MessageBuilder.Trace($"Duplication of the {gameServerName} game server. Can not add more than one."));
                    continue;
                }

                gameServerInformations.Add(gameServerName, gameServerInformation);
            }

            gameServerSelectorWindow.EnableAllButtons();

            if (gameServerInformations.Count != 0)
            {
                ShowGameServerList();
            }
            else
            {
                gameServerSelectorWindow.GameServerSelectorRefreshImage.Message = "No servers found.";
            }
        }
        public async Task <ConnectionStatus> Connect(IYield yield, ICoroutinesExecutor coroutinesExecutor, ServerConnectionInformation serverConnectionInformation)
        {
            var serverType = serverConnectionInformation.ServerType;

            if (IsConnected())
            {
                throw new ServerConnectionFailed($"A connection already exists with a {serverType} server.");
            }

            ConnectionInformation = serverConnectionInformation;

            var ip   = ConnectionInformation.PeerConnectionInformation.Ip;
            var port = ConnectionInformation.PeerConnectionInformation.Port;

            LogUtils.Log($"Connecting to a {serverType} server. IP: {ip} Port: {port}");

            var serverConnector      = new PhotonServerConnector(() => coroutinesExecutor);
            var networkConfiguration = NetworkConfiguration.GetInstance();
            var connectionDetails    = new ConnectionDetails(networkConfiguration.ConnectionProtocol, networkConfiguration.DebugLevel);

            ServerPeer = await serverConnector.ConnectAsync(yield, ConnectionInformation.PeerConnectionInformation, connectionDetails);

            if (ServerPeer == null)
            {
                return(ConnectionStatus.Failed);
            }

            SubscribeToDisconnectionNotifier();

            LogUtils.Log($"A {serverType} server has been connected: {ip}:{port}");

            serviceConnectionNotifier.Connection();
            return(ConnectionStatus.Succeed);
        }
Пример #6
0
 /// <summary>
 /// Iterate through the given properties on <paramref name="args" />
 /// and return IYields until all properties are non-null. Questions are
 /// pulled from either the property's
 /// <see cref="ArgumentQuestionAttribute"/>,
 /// <see cref="ArgumentDescriptionAttribute"/>,
 /// or the property name (in that order).
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="gen"></param>
 /// <param name="args"></param>
 /// <param name="propertyNames"></param>
 /// <param name="culture">Culture to localize the question.</param>
 /// <returns></returns>
 public static async Task AskForPropertiesWhileNull <T>(
     IYield <string, string> gen, T args, IList <string> propertyNames, CultureInfo culture = null)
 {
     await AskForPropertiesWhileNull(gen, args,
                                     typeof(T).GetProperties().Where(p => propertyNames.Contains(p.Name)),
                                     culture);
 }
Пример #7
0
        protected async Task Authorize(IYield yield)
        {
            OnPreAuthorization();

            var authorizationStatus = AuthorizationStatus.Failed;

            try
            {
                var parameters         = new AuthorizeRequestParameters(AccessTokenProvider.AccessToken);
                var responseParameters = await Authorize(yield, parameters);

                authorizationStatus = responseParameters.Status;
            }
            catch (Exception)
            {
                // Left blank intentionally
            }

            if (authorizationStatus == AuthorizationStatus.Failed)
            {
                OnNonAuthorized();
                return;
            }

            SetPeerLogicAfterAuthorization();
            OnAuthorized();
        }
Пример #8
0
        public async Task EnterScene(IYield yield)
        {
            var responseParameters = await ServerPeerHandler.SendOperation <EmptyParameters, EnterSceneResponseParameters>
                                         (yield, (byte)GameOperations.EnterScene, new EmptyParameters(), MessageSendOptions.DefaultReliable());

            SceneEntered?.Invoke(responseParameters);
        }
Пример #9
0
        public async Task GetDirections(IYield <string, string> gen, DirectionsArgs args)
        {
            await PluginUtils.AskForPropertiesWhileNull(gen, args, _grammar);

            await gen.Yield(
                String.Format("You have traveled from {0} to {1}.",
                              args.Source, args.Destination));
        }
Пример #10
0
        public async Task GetDirections(IYield<string, string> gen, DirectionsArgs args)
        {
            await PluginUtils.AskForPropertiesWhileNull(gen, args, _grammar);

            await gen.Yield(
                String.Format("You have traveled from {0} to {1}.",
                args.Source, args.Destination));
        }
Пример #11
0
        public Task <ChangeSceneResponseParameters> ChangeScene(IYield yield, ChangeSceneRequestParameters parameters)
        {
            var id = parameters.PortalId;
            var portalContainer = Components.GetComponent <IPortalContainer>().AssertNotNull();
            var map             = portalContainer.GetMap(id);

            return(Task.FromResult(new ChangeSceneResponseParameters(map)));
        }
    internal EditorCoroutine(int ownerHash, IEnumerator routine, string id)
    {
        currentYield = new Yield.Default();
        finished     = false;

        this.enumerator = routine ?? throw new ArgumentNullException(nameof(routine), "运行时不能为null.");
        this.ownerHash  = ownerHash;
        this.id         = id;
    }
        public Task <Server1OperationResponseParameters> Server1Operation(IYield yield, Server1OperationRequestParameters parameters)
        {
            if (outboundServerPeerLogic == null)
            {
                return(Task.FromResult(new Server1OperationResponseParameters()));
            }

            return(outboundServerPeerLogic.SendOperation <Server1OperationRequestParameters, Server1OperationResponseParameters>
                       (yield, (byte)ServerOperations.Server1Operation, parameters));
        }
        public Task <AuthorizeUserResponseParameters> UserAuthorization(IYield yield, AuthorizeUserRequestParameters parameters)
        {
            if (outboundServerPeerLogic == null)
            {
                return(Task.FromResult(new AuthorizeUserResponseParameters()));
            }

            return(outboundServerPeerLogic.SendOperation <AuthorizeUserRequestParameters, AuthorizeUserResponseParameters>
                       (yield, (byte)AuthorizationOperations.UserAuthorization, parameters));
        }
        public Task <GetCharacterResponseParameters> GetCharacter(IYield yield, GetCharacterRequestParametersEx parameters)
        {
            if (outboundServerPeerLogic == null)
            {
                return(Task.FromResult(new GetCharacterResponseParameters()));
            }

            return(outboundServerPeerLogic.SendOperation <GetCharacterRequestParametersEx, GetCharacterResponseParameters>
                       (yield, (byte)CharacterOperations.GetCharacter, parameters));
        }
        public async Task <AuthenticateResponseParameters> Authenticate(IYield yield, AuthenticateRequestParameters parameters)
        {
            var responseParameters = await ServerPeerHandler.SendOperation <AuthenticateRequestParameters, AuthenticateResponseParameters>
                                         (yield, (byte)LoginOperations.Authenticate, parameters, MessageSendOptions.DefaultReliable());

            if (responseParameters.HasAccessToken)
            {
                AccessTokenProvider.AccessToken = responseParameters.AccessToken;
            }
            return(new AuthenticateResponseParameters(responseParameters.Status));
        }
Пример #17
0
        public async Task <ValidateCharacterResponseParameters> ValidateCharacter(IYield yield, ValidateCharacterRequestParameters parameters)
        {
            var responseParameters = await ServerPeerHandler.SendOperation <ValidateCharacterRequestParameters, ValidateCharacterResponseParameters>
                                         (yield, (byte)CharacterOperations.ValidateCharacter, parameters, MessageSendOptions.DefaultReliable());

            if (responseParameters.Status == CharacterValidationStatus.Ok)
            {
                ServiceContainer.GameService.SetPeerLogic <GameScenePeerLogic, GameOperations, GameEvents>();
            }
            return(responseParameters);
        }
Пример #18
0
        private async Task GetCharacters(IYield yield)
        {
            var characterService = ServiceContainer.GameService.GetPeerLogic <ICharacterPeerLogicAPI>().AssertNotNull();
            var parameters       = await characterService.GetCharacters(yield);

            if (parameters.Characters == null)
            {
                throw new Exception("Failed to get characters.");
            }

            OnReceivedCharacters(parameters);
        }
Пример #19
0
        private async Task Authenticate(IYield yield)
        {
            var parameters         = new AuthenticateRequestParameters(secretKey);
            var responseParameters = await SendOperation <AuthenticateRequestParameters, AuthenticateResponseParameters>
                                         (yield, (byte)AuthenticationOperations.Authenticate, parameters);

            if (responseParameters.Status == AuthenticationStatus.Succeed)
            {
                isAuthenticated = true;
                onAuthenticated?.Invoke();
            }
        }
Пример #20
0
        private async Task Authenticate(IYield yield, AuthenticateRequestParameters parameters)
        {
            var loginPeerLogic     = ServiceContainer.LoginService.GetPeerLogic <ILoginPeerLogicAPI>().AssertNotNull();
            var responseParameters = await loginPeerLogic.Authenticate(yield, parameters);

            switch (responseParameters.Status)
            {
            case LoginStatus.Succeed:
            {
                var noticeWindow = UserInterfaceContainer.Instance.Get <NoticeWindow>().AssertNotNull();
                noticeWindow.Message.text = "You have logged in successfully!";
                break;
            }

            case LoginStatus.UserNotExist:
            {
                var noticeWindow = UserInterfaceContainer.Instance.Get <NoticeWindow>().AssertNotNull();
                noticeWindow.Message.text          = "The user does not exist. Please check your typed email.";
                noticeWindow.OkButton.interactable = true;
                break;
            }

            case LoginStatus.PasswordIncorrect:
            {
                var noticeWindow = UserInterfaceContainer.Instance.Get <NoticeWindow>().AssertNotNull();
                noticeWindow.Message.text          = "The password is incorrect, please type it again.";
                noticeWindow.OkButton.interactable = true;
                break;
            }

            case LoginStatus.NonAuthorized:
            {
                var noticeWindow = UserInterfaceContainer.Instance.Get <NoticeWindow>().AssertNotNull();
                noticeWindow.Message.text          = "Authentication with login server failed.";
                noticeWindow.OkButton.interactable = true;
                break;
            }

            default:
            {
                var noticeWindow = UserInterfaceContainer.Instance.Get <NoticeWindow>().AssertNotNull();
                noticeWindow.Message.text          = "Something went wrong, please try again.";
                noticeWindow.OkButton.interactable = true;
                break;
            }
            }

            if (responseParameters.Status == LoginStatus.Succeed)
            {
                OnLoginSucceed();
            }
        }
Пример #21
0
        private async Task <AuthorizeResponseParameters?> Authorize(IYield yield, AuthorizeAccesTokenRequestParameters parameters)
        {
            var authorization = await authorizationServiceApi.AccessTokenAuthorization(yield, parameters);

            if (authorization.Status == AuthorizationStatus.Succeed)
            {
                onAuthorized?.Invoke();
                onAuthorizedArg?.Invoke(authorization.UserId);
                return(new AuthorizeResponseParameters(authorization.UserId, authorization.Status));
            }

            onNonAuthorized?.Invoke();
            return(null);
        }
Пример #22
0
        private async Task <AuthenticateResponseParameters?> AccessTokenProvider(IYield yield, AuthorizeUserRequestParameters parameters)
        {
            var userAuthorization = await authorizationServiceApi.UserAuthorization(yield, parameters);

            var responseParameters = userAuthorization.Status == AuthorizationStatus.Succeed
                ? new AuthenticateResponseParameters(LoginStatus.Succeed, userAuthorization.AccessToken)
                : new AuthenticateResponseParameters(LoginStatus.NonAuthorized);

            if (responseParameters.Status == LoginStatus.Succeed)
            {
                onAuthenticated.Invoke(parameters.UserId);
            }
            return(responseParameters);
        }
    void ICoroutine.Check()
    {
        object current = enumerator.Current;

        switch (current)
        {
        case null:
        case WaitForFixedUpdate _:
        case WaitForEndOfFrame _:
            currentYield = new Yield.WaitForFrames(1);
            break;

        case WaitForSeconds waitForSeconds:
            const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
            FieldInfo          field        = typeof(WaitForSeconds).GetField("m_Seconds", bindingFlags);
            // 如果内部 m_Seconds 字段不变就可以获取到
            if (field != null)
            {
                float seconds = float.Parse(field.GetValue(waitForSeconds).ToString());
                currentYield = new Yield.WaitForSeconds(seconds);
            }
            // 除非Unity在WaitForSeconds中更改了内部变量的命名,在这种情况下,我们使用Yield.Default。
            else
            {
                currentYield = new Yield.Default();
            }

            break;

        case AsyncOperation asyncOperation:
            currentYield = new Yield.AsyncOperation(asyncOperation);
            break;

        case CustomYieldInstruction customYieldInstruction:
            currentYield = new Yield.CustomYieldInstruction(customYieldInstruction);
            break;

        case EditorCoroutine coroutine:
            currentYield = new Yield.NestedCoroutine(coroutine);
            break;

        default:
            currentYield = new Yield.Default();
            break;
        }
    }
        private async Task <ValidateCharacterResponseParameters?> GetCharacter(IYield yield, GetCharacterRequestParametersEx parameters)
        {
            var responseParameters = await characterServiceAPI.GetCharacter(yield, parameters);

            onCharacterSelected?.Invoke(responseParameters.Character);

            var status = responseParameters.Character.HasCharacter ? CharacterValidationStatus.Ok : CharacterValidationStatus.Wrong;

            if (status == CharacterValidationStatus.Wrong)
            {
                return(null);
            }

            var map = responseParameters.Character.LastMap;

            return(new ValidateCharacterResponseParameters(status, map));
        }
Пример #25
0
        private void StopImpl(bool yieldStopped)
        {
            if (!yieldStopped)
            {
                StopCurrentYield();
            }
            CurrentYield = null;

            startedInstances.Remove(Routine);

            update -= Update;

            Done.NPInvoke();
            Done = null;

            LogStop();
        }
        public async Task <IServerPeer> ConnectAsync(IYield yield, PeerConnectionInformation connectionInformation, ConnectionDetails connectionDetails)
        {
            var coroutinesExecuter = coroutinesExecuterProvider.Invoke();
            var photonPeer         = new PhotonPeer(connectionInformation, connectionDetails.ConnectionProtocol, connectionDetails.DebugLevel, coroutinesExecuter);

            photonPeer.Connect();

            var statusCode = await WaitForStatusCodeChange(yield, photonPeer);

            if (statusCode == StatusCode.Connect)
            {
                return(photonPeer);
            }

            LogUtils.Log($"Connecting to {connectionInformation.Ip}:{connectionInformation.Port} failed. Status Code: {statusCode}");
            return(null);
        }
Пример #27
0
        private async Task ChangeScene(IYield yield)
        {
            var sceneObject        = GetComponent <ISceneObject>();
            var gameScenePeerLogic = ServiceContainer.GameService.GetPeerLogic <IGameScenePeerLogicAPI>().AssertNotNull();
            var responseParameters = await gameScenePeerLogic.ChangeScene(yield, new ChangeSceneRequestParameters(sceneObject.Id));

            var map = responseParameters.Map;

            if (map == 0)
            {
                LogUtils.Log(MessageBuilder.Trace("You can not teleport to scene index 0."));
                return;
            }

            GameScenesController.Instance.LoadScene(map);

            Dispose();
        }
Пример #28
0
        private static async Task AskForPropertiesWhileNull <T>(IYield <string, string> gen,
                                                                T args, IEnumerable <PropertyInfo> propertyNames, CultureInfo culture)
        {
            if (ReferenceEquals(args, null))
            {
                throw new ArgumentNullException("args");
            }
            foreach (var prop in propertyNames)
            {
                var value = prop.GetValue(args);
                while (value == null)
                {
                    value = await gen.Yield(GetQuestion(prop, culture));

                    prop.SetValue(args, value);
                }
            }
        }
Пример #29
0
        /// <summary>
        /// Iterate through the given properties on <paramref name="args" />
        /// and return IYields until all properties are non-null. Questions are
        /// pulled from either the property's
        /// <see cref="ArgumentQuestionAttribute"/>,
        /// <see cref="ArgumentDescriptionAttribute"/>,
        /// or the property name (in that order).
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="gen"></param>
        /// <param name="args"></param>
        /// <param name="grammar"></param>
        /// <param name="culture">Culture to localize the question.</param>
        /// <returns></returns>
        public static async Task AskForPropertiesWhileNull <T>(
            IYield <string, string> gen, T args, IGrammar grammar, CultureInfo culture = null)
        {
            var registeredProperties = grammar.Properties.Select(p => new
            {
                p.DeclaringType,
                p.Name
            });

            await AskForPropertiesWhileNull(gen, args,
                                            typeof(T).GetProperties()
                                            .Where(p => registeredProperties.Contains(new
            {
                p.DeclaringType,
                p.Name
            })),
                                            culture);
        }
        private async Task <StatusCode> WaitForStatusCodeChange(IYield yield, PhotonPeer photonPeer)
        {
            var statusChanged = false;
            var statusCode    = StatusCode.Disconnect;

            Action <StatusCode> onStatusChanged = (newStatusCode) =>
            {
                statusChanged = true;
                statusCode    = newStatusCode;
            };

            photonPeer.StatusChanged += onStatusChanged;

            await yield.Return(new WaitUntilIsTrue(() => statusChanged));

            photonPeer.StatusChanged -= onStatusChanged;

            return(statusCode);
        }
        private async Task CreateCharacter(IYield yield)
        {
            var characterPeerLogic = ServiceContainer.GameService.GetPeerLogic <ICharacterPeerLogicAPI>().AssertNotNull();
            var responseParameters = await characterPeerLogic.CreateCharacter(yield, characterRequestParameters);

            switch (responseParameters.Status)
            {
            case CharacterCreationStatus.Succeed:
            {
                CharactersController.Instance.RecreateCharacter(GetLastCreatedCharacter());

                var noticeWindow = UserInterfaceContainer.Instance.Get <NoticeWindow>().AssertNotNull();
                noticeWindow.Message.text          = "Character created successfully.";
                noticeWindow.OkButtonClickedAction = charactersSelectionWindow.DeactiveAll;
                noticeWindow.OkButton.interactable = true;
                break;
            }

            case CharacterCreationStatus.Failed:
            {
                var noticeWindow = UserInterfaceContainer.Instance.Get <NoticeWindow>().AssertNotNull();
                noticeWindow.Message.text          = "Failed to create a new character, please try again.";
                noticeWindow.OkButton.interactable = true;
                break;
            }

            case CharacterCreationStatus.NameUsed:
            {
                var noticeWindow = UserInterfaceContainer.Instance.Get <NoticeWindow>().AssertNotNull();
                noticeWindow.Message.text          = "The name is already in use, choose another name.";
                noticeWindow.OkButton.interactable = true;
                break;
            }

            default:
            {
                var noticeWindow = UserInterfaceContainer.Instance.Get <NoticeWindow>().AssertNotNull();
                noticeWindow.Message.text          = "Something went wrong, please try again.";
                noticeWindow.OkButton.interactable = true;
                break;
            }
            }
        }
Пример #32
0
 public async Task WithStaticField(IYield gen)
 {
     _staticField = (string)await gen.Yield();
     await gen.Yield(_staticField);
 }
Пример #33
0
 public async Task WithValueInFirstYield(IYield gen)
 {
     await gen.Yield("response");
 }
Пример #34
0
 public async Task WithTenYields(IYield gen)
 {
     for (var i = 0; i < 10; i++)
     {
         await gen.Yield("response");
     }
 }
Пример #35
0
 public async Task WithLocalField(IYield gen)
 {
     var name = (string)await gen.Yield();
     await gen.Yield(name);
 }
Пример #36
0
 public async Task WithNestedField(IYield gen)
 {
     var data = new Outer { InnerThing = new Outer.Inner() };
     data.InnerThing.Field = (string)await gen.Yield();
     await gen.Yield(data.InnerThing.Field);
 }
Пример #37
0
 public async Task WithNestedProperty(IYield gen)
 {
     var data = new Outer { InnerThing = new Outer.Inner() };
     data.InnerThing.Property = (string)await gen.Yield();
     await gen.Yield(data.InnerThing.Property);
 }
Пример #38
0
 public async Task WithParameterProperty(IYield gen, SomeClass param)
 {
     param.PropertyName = (string)await gen.Yield();
     await gen.Yield(param.PropertyName);
 }
Пример #39
0
 public async Task WithWellDefinedTypes(IYield<int, string> gen)
 {
     var value = await gen.Yield();
     await gen.Yield(value.ToString());
 }
Пример #40
0
 public async Task WithIndexer(IYield gen)
 {
     var data = new Dictionary<string, string>();
     data["thing"] = (string)await gen.Yield();
     await gen.Yield(data["thing"]);
 }
Пример #41
0
 public async Task WithStaticProperty(IYield gen)
 {
     StaticProperty = (string)await gen.Yield();
     await gen.Yield(StaticProperty);
 }