コード例 #1
0
 public void Login(string username, string password, Action <ILoginResult> callback)
 {
     try
     {
         database.ClearServerTimeOffsetMillis();
         IGuestControllerClient guestControllerClient = guestControllerClientFactory.Create("NoSwid");
         guestControllerClient.LogIn(new LogInRequest
         {
             loginValue = username,
             password   = password
         }, delegate(GuestControllerResult <LogInResponse> r)
         {
             if (!r.Success)
             {
                 logger.Error("Login failed");
                 callback(new LoginFailedAuthenticationResult());
             }
             else
             {
                 HandleLoginSuccess(r, callback);
             }
         });
     }
     catch (Exception arg)
     {
         logger.Critical("Unhandled exception: " + arg);
         callback(new LoginResult(success: false, null));
     }
 }
コード例 #2
0
ファイル: AssetLoader.cs プロジェクト: smdx24/CPI-Source-Code
        private static void HandleResult(WwwCallResult result, string log, byte[] bytes, Uri uri, StringBuilder timeoutLogs, int numAttempts, Action <LoadAssetResult> callback, Action <Uri, Action <LoadAssetResult>, StringBuilder, int> retry, AbstractLogger logger)
        {
            switch (result)
            {
            case WwwCallResult.Success:
                logger.Debug(log);
                callback(new LoadAssetResult(success: true, bytes));
                break;

            case WwwCallResult.TooManyTimeoutsError:
                logger.Critical("Too many timeouts: " + uri.AbsoluteUri + "\nPrevious logs:\n" + timeoutLogs);
                callback(new LoadAssetResult(success: false, null));
                break;

            case WwwCallResult.TooManyServerErrors:
                logger.Critical("Too many server errors:\n" + log);
                callback(new LoadAssetResult(success: false, null));
                break;

            case WwwCallResult.RetryTimeout:
                logger.Error(log);
                timeoutLogs.Append(log);
                timeoutLogs.Append("\n\n");
                retry(uri, callback, timeoutLogs, numAttempts + 1);
                break;

            case WwwCallResult.RetryServerError:
                logger.Error(log);
                retry(uri, callback, timeoutLogs, numAttempts + 1);
                break;

            case WwwCallResult.OfflineError:
                logger.Error(log);
                callback(new LoadAssetResult(success: false, null));
                break;

            case WwwCallResult.ClientError:
                logger.Critical(log);
                callback(new LoadAssetResult(success: false, null));
                break;
            }
        }
コード例 #3
0
 public static DateTime?ParseDateTime(AbstractLogger logger, string date)
 {
     if (date == null)
     {
         return(null);
     }
     if (!DateTime.TryParse(date, out var result))
     {
         logger.Error("Received an invalid date of birth: " + result);
         return(null);
     }
     return(result);
 }
コード例 #4
0
 public static void Send(AbstractLogger logger, INotificationQueue notificationQueue, IMixWebCallFactory mixWebCallFactory, string inviteeDisplayName, bool requestTrust, Action <long> successCallback, Action <ISendFriendInvitationResult> failureCallback)
 {
     try
     {
         AddFriendshipInvitationRequest addFriendshipInvitationRequest = new AddFriendshipInvitationRequest();
         addFriendshipInvitationRequest.InviteeDisplayName = inviteeDisplayName;
         addFriendshipInvitationRequest.IsTrusted          = requestTrust;
         AddFriendshipInvitationRequest request = addFriendshipInvitationRequest;
         IWebCall <AddFriendshipInvitationRequest, AddFriendshipInvitationResponse> webCall = mixWebCallFactory.FriendshipInvitationPut(request);
         webCall.OnResponse += delegate(object sender, WebCallEventArgs <AddFriendshipInvitationResponse> e)
         {
             AddFriendshipInvitationResponse response = e.Response;
             if (NotificationValidator.Validate(response.Notification))
             {
                 notificationQueue.Dispatch(response.Notification, delegate
                 {
                     successCallback(response.Notification.Invitation.FriendshipInvitationId.Value);
                 }, delegate
                 {
                     failureCallback(new SendFriendInvitationResult(success: false, null));
                 });
             }
             else
             {
                 logger.Critical("Failed to validate invitation: " + JsonParser.ToJson(response));
                 failureCallback(new SendFriendInvitationResult(success: false, null));
             }
         };
         webCall.OnError += delegate(object sender, WebCallErrorEventArgs e)
         {
             string status  = e.Status;
             string message = e.Message;
             string text    = status;
             if (text != null && text == "INVITATION_ALREADY_EXISTS")
             {
                 logger.Error("Failed to send invitation because it already exists: " + message);
                 failureCallback(new SendFriendInvitationAlreadyExistsResult(success: false, null));
             }
             else
             {
                 failureCallback(new SendFriendInvitationResult(success: false, null));
             }
         };
         webCall.Execute();
     }
     catch (Exception ex)
     {
         logger.Critical("Unhandled exception: " + ex);
         failureCallback(new SendFriendInvitationResult(success: false, null));
     }
 }
