public ApiModel(string endpoint, Dictionary <string, object> fields) : this(endpoint) { string Error = null; SetApiFieldsFromJson(fields, ref Error); if (Error != null) { Logger.LogFormat(DebugLevel.API, "Error applying fields: {0}", Error); } }
public static void SendRequest(string endpoint, HTTPMethods method, ApiContainer responseContainer = null, Dictionary <string, object> requestParams = null, bool authenticationRequired = true, bool disableCache = false, float cacheLifetime = 3600f, int retryCount = 2, CredentialsBundle credentials = null) { if (Logger.DebugLevelIsEnabled(DebugLevel.API)) { Logger.LogFormat(DebugLevel.API, "Requesting {0} {1} {2} disableCache: {3} retryCount: {4}", method, endpoint, (requestParams == null) ? "{{}}" : Json.Encode(requestParams).Replace("{", "{{").Replace("}", "}}"), disableCache.ToString(), retryCount.ToString()); } UpdateDelegator.Dispatch(delegate { SendRequestInternal(endpoint, method, responseContainer, requestParams, authenticationRequired, disableCache, cacheLifetime, retryCount, credentials); }); }
protected virtual bool ReadField(string fieldName, ref object data) { PropertyInfo propertyInfo = FindProperty(fieldName); if (propertyInfo == null) { Logger.LogFormat(DebugLevel.API, "{0}: Could not read property {1}", GetType().Name, fieldName); return(false); } MethodInfo getMethod = propertyInfo.GetGetMethod(); data = getMethod.Invoke(this, new object[0]); if (data == null) { return(false); } if (!TryReadConvert(ref data)) { Logger.LogErrorFormat(DebugLevel.API, "{0}: Could not read property due to encoding failure, {1} is a {2}", GetType().Name, fieldName, propertyInfo.PropertyType.FullName); return(false); } return(true); }
private static void SendRequestInternal(string endpoint, HTTPMethods method, ApiContainer responseContainer = null, Dictionary <string, object> requestParams = null, bool authenticationRequired = true, bool disableCache = false, float cacheLifetime = 3600f, int retryCount = 2, CredentialsBundle credentials = null) { if (responseContainer == null) { responseContainer = new ApiContainer(); } if (API_ONLINE_MODE == ApiOnlineMode.Offline) { SendOfflineRequest(endpoint, method, responseContainer, requestParams); } else { if (API_ONLINE_MODE == ApiOnlineMode.Uninitialized) { Debug.LogError((object)"Api Web Request send before online mode is initialized."); } string apiUrl = GetApiUrl(); Action action = delegate { string uri = apiUrl + endpoint; UriBuilder baseUri = new UriBuilder(uri); if (!string.IsNullOrEmpty(ApiKey)) { AppendQuery(ref baseUri, "apiKey=" + ApiKey); } if (API_ORGANIZATION == null) { throw new Exception("ApiModel does not have it's organization set!"); } AppendQuery(ref baseUri, "organization=" + API_ORGANIZATION); string text = null; if (requestParams != null) { if (method == HTTPMethods.Get) { foreach (KeyValuePair <string, object> requestParam in requestParams) { string text2 = null; AppendQuery(ref baseUri, string.Concat(str2: (!(requestParam.Value is string)) ? ((!typeof(List <>).IsAssignableFrom(requestParam.Value.GetType())) ? Json.Encode(requestParam.Value) : Json.Encode((requestParam.Value as IList).Cast <object>().ToArray())) : (requestParam.Value as string), str0: requestParam.Key, str1: "=")); } } else { text = Json.Encode(requestParams); } } string uriPath = baseUri.Uri.PathAndQuery; bool useCache = !disableCache && method == HTTPMethods.Get; ApiCache.CachedResponse cachedResponse = (!useCache) ? null : ApiCache.GetOrClearCachedResponse(baseUri.Uri.PathAndQuery, cacheLifetime); if (cachedResponse != null) { Logger.LogFormat(DebugLevel.API, "Using cached {0} request to {1}", method, baseUri.Uri); try { if (responseContainer.OnComplete(success: true, baseUri.Uri.PathAndQuery, 200, string.Empty, () => cachedResponse.Data, () => cachedResponse.DataAsText, cachedResponse.Timestamp)) { responseContainer.OnSuccess(responseContainer); } else { Logger.LogErrorFormat(DebugLevel.API, "Something went wrong re-serving data from cache for {0}", baseUri.Uri); } } catch (Exception ex) { Debug.LogException(ex); } } else if (method == HTTPMethods.Get && activeRequests.ContainsKey(uriPath)) { Logger.LogFormat(DebugLevel.API, "Piggy-backing {0} request to {1}", method, baseUri.Uri); OnRequestFinishedDelegate originalCallback = activeRequests[uriPath].Callback; activeRequests[uriPath].Callback = delegate(HTTPRequest req, HTTPResponse resp) { if (activeRequests.ContainsKey(uriPath)) { activeRequests.Remove(uriPath); } if (originalCallback != null) { originalCallback(req, resp); } try { APIResponseHandler.HandleReponse(0, req, resp, responseContainer, retryCount, useCache); } catch (Exception ex2) { Debug.LogException(ex2); } }; } else { int requestId = ++lastRequestId; Logger.LogFormat(DebugLevel.API, "[{0}] Sending {1} request to {2}", requestId, method, baseUri.Uri); HTTPRequest hTTPRequest = new HTTPRequest(baseUri.Uri, delegate(HTTPRequest req, HTTPResponse resp) { if (activeRequests.ContainsKey(uriPath)) { activeRequests.Remove(uriPath); } APIResponseHandler.HandleReponse(requestId, req, resp, responseContainer, retryCount, useCache); }); if (authenticationRequired) { if (credentials != null) { hTTPRequest.Credentials = new Credentials(AuthenticationTypes.Basic, credentials.Username, credentials.Password); } else if (!string.IsNullOrEmpty(ApiCredentials.GetAuthToken())) { List <Cookie> cookies = hTTPRequest.Cookies; cookies.Add(new Cookie("auth", ApiCredentials.GetAuthToken())); hTTPRequest.Cookies = cookies; } else { Logger.LogErrorFormat(DebugLevel.API, "No credentials!"); } } hTTPRequest.AddHeader("X-Requested-With", "XMLHttpRequest"); hTTPRequest.AddHeader("X-MacAddress", DeviceID); if (Tools.isClient) { hTTPRequest.AddHeader("X-Client-Version", Tools.ClientVersion); } else { hTTPRequest.AddHeader("X-SDK-Version", Tools.ClientVersion); } hTTPRequest.AddHeader("X-Platform", Tools.Platform); hTTPRequest.AddHeader("Content-Type", (method != 0) ? "application/json" : "application/x-www-form-urlencoded"); hTTPRequest.AddHeader("Origin", "vrchat.com"); hTTPRequest.MethodType = method; hTTPRequest.ConnectTimeout = TimeSpan.FromSeconds(20.0); hTTPRequest.Timeout = TimeSpan.FromSeconds(60.0); hTTPRequest.EnableTimoutForStreaming = true; if (!string.IsNullOrEmpty(text)) { hTTPRequest.RawData = Encoding.UTF8.GetBytes(text); } if (method == HTTPMethods.Get) { activeRequests.Add(uriPath, hTTPRequest); } hTTPRequest.DisableCache = true; hTTPRequest.Send(); } string key = endpoint.ToLower().Split('?')[0]; if (!EndpointAccessTimes.ContainsKey(key)) { EndpointAccessTimes.Add(key, new EndpointAccessEntry { count = 1, time = Time.get_realtimeSinceStartup() }); } else { EndpointAccessTimes[key].time = Time.get_realtimeSinceStartup(); EndpointAccessTimes[key].count++; } }; if (endpoint != "config" && string.IsNullOrEmpty(ApiKey) && !IsOffline()) { FetchApiKey(action); } else { action(); } } }