public IEnumerator LoginWithOtherPlatform(PlatformType platformType, string platformToken, ResultCallback callback) { Report.GetFunctionLog(this.GetType().Name); Assert.IsNotNull(platformToken, "PlatformToken parameter is null."); var request = HttpRequestBuilder.CreatePost(this.baseUrl + "/oauth/platforms/{platformId}/token") .WithPathParam("platformId", platformType.ToString().ToLower()) .WithBasicAuth(this.clientId, this.clientSecret) .WithContentType(MediaType.ApplicationForm) .Accepts(MediaType.ApplicationJson) .WithFormParam("platform_token", platformToken) .WithFormParam("namespace", this.@namespace) .GetResult(); IHttpResponse response = null; yield return(this.httpWorker.SendRequest(request, rsp => response = rsp)); Result <TokenData> result = response.TryParseJson <TokenData>(); this.tokenData = result.Value; if (!result.IsError) { this.maintainAccessTokenCoroutine = this.coroutineRunner.Run(MaintainAccessToken()); callback.TryOk(); } else { callback.TryError(result.Error); } }
private IEnumerator <ITask> LoginWithDeviceIdAsync(DeviceProvider deviceProvider, ResultCallback callback) { if (this.IsLoggedIn) { this.Logout(); } Result <TokenData> loginResult = null; yield return(Task.Await( this.authApi.GetUserTokenWithDeviceId( this.@namespace, this.clientId, this.clientSecret, deviceProvider.DeviceType, deviceProvider.DeviceId, result => loginResult = result))); if (loginResult.IsError) { callback.TryError(loginResult.Error.Code, loginResult.Error.Message); yield break; } this.tokenData = loginResult.Value; this.nextRefreshTime = User.ScheduleNormalRefresh(this.tokenData.expires_in); callback.TryOk(); }
/// <summary> /// Check if user has purchased the subscription and eligible to play /// </summary> /// <param name="callback"> Returns the boolean result whether the user is subscribed and eligible to play the game via callback when the operation is completed</param> public void GetUserEligibleToPlay(ResultCallback <bool> callback) { Report.GetFunctionLog(this.GetType().Name); ResultCallback <ItemInfo> onGotItemInfo = (itemInfoResult) => { if (itemInfoResult.IsError) { callback.TryError(itemInfoResult.Error.Code); return; } string[] skus = itemInfoResult.Value.features; string[] appIds = { AccelBytePlugin.Config.AppId }; AccelBytePlugin.GetEntitlement().GetUserEntitlementOwnershipAny(null, appIds, skus, (ownershipResult) => { if (ownershipResult.IsError) { callback.TryError(ownershipResult.Error.Code); return; } callback.TryOk(ownershipResult.Value.owned); }); }; AccelBytePlugin.GetItems().GetItemByAppId(AccelBytePlugin.Config.AppId, onGotItemInfo); }
private IEnumerator <ITask> LoginWithOtherPlatformAsync(PlatformType platformType, string platformToken, ResultCallback callback) { if (this.IsLoggedIn) { this.Logout(); } Result <TokenData> loginResult = null; yield return(Task.Await(this.authApi.GetUserTokenWithOtherPlatform(this.@namespace, this.clientId, this.clientSecret, platformType, platformToken, result => { loginResult = result; }))); if (loginResult.IsError) { callback.TryError(ErrorCode.GenerateTokenFailed, "cannot generate platform token for " + platformType, loginResult.Error); yield break; } this.tokenData = loginResult.Value; this.nextRefreshTime = User.ScheduleNormalRefresh(this.tokenData.expires_in); callback.TryOk(); }
public IEnumerator LoginWithDeviceId(ResultCallback callback) { Report.GetFunctionLog(this.GetType().Name); DeviceProvider deviceProvider = DeviceProvider.GetFromSystemInfo(); IHttpRequest request = HttpRequestBuilder.CreatePost(this.baseUrl + "/oauth/platforms/{platformId}/token") .WithPathParam("platformId", deviceProvider.DeviceType) .WithBasicAuth(this.clientId, this.clientSecret) .WithContentType(MediaType.ApplicationForm) .Accepts(MediaType.ApplicationJson) .WithFormParam("device_id", deviceProvider.DeviceId) .WithFormParam("namespace", this.@namespace) .GetResult(); IHttpResponse response = null; yield return(this.httpWorker.SendRequest(request, rsp => response = rsp)); Result <TokenData> result = response.TryParseJson <TokenData>(); this.tokenData = result.Value; if (!result.IsError) { this.maintainAccessTokenCoroutine = this.coroutineRunner.Run(MaintainAccessToken()); callback.TryOk(); } else { callback.TryError(result.Error); } }
public IEnumerator LoginWithUsername(string username, string password, ResultCallback callback) { Report.GetFunctionLog(this.GetType().Name); Assert.IsNotNull(username, "Username parameter is null."); Assert.IsNotNull(password, "Password parameter is null."); var request = HttpRequestBuilder.CreatePost(this.baseUrl + "/oauth/token") .WithBasicAuth(this.clientId, this.clientSecret) .WithContentType(MediaType.ApplicationForm) .Accepts(MediaType.ApplicationJson) .WithFormParam("grant_type", "password") .WithFormParam("username", username) .WithFormParam("password", password) .WithFormParam("namespace", this.@namespace) .GetResult(); IHttpResponse response = null; yield return(this.httpWorker.SendRequest(request, rsp => response = rsp)); Result <TokenData> result = response.TryParseJson <TokenData>(); this.tokenData = result.Value; if (!result.IsError) { this.maintainAccessTokenCoroutine = this.coroutineRunner.Run(MaintainAccessToken()); callback.TryOk(); } else { callback.TryError(result.Error); } }
private IEnumerator GetDataAsync(ResultCallback <UserData> callback) { Report.GetFunctionLog(this.GetType().Name); if (this.userDataCache != null) { callback.TryOk(this.userDataCache); } else { yield return(RefreshDataAsync(callback)); } }
private async Task ShutdownAgones(ResultCallback callback) { if (await agones.GetSDK().Shutdown()) { Debug.Log("Successfully shutting down Agones GameServer."); agones.SetReady(false); callback.TryOk(); } else { callback.TryError(ErrorCode.UnknownError, "Failed to shutdown Agones GameServer."); } serverType = ServerType.NONE; }
/// <summary> /// Logout current user session /// </summary> public void Logout(ResultCallback callback) { Report.GetFunctionLog(this.GetType().Name); this.sessionAdapter.UserId = null; if (!this.sessionAdapter.IsValid()) { callback.TryOk(); return; } this.coroutineRunner.Run(this.loginSession.Logout(callback)); }
private void TrySetAccessToken(ResultCallback callback, IHttpResponse response) { var result = response.TryParseJson <SessionData>(); if (result.IsError) { callback.TryError(result.Error); return; } this.AuthorizationToken = result.Value.session_id; callback.TryOk(); }
private IEnumerator RefreshDataAsync(ResultCallback <UserData> callback) { Result <UserData> result = null; yield return(this.userAccount.GetData(r => result = r)); if (!result.IsError) { this.userDataCache = result.Value; callback.TryOk(this.userDataCache); yield break; } callback.Try(result); }
private IEnumerator GetServerLatenciesAsync(ResultCallback <Dictionary <string, int> > callback) { Result <QosServerList> getQosServersResult = null; yield return(this.qosManager.GetQosServers(result => getQosServersResult = result)); if (getQosServersResult.IsError) { callback.TryError(getQosServersResult.Error.Code); yield break; } var stopwatch = new Stopwatch(); var latencies = new Dictionary <string, int>(); foreach (QosServer server in getQosServersResult.Value.servers) { using (var udpClient = new UdpClient(server.port)) { udpClient.Connect(new IPEndPoint(IPAddress.Parse(server.ip), server.port)); byte[] sendBytes = Encoding.ASCII.GetBytes("PING"); stopwatch.Restart(); IAsyncResult asyncResult = udpClient.BeginSend(sendBytes, sendBytes.Length, null, null); yield return(WaitUntil(() => asyncResult.IsCompleted, 15 * 1000)); udpClient.EndSend(asyncResult); var remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); asyncResult = udpClient.BeginReceive(null, null); yield return(WaitUntil(() => asyncResult.IsCompleted, 15 * 1000)); if (!asyncResult.IsCompleted) { AccelByteDebug.Log($"[QOS] timeout to PING {server.ip}"); } udpClient.EndReceive(asyncResult, ref remoteIpEndPoint); latencies[server.region] = stopwatch.Elapsed.Milliseconds; } } callback.TryOk(latencies); }
private IEnumerator LoginAsync(Func <ResultCallback, IEnumerator> loginMethod, ResultCallback callback) { if (this.sessionAdapter.IsValid()) { callback.TryError(ErrorCode.InvalidRequest, "User is already logged in."); yield break; } Result loginResult = null; yield return(loginMethod(r => loginResult = r)); if (loginResult.IsError) { callback.TryError(loginResult.Error); yield break; } this.sessionAdapter.AuthorizationToken = this.loginSession.AuthorizationToken; if (this.needsUserId) { Result <UserData> userDataResult = null; yield return(RefreshDataAsync(result => userDataResult = result)); if (userDataResult.IsError) { callback.TryError(userDataResult.Error); yield break; } this.sessionAdapter.UserId = this.userDataCache.userId; } else { this.sessionAdapter.UserId = this.loginSession.UserId; } callback.TryOk(); }
public IEnumerator GetContentPreview(string @namespace, string userId, string accessToken, string contentId, ResultCallback <byte[]> callback) { Report.GetFunctionLog(this.GetType().Name); Assert.IsNotNull(@namespace, "Can't get content! Namespace parameter is null!"); Assert.IsNotNull(userId, "Can't get content! UserId parameter is null!"); Assert.IsNotNull(accessToken, "Can't get content! AccessToken parameter is null!"); Assert.IsNotNull(contentId, "Can't get content! contentId parameter is null!"); yield return(GetContentPreview(@namespace, userId, accessToken, contentId, result => { if (result.IsError) { callback.TryError(result.Error); return; } byte[] bytes = System.Convert.FromBase64String(result.Value.preview); callback.TryOk(bytes); })); }
private IEnumerator <ITask> GetClientToken(ResultCallback <string> callback) { if (this.clientToken == null || this.clientTokenExpiryTime < DateTime.UtcNow) { Result <TokenData> tokenResult = null; yield return(Task.Await(this.authApi.GetClientToken(this.clientId, this.clientSecret, result => tokenResult = result))); if (tokenResult.IsError) { callback.TryError(tokenResult.Error.Code, tokenResult.Error.Message); yield break; } this.clientToken = tokenResult.Value.access_token; this.clientTokenExpiryTime = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.Value.expires_in); } callback.TryOk(this.clientToken); }
private IEnumerator LoginAsync(Func <ResultCallback, IEnumerator> loginMethod, ResultCallback callback) { if (this.loginSession.IsValid()) { callback.TryError(ErrorCode.InvalidRequest, "User is already logged in."); yield break; } Result loginResult = null; yield return(loginMethod(r => loginResult = r)); if (loginResult.IsError) { callback.TryError(loginResult.Error); yield break; } callback.TryOk(); }
private IEnumerator GetUserEntitlementOwnershipTokenAsync(string key, string[] itemIds, string[] appIds, string[] skus, bool verifyPublicKey, bool verifyExpiration, bool verifyUserId, ResultCallback <OwnershipEntitlement[]> callback) { if (!this.session.IsValid()) { callback.TryError(ErrorCode.IsNotLoggedIn); yield break; } Result <OwnershipToken> result = null; yield return(this.api.GetUserEntitlementOwnershipToken( AccelBytePlugin.Config.PublisherNamespace, this.session.AuthorizationToken, itemIds, appIds, skus, r => result = r)); if (result.IsError) { callback.TryError(result.Error.Code); yield break; } if (!JsonWebToken.TryDecodeToken <OwnershipTokenPayload>(key, result.Value.ownershipToken, out var payloadResult, verifyPublicKey, verifyExpiration)) { callback.TryError(ErrorCode.InvalidResponse); yield break; } if (verifyUserId && this.session.UserId != payloadResult.sub) { callback.TryError(ErrorCode.InvalidResponse); yield break; } callback.TryOk(payloadResult.entitlements); }
public IEnumerator LoginWithClientCredentials(ResultCallback callback) { Result <TokenData> getClientTokenResult = null; yield return(GetClientToken(r => getClientTokenResult = r)); this.tokenData = getClientTokenResult.Value; if (!getClientTokenResult.IsError) { if (this.maintainAccessTokenCoroutine == null) { this.maintainAccessTokenCoroutine = this.coroutineRunner.Run(MaintainAccessToken()); } callback.TryOk(); } else { callback.TryError(getClientTokenResult.Error); } }
private IEnumerator <ITask> LoginWithUserNameAsync(string email, string password, ResultCallback callback) { if (this.IsLoggedIn) { this.Logout(); } Result <TokenData> loginResult = null; yield return(Task.Await(this.authApi.GetUserToken(this.@namespace, this.clientId, this.clientSecret, email, password, result => { loginResult = result; }))); if (loginResult.IsError) { callback.TryError(ErrorCode.GenerateTokenFailed, "Generate token with password grant failed.", loginResult.Error); yield break; } this.tokenData = loginResult.Value; this.nextRefreshTime = User.ScheduleNormalRefresh(this.tokenData.expires_in); callback.TryOk(); }
private async void InitiateAgones(ResultCallback callback) { GameObject dummyGameObject = GameObject.Find("AccelByteDummyGameObject"); if (dummyGameObject == null) { dummyGameObject = new GameObject("AccelByteDummyGameObject"); } agones.SetComponentSDK(dummyGameObject.AddComponent <AgonesSdk>()); UnityEngine.Object.DontDestroyOnLoad(dummyGameObject); bool isAgonesConnectionEstablished = await agones.GetSDK().Connect(); if (isAgonesConnectionEstablished) { bool isAgonesGameServerIsReady = await agones.GetSDK().Ready(); if (isAgonesGameServerIsReady) { //Check Agones GameServer's health DateTime healthCheckStarted = DateTime.Now; var gameServer = await agones.GetSDK().GameServer(); if (gameServer == null && DateTime.Now.Subtract(healthCheckStarted) > agones.INITIAL_HEALTH_CHECK_TIMEOUT) { Debug.Log("[Agones] GameServer is not healthy. Shutting down."); agones.GetSDK().Shutdown(); } else { Debug.Log("[Agones] GameServer is healthy."); agones.SetReady(true); } } else { Debug.Log("[Agones] GameServer is not ready."); } } else { Debug.Log("[Agones] Failed to establish a connection to GameServer."); } if (agones.IsReady()) { callback.TryOk(); serverType = ServerType.CLOUDSERVER; } else { DateTime startWaitingRegistrationTime = DateTime.Now; while (startWaitingRegistrationTime.Add(agones.REGISTRATION_TIMEOUT) > DateTime.Now) { if (agones.IsReady()) { break; } await Task.Delay(1000); } if (agones.IsReady()) { callback.TryOk(); serverType = ServerType.CLOUDSERVER; } else { callback.TryError(ErrorCode.ServiceUnavailable, "Agones GameServer is not ready."); } } }