コード例 #5
0
 private void UpdateDisplayName(Disney.Mix.SDK.Internal.GuestControllerDomain.DisplayName displayName)
 {
     if (displayName != null)
     {
         if (!DateTime.TryParse(displayName.moderatedStatusDate, out var result))
         {
             DisplayNameModeratedStatusDate = null;
             logger.Error("Received an invalid moderated status date: " + result);
         }
         else
         {
             DisplayNameModeratedStatusDate = result;
         }
         DisplayName               = displayName.displayName;
         ProposedDisplayName       = displayName.proposedDisplayName;
         DisplayNameProposedStatus = GetProposedDisplayNameStatus(displayName.proposedStatus);
     }
 }
コード例 #6
0
 public void RestoreLastSession(Action <IRestoreLastSessionResult> callback)
 {
     try
     {
         database.ClearServerTimeOffsetMillis();
         SessionDocument lastSessionDoc = database.GetLastLoggedInSessionDocument();
         if (lastSessionDoc == null)
         {
             callback(new RestoreLastSessionNotFoundResult());
         }
         else
         {
             IGuestControllerClient guestControllerClient = guestControllerClientFactory.Create(lastSessionDoc.Swid);
             guestControllerClient.Refresh(delegate(GuestControllerResult <RefreshResponse> r)
             {
                 if (r.Response == null)
                 {
                     logger.Error("Error refreshing auth token");
                     callback(new RestoreLastSessionResult(success: false, null));
                 }
                 else
                 {
                     HandleRefreshSuccess(callback, r, lastSessionDoc);
                 }
             });
         }
     }
     catch (CorruptionException arg)
     {
         logger.Fatal("Corruption detected during session restoration: " + arg);
         callback(new RestoreLastSessionCorruptionDetectedResult());
     }
     catch (Exception arg2)
     {
         logger.Critical("Unhandled exception: " + arg2);
         callback(new RestoreLastSessionResult(success: false, null));
     }
 }
コード例 #7
0
        private void HandleWwwDone(object sender, WwwDoneEventArgs e)
        {
            wwwCall.OnDone -= HandleWwwDone;
            bool   flag  = false;
            string error = wwwCall.Error;

            if (!string.IsNullOrEmpty(error))
            {
                string text = error.ToLower();
                flag = text == "couldn't connect to host" || text.Contains("timedout") || text.Contains("timed out");
            }
            if (flag)
            {
                string responsePlaintext = GetResponsePlaintext(wwwCall.ResponseBody);
                string text2             = HttpLogBuilder.BuildTimeoutLog(wwwCall.RequestId, uri, method, wwwCall.ResponseHeaders, responsePlaintext, wwwCall.TimeToStartUpload, wwwCall.TimeToFinishUpload, wwwCall.PercentUploaded, wwwCall.TimeToStartDownload, wwwCall.TimeToFinishDownload, wwwCall.PercentDownloaded, wwwCall.TimeoutReason, wwwCall.TimeoutTime);
                timeoutLogs.Append(text2);
                timeoutLogs.Append("\n\n");
                logger.Error(text2);
                wwwCall.Dispose();
                if (numAttempts > 3)
                {
                    logger.Critical("Too many timeouts: " + uri.AbsoluteUri + "\nPrevious logs:\n" + timeoutLogs);
                    DispatchError("Too many timeouts");
                }
                else
                {
                    Execute();
                }
                return;
            }
            uint statusCode = wwwCall.StatusCode;

            if (statusCode >= 500 && statusCode <= 599)
            {
                string responsePlaintext = GetResponsePlaintext(wwwCall.ResponseBody);
                string text2             = HttpLogBuilder.BuildResponseLog(wwwCall.RequestId, uri, method, wwwCall.ResponseHeaders, responsePlaintext, statusCode);
                wwwCall.Dispose();
                if (numAttempts > 1)
                {
                    logger.Critical("Too many server errors:\n" + text2);
                    DispatchError(statusCode + " Server error: " + wwwCall.Error);
                }
                else
                {
                    logger.Error(text2);
                    Execute();
                }
                return;
            }
            bool flag2 = statusCode >= 200 && statusCode <= 299;

            if (statusCode >= 400 && statusCode <= 499)
            {
                string responsePlaintext;
                try
                {
                    responsePlaintext = GetResponseText(wwwCall.ResponseBody);
                }
                catch (Exception ex)
                {
                    logger.Warning("Text was not encrypted, error: " + ex);
                    responsePlaintext = GetResponsePlaintext(wwwCall.ResponseBody);
                }
                if (statusCode == 429)
                {
                    this.OnError(this, new WebCallErrorEventArgs(statusCode + " Too many requests", "THROTTLED"));
                    return;
                }
                string status = GetStatus(responsePlaintext);
                if (statusCode == 401)
                {
                    logger.Debug(HttpLogBuilder.BuildResponseLog(wwwCall.RequestId, uri, method, wwwCall.ResponseHeaders, responsePlaintext, statusCode));
                    wwwCall.Dispose();
                    this.OnUnauthorized(this, new WebCallUnauthorizedEventArgs(status, responsePlaintext));
                }
                else
                {
                    logger.Error(HttpLogBuilder.BuildResponseLog(wwwCall.RequestId, uri, method, wwwCall.ResponseHeaders, responsePlaintext, statusCode));
                    this.OnError(this, new WebCallErrorEventArgs(statusCode + " Client error = " + wwwCall.Error, status));
                    wwwCall.Dispose();
                }
            }
            else if (flag2)
            {
                string responsePlaintext;
                try
                {
                    responsePlaintext = GetResponseText(wwwCall.ResponseBody);
                }
                catch (Exception ex)
                {
                    string responsePlaintext2 = GetResponsePlaintext(wwwCall.ResponseBody);
                    logger.Critical(string.Concat("Error getting response body:\n", ex, "\n", HttpLogBuilder.BuildResponseLog(wwwCall.RequestId, uri, method, wwwCall.ResponseHeaders, responsePlaintext2, statusCode)));
                    DispatchError(statusCode + " Couldn't get response body text");
                    wwwCall.Dispose();
                    return;
                }
                logger.Debug(HttpLogBuilder.BuildResponseLog(wwwCall.RequestId, uri, method, wwwCall.ResponseHeaders, responsePlaintext, statusCode));
                TResponse val = null;
                try
                {
                    val = JsonParser.FromJson <TResponse>(responsePlaintext);
                }
                catch (Exception ex)
                {
                    logger.Critical(string.Concat("Error parsing response body: ", ex, "\n", responsePlaintext));
                }
                if (val != null && val.Status == "OK")
                {
                    this.OnResponse(this, new WebCallEventArgs <TResponse>(val));
                }
                else
                {
                    DispatchError(statusCode + " Response JSON is invalid or indicates an error: " + responsePlaintext);
                }
                wwwCall.Dispose();
            }
            else
            {
                bool flag3 = false;
                if (!string.IsNullOrEmpty(error))
                {
                    string text = error.ToLower();
                    flag3 = text.Contains("connection appears to be offline") || text.Contains("connection was lost") || text.Contains("network is unreachable");
                }
                if (flag3)
                {
                    logger.Error("Offline error = " + wwwCall.Error);
                }
                else
                {
                    logger.Critical("Other web call error = " + wwwCall.Error);
                }
                DispatchError(statusCode + " Other web call error = " + wwwCall.Error);
                wwwCall.Dispose();
            }
        }
コード例 #8
0
    private void ExecuteNextCall()
    {
        if (isExecuting || queue.Count == 0)
        {
            return;
        }
        QueueItem item = queue[0];
        Dictionary <string, string> dictionary = new Dictionary <string, string>();

        dictionary.Add("Content-Type", "application/json");
        dictionary.Add("Accept", "application/json");
        dictionary.Add("Cache-Control", "no-cache,no-store,must-revalidate");
        Dictionary <string, string> dictionary2 = dictionary;

        if (spoofedIpAddress != null)
        {
            dictionary2["X-Forwarded-For"] = spoofedIpAddress;
        }
        switch (item.AuthType)
        {
        case GuestControllerAuthenticationType.ApiKey:
        {
            string guestControllerApiKey = database.GetGuestControllerApiKey();
            if (guestControllerApiKey == null)
            {
                GetApiKeyImmediately(delegate(GuestControllerResult <GuestControllerWebCallResponse> r)
                    {
                        if (!r.Success)
                        {
                            logger.Critical("Getting API key failed");
                            queue.Remove(item);
                            CallCallbackWithFailureResult(item, null, null);
                        }
                        ExecuteNextCall();
                    });
                return;
            }
            dictionary2["Authorization"] = "APIKEY " + guestControllerApiKey;
            break;
        }

        case GuestControllerAuthenticationType.AccessToken:
        {
            SessionDocument sessionDocument = database.GetSessionDocument(swid);
            if (sessionDocument == null)
            {
                logger.Critical("Guest Controller web call requires access token, but no session document found");
                queue.Remove(item);
                CallCallbackWithFailureResult(item, null, null);
                ExecuteNextCall();
                return;
            }
            string guestControllerAccessToken = sessionDocument.GuestControllerAccessToken;
            if (guestControllerAccessToken == null)
            {
                logger.Critical("Guest Controller web call requires access token, session document doesn't have one");
                queue.Remove(item);
                CallCallbackWithFailureResult(item, null, null);
                ExecuteNextCall();
                return;
            }
            dictionary2["Authorization"] = "BEARER " + guestControllerAccessToken;
            break;
        }
        }
        item.NumAttempts++;
        isExecuting = true;
        IWwwCall wwwCall = wwwCallFactory.Create(item.Uri, item.HttpMethod, item.RequestBody, dictionary2, 60000L, 70000L);

        logger.Debug(HttpLogBuilder.BuildRequestLog(wwwCall.RequestId, item.Uri, item.HttpMethod, dictionary2, item.RequestBodyJson));
        wwwCalls.Add(wwwCall);
        wwwCall.OnDone += delegate
        {
            isExecuting = false;
            Dictionary <string, string> responseHeaders = new Dictionary <string, string>(wwwCall.ResponseHeaders);
            string error                            = wwwCall.Error;
            int    requestId                        = wwwCall.RequestId;
            long   timeToStartUpload                = wwwCall.TimeToStartUpload;
            long   timeToFinishUpload               = wwwCall.TimeToFinishUpload;
            float  percentUploaded                  = wwwCall.PercentUploaded;
            long   timeToStartDownload              = wwwCall.TimeToStartDownload;
            long   timeToFinishDownload             = wwwCall.TimeToFinishDownload;
            float  percentDownloaded                = wwwCall.PercentDownloaded;
            string timeoutReason                    = wwwCall.TimeoutReason;
            long   timeoutTime                      = wwwCall.TimeoutTime;
            uint   statusCode                       = wwwCall.StatusCode;
            string responseText                     = (wwwCall.ResponseBody == null) ? string.Empty : stringEncoding.GetString(wwwCall.ResponseBody);
            GuestControllerWebCallResponse response = item.ResponseParser(responseText);
            if (response == null)
            {
                CallCallbackWithFailureResult(item, null, responseHeaders);
            }
            else
            {
                wwwCalls.Remove(wwwCall);
                wwwCall.Dispose();
                if (!string.IsNullOrEmpty(error))
                {
                    string text = error.ToLower();
                    if (text == "couldn't connect to host" || text.Contains("timedout") || text.Contains("timed out"))
                    {
                        string text2 = HttpLogBuilder.BuildTimeoutLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, timeToStartUpload, timeToFinishUpload, percentUploaded, timeToStartDownload, timeToFinishDownload, percentDownloaded, timeoutReason, timeoutTime);
                        item.TimeoutLogs.Append(text2);
                        item.TimeoutLogs.Append("\n\n");
                        logger.Error(text2);
                        if (item.NumAttempts > 3)
                        {
                            logger.Critical("Too many timeouts: " + item.Uri.AbsoluteUri + "\nPrevious logs:\n" + item.TimeoutLogs);
                            queue.Remove(item);
                            CallCallbackWithFailureResult(item, response, responseHeaders);
                        }
                        ExecuteNextCall();
                        return;
                    }
                }
                if (statusCode >= 500 && statusCode <= 599)
                {
                    string text2 = HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode);
                    if (item.NumAttempts > 1)
                    {
                        logger.Critical(text2);
                        logger.Critical("Too many server errors");
                        queue.Remove(item);
                        CallCallbackWithFailureResult(item, response, responseHeaders);
                    }
                    else
                    {
                        logger.Error(text2);
                    }
                    ExecuteNextCall();
                }
                else if (HasErrorCode(response, "API_KEY_INVALID"))
                {
                    logger.Error(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode));
                    if (item.RefreshedApiKey)
                    {
                        logger.Critical("Invalid API key. Already got new token once. Giving up.");
                        queue.Remove(item);
                        CallCallbackWithFailureResult(item, response, responseHeaders);
                        ExecuteNextCall();
                    }
                    else
                    {
                        logger.Error("Invalid API key. Getting new API key...");
                        GetApiKeyImmediately(delegate(GuestControllerResult <GuestControllerWebCallResponse> r)
                        {
                            if (!r.Success)
                            {
                                logger.Critical(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode));
                                logger.Critical("Getting new API key failed.");
                                queue.Remove(item);
                                CallCallbackWithFailureResult(item, response, responseHeaders);
                            }
                            ExecuteNextCall();
                        });
                    }
                }
                else if (HasErrorCode(response, "RATE_LIMITED"))
                {
                    logger.Error(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode));
                    if (item.RefreshedApiKey)
                    {
                        logger.Critical("Couldn't get new API key. Already got new API key once. Giving up.");
                        queue.Remove(item);
                        CallCallbackWithFailureResult(item, response, responseHeaders);
                        ExecuteNextCall();
                    }
                    else
                    {
                        logger.Error("Rate limited. Getting new API key...");
                        GetApiKeyImmediately(delegate(GuestControllerResult <GuestControllerWebCallResponse> r)
                        {
                            if (!r.Success || HasErrorCode(r.Response, "RATE_LIMITED"))
                            {
                                logger.Critical(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode));
                                logger.Critical("Getting new API key failed.");
                                queue.Remove(item);
                                CallCallbackWithFailureResult(item, response, responseHeaders);
                            }
                            ExecuteNextCall();
                        });
                    }
                }
                else if (HasErrorCode(response, "ACCESS_TOKEN_NOT_FOUND", "AUTHORIZATION_INVALID_OR_EXPIRED_TOKEN"))
                {
                    logger.Error(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode));
                    if (item.RefreshedAccessToken)
                    {
                        logger.Critical("Invalid access token. Already tried to refresh. Giving up.");
                        queue.Remove(item);
                        CallCallbackWithFailureResult(item, response, responseHeaders);
                        ExecuteNextCall();
                    }
                    else
                    {
                        logger.Error("Invalid access token. Refreshing...");
                        RefreshImmediately(delegate(GuestControllerResult <RefreshResponse> r)
                        {
                            if (!r.Success)
                            {
                                logger.Critical(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode));
                                logger.Critical("Refreshing access token failed");
                                queue.Remove(item);
                                CallCallbackWithFailureResult(item, response, responseHeaders);
                            }
                            ExecuteNextCall();
                        });
                    }
                }
                else if (statusCode >= 401 && statusCode <= 499)
                {
                    logger.Critical(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode));
                    queue.Remove(item);
                    CallCallbackWithFailureResult(item, response, responseHeaders);
                    ExecuteNextCall();
                }
                else if (statusCode == 400 || (statusCode >= 200 && statusCode <= 299))
                {
                    logger.Debug(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode));
                    queue.Remove(item);
                    item.Callback(new GuestControllerResult <GuestControllerWebCallResponse>(success: true, response, responseHeaders));
                    ExecuteNextCall();
                }
                else
                {
                    if (!string.IsNullOrEmpty(error))
                    {
                        string text = error.ToLower();
                        if (text.Contains("connection appears to be offline") || text.Contains("connection was lost") || text.Contains("network is unreachable"))
                        {
                            logger.Critical(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode));
                            logger.Critical("Offline error = " + error);
                        }
                        else
                        {
                            logger.Critical(HttpLogBuilder.BuildResponseLog(requestId, item.Uri, item.HttpMethod, responseHeaders, responseText, statusCode));
                            logger.Critical("Other web call error = " + error);
                        }
                    }
                    queue.Remove(item);
                    CallCallbackWithFailureResult(item, response, responseHeaders);
                    ExecuteNextCall();
                }
            }
        };
        wwwCall.Execute();
    }