Exemplo n.º 1
0
        private void OnRsp(RequestMessageWrapper sendMessageWrapper, HTTPResponse response)
        {
            if (response.GetFirstHeaderValue("msgId") == null)
            {
                Debug.Log("BEST HTTP :error message no message id on response header");
                return;
            }
            else
            {
                int messageId = int.Parse(response.GetFirstHeaderValue("msgId"));
                if (messageId == 400)
                {
                    GOEngine.DebugUtil.Log($"BEST HTTP :server error == 400  ,server ip:{this.m_serverIp}");
                }

                byte[] buffer = response.Data;

                if (!string.IsNullOrEmpty(response.GetFirstHeaderValue("errorCode")))
                {
                    int    errorCode    = int.Parse(response.GetFirstHeaderValue("errorCode"));
                    string errorContent = Encoding.UTF8.GetString(buffer);

                    EngineCoreEvents.SystemEvents.NetWorkError.SafeInvoke(errorCode, errorContent);
                }
                else
                {
                    IMessage message = EngineCore.MessageParser.Parse(messageId, buffer);

                    this.m_messageQueue.Enqueue(new ResponseMessageWrapper(messageId, message));


                    HttpPairCahce.EnCache(sendMessageWrapper.MessageBody);
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Returns true if the stored caching values are the same than the ones in the response.
        /// </summary>
        private bool AlreadyStored(HTTPResponse response)
        {
            if (!IsExists())
            {
                return(false);
            }

            string newEtag = response.GetFirstHeaderValue("ETag").ToStrOrEmpty();

            if (newEtag != this.ETag)
            {
                return(false);
            }

            DateTime newExpires = response.GetFirstHeaderValue("Expires").ToDateTime(DateTime.FromBinary(0));

            if (newExpires != this.Expires)
            {
                return(false);
            }

            string newLastModified = response.GetFirstHeaderValue("Last-Modified").ToStrOrEmpty();

            if (newLastModified != this.LastModified)
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 3
0
        private Response <T> ProcessResponse <T>(HTTPRequest request, HTTPResponse httpResponse)
        {
            Response <T> response;

            if (httpResponse.IsSuccess)
            {
                if (typeof(T) == typeof(ResponseBody))
                {
                    ResponseBody responseBody = new ResponseBody(
                        httpResponse.Data,
                        httpResponse.GetFirstHeaderValue("Content-Type")
                        );

                    response = new Response <T>((T)Convert.ChangeType(responseBody, typeof(T)), httpResponse);
                }
                else
                {
                    response = new Response <T>(converter.ToObject <T>(httpResponse.DataAsText), httpResponse);
                }
            }
            else
            {
                ResponseBody responseBody = new ResponseBody(
                    httpResponse.Data,
                    httpResponse.GetFirstHeaderValue("Content-Type")
                    );
                response = new Response <T>(responseBody, httpResponse);
            }

            return(response);
        }
        private SupportedSocketIOVersions GetServerVersion(HTTPResponse resp)
        {
            string contentTypeValue = resp.GetFirstHeaderValue("content-type");

            if (string.IsNullOrEmpty(contentTypeValue))
            {
                return(SupportedSocketIOVersions.v2);
            }

            HeaderParser contentType = new HeaderParser(contentTypeValue);
            PayloadTypes type        = contentType.Values.FirstOrDefault().Key == "text/plain" ? PayloadTypes.Text : PayloadTypes.Binary;

            if (type != PayloadTypes.Text)
            {
                return(SupportedSocketIOVersions.v2);
            }

            // https://github.com/socketio/engine.io-protocol/issues/35
            // v3: 96:0{ "sid":"lv_VI97HAXpY6yYWAAAC","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
            // v4:    0{ "sid":"lv_VI97HAXpY6yYWAAAC","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
            for (int i = 0; i < resp.Data.Length; ++i)
            {
                if (resp.Data[i] == ':')
                {
                    return(SupportedSocketIOVersions.v2);
                }
                if (resp.Data[i] == '{')
                {
                    return(SupportedSocketIOVersions.v3);
                }
            }

            return(SupportedSocketIOVersions.Unknown);
        }
Exemplo n.º 5
0
    void OnGUI()
    {
        if (GUI.Button(new Rect(10, 10, 200, 60), "Refresh") && (response == null || response.IsStreamingFinished))
        {
            StartRefreshLeaderboard();
        }

        if (GUI.Button(new Rect(240, 10, 200, 60), "Clear Cache"))
        {
            BestHTTP.Caching.HTTPCacheService.BeginClear();
        }

        GUI.Label(new Rect(10, 80, 200, 20), "Rank          Name            Points");
        if (Entries.Count > 0)
        {
            for (int i = 0; i < Entries.Count; ++i)
            {
                GUI.Label(new Rect(10, 100 + (i * 30), 400, 25), string.Format("{0,5}{1,20}{2,6}", from + i + 1, Entries[i].Name, Entries[i].Points));
            }
        }

        if (response != null)
        {
            GUI.color = response.IsStreamingFinished ? Color.green : Color.red;
            string status = response.IsStreamingFinished ? "Download Finished" : "Downloading";
            if (response.IsFromCache)
            {
                GUI.color = Color.yellow;
                status   += " From Cache!";
            }

            GUI.Label(new Rect(80, 100 + (Entries.Count + 1) * 30, 250, 20), status);
            GUI.color = Color.white;

            string expires = response.GetFirstHeaderValue("expires");
            GUI.Label(new Rect(10, Screen.height - 50, 400, 20), "Cache will expire: " + DateTime.Parse(expires).ToUniversalTime());
            GUI.Label(new Rect(10, Screen.height - 25, 400, 20), "Current time: " + DateTime.UtcNow);
        }

        if (response != null && response.IsStreamingFinished)
        {
            if (GUI.Button(new Rect(20, 500, 200, 60), "Prev Page") && from > 0)
            {
                from -= count;
                StartRefreshLeaderboard();
            }

            if (GUI.Button(new Rect(250, 500, 200, 60), "Next Page"))
            {
                from += count;
                StartRefreshLeaderboard();
            }
        }

        if (GUI.Button(new Rect(Screen.width - 120, Screen.height - 65, 110, 60), "Back"))
        {
            Application.LoadLevel(0);
        }
    }
        private void SetUpCachingValues(HTTPResponse response)
        {
            response.CacheFileInfo = this;

            this.ETag         = response.GetFirstHeaderValue("ETag").ToStrOrEmpty();
            this.Expires      = response.GetFirstHeaderValue("Expires").ToDateTime(DateTime.FromBinary(0));
            this.LastModified = response.GetFirstHeaderValue("Last-Modified").ToStrOrEmpty();

            this.Age = response.GetFirstHeaderValue("Age").ToInt64(0);

            this.Date = response.GetFirstHeaderValue("Date").ToDateTime(DateTime.FromBinary(0));

            string cacheControl = response.GetFirstHeaderValue("cache-control");

            if (!string.IsNullOrEmpty(cacheControl))
            {
                string[] kvp = cacheControl.FindOption("max-age");
                if (kvp != null)
                {
                    // Some cache proxies will return float values
                    double maxAge;
                    if (double.TryParse(kvp[1], out maxAge))
                    {
                        this.MaxAge = (int)maxAge;
                    }
                }

                this.MustRevalidate = cacheControl.ToLower().Contains("must-revalidate");
            }

            this.Received = DateTime.UtcNow;
        }
    private void OnHeadRequestComplete(HTTPRequest request, HTTPResponse response)
    {
        if (response == null ||
            request.State == HTTPRequestStates.Error)
        {
            OnHeadRequestError(request);
            return;
        }

        long contentSize = Convert.ToInt64(response.GetFirstHeaderValue("content-length"));

        mContentSize = contentSize;

        Debug.Log("Head request is complete. Status code: " + response.StatusCode);
        ExecuteVideoDownload(request, mContentSize, mConnectionCount);
    }
Exemplo n.º 8
0
        private bool OnData(HTTPRequest request, HTTPResponse response, byte[] dataFragment, int dataFragmentLength)
        {
            if (this.State == States.Connecting)
            {
                string contentType = response.GetFirstHeaderValue("content-type");
                bool   IsUpgraded  = response.StatusCode == 200 &&
                                     !string.IsNullOrEmpty(contentType) &&
                                     contentType.ToLower().StartsWith("text/event-stream");

                if (IsUpgraded)
                {
                    ProtocolEventHelper.AddProtocol(this);

                    if (this.OnOpen != null)
                    {
                        try
                        {
                            this.OnOpen(this);
                        }
                        catch (Exception ex)
                        {
                            HTTPManager.Logger.Exception("EventSource", "OnOpen", ex, request.Context);
                        }
                    }

                    this.RetryCount = 0;
                    this.State      = States.Open;
                }
                else
                {
                    this.State = States.Closing;
                    request.Abort();
                }
            }

            if (this.State == States.Closing)
            {
                return(true);
            }

            if (FeedData(dataFragment, dataFragmentLength))
            {
                ProtocolEventHelper.EnqueueProtocolEvent(new ProtocolEventInfo(this));
            }

            return(true);
        }
Exemplo n.º 9
0
        private void OnHeadersReceived(HTTPRequest req, HTTPResponse resp, Dictionary <string, List <string> > newHeaders)
        {
            var range = resp.GetRange();

            if (range != null)
            {
                this.DownloadLength = range.ContentLength;
            }
            else
            {
                var contentLength = resp.GetFirstHeaderValue("content-length");
                if (contentLength != null)
                {
                    long length = 0;
                    if (long.TryParse(contentLength, out length))
                    {
                        this.DownloadLength = length;
                    }
                }
            }
        }
Exemplo n.º 10
0
        private void OnASyncRequestFinished(HTTPRequest originalRequest, HTTPResponse response)
        {
            RequestMessageWrapper sendMessageWrapper = HttpSendingCahce.GetAndRemoveFromSendingCache(originalRequest);

            if (null == sendMessageWrapper)
            {
                Debug.LogError($"BEST HTTP : return unknown rsp {response.GetFirstHeaderValue("msgId")}");
                return;
            }
            switch (originalRequest.State)
            {
            case HTTPRequestStates.Finished:
                //Debug.Log("Request Finished Successfully!\n" + response.DataAsText);
                OnRsp(sendMessageWrapper, response);
                break;

            case HTTPRequestStates.Error:
                Debug.LogError("BEST HTTP :Request Finished with Error! " + (originalRequest.Exception != null ? (originalRequest.Exception.Message + "\n" + originalRequest.Exception.StackTrace) : "No Exception"));
                BornErrorLog(sendMessageWrapper);
                break;

            case HTTPRequestStates.Aborted:
                Debug.LogWarning("BEST HTTP :Request Aborted!");
                BornErrorLog(sendMessageWrapper);
                break;

            case HTTPRequestStates.ConnectionTimedOut:
                Debug.LogError("BEST HTTP :Connection Timed Out!");
                BornErrorLog(sendMessageWrapper);
                break;

            case HTTPRequestStates.TimedOut:
                Debug.LogError("BEST HTTP :Processing the request Timed Out!");
                BornErrorLog(sendMessageWrapper);
                break;
            }
        }
Exemplo n.º 11
0
        private void SetUpCachingValues(HTTPResponse response)
        {
            ETag         = response.GetFirstHeaderValue("ETag").ToStrOrEmpty();
            Expires      = response.GetFirstHeaderValue("Expires").ToDateTime(DateTime.FromBinary(0L));
            LastModified = response.GetFirstHeaderValue("Last-Modified").ToStrOrEmpty();
            Age          = response.GetFirstHeaderValue("Age").ToInt64(0L);
            Date         = response.GetFirstHeaderValue("Date").ToDateTime(DateTime.FromBinary(0L));
            string firstHeaderValue = response.GetFirstHeaderValue("cache-control");

            if (!string.IsNullOrEmpty(firstHeaderValue))
            {
                string[] array = firstHeaderValue.FindOption("Max-Age");
                if (array != null && double.TryParse(array[1], out double result))
                {
                    MaxAge = (int)result;
                }
                MustRevalidate = firstHeaderValue.ToLower().Contains("must-revalidate");
            }
            Received = DateTime.UtcNow;
        }
Exemplo n.º 12
0
        internal void SetUpCachingValues(HTTPResponse response)
        {
            response.CacheFileInfo = this;

            this.ETag         = response.GetFirstHeaderValue("ETag").ToStr(this.ETag ?? string.Empty);
            this.Expires      = response.GetFirstHeaderValue("Expires").ToDateTime(this.Expires);
            this.LastModified = response.GetFirstHeaderValue("Last-Modified").ToStr(this.LastModified ?? string.Empty);

            this.Age = response.GetFirstHeaderValue("Age").ToInt64(this.Age);

            this.Date = response.GetFirstHeaderValue("Date").ToDateTime(this.Date);

            List <string> cacheControls = response.GetHeaderValues("cache-control");

            if (cacheControls != null && cacheControls.Count > 0)
            {
                // Merge all Cache-Control header values into one
                string cacheControl = cacheControls[0];
                for (int i = 1; i < cacheControls.Count; ++i)
                {
                    cacheControl += "," + cacheControls[i];
                }

                if (!string.IsNullOrEmpty(cacheControl))
                {
                    string[] options = cacheControl.ToLowerInvariant().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    string[] kvp = options.FindOption("max-age");
                    if (kvp != null)
                    {
                        // Some cache proxies will return float values
                        double maxAge;
                        if (double.TryParse(kvp[1], out maxAge))
                        {
                            this.MaxAge = (int)maxAge;
                        }
                        else
                        {
                            this.MaxAge = 0;
                        }
                    }
                    else
                    {
                        this.MaxAge = 0;
                    }

                    kvp = options.FindOption("stale-while-revalidate");
                    if (kvp != null && kvp.Length == 2 && !string.IsNullOrEmpty(kvp[1]))
                    {
                        this.StaleWhileRevalidate = kvp[1].ToInt64(0);
                    }

                    kvp = options.FindOption("stale-if-error");
                    if (kvp != null && kvp.Length == 2 && !string.IsNullOrEmpty(kvp[1]))
                    {
                        this.StaleIfError = kvp[1].ToInt64(0);
                    }

                    this.MustRevalidate = cacheControl.Contains("must-revalidate");
                    this.NoCache        = cacheControl.Contains("no-cache");
                }
            }

            this.Received = DateTime.UtcNow;
        }
Exemplo n.º 13
0
        /// <summary>
        /// Checks if the given response can be cached. http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
        /// </summary>
        /// <returns>Returns true if cacheable, false otherwise.</returns>
        internal static bool IsCacheble(Uri uri, HTTPMethods method, HTTPResponse response)
        {
            if (!IsSupported)
            {
                return(false);
            }

            if (method != HTTPMethods.Get)
            {
                return(false);
            }

            if (response == null)
            {
                return(false);
            }

            // https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.12 - Cache Replacement
            // It MAY insert it into cache storage and MAY, if it meets all other requirements, use it to respond to any future requests that would previously have caused the old response to be returned.
            //if (response.StatusCode == 304)
            //    return false;

            // Partial response
            if (response.StatusCode == 206)
            {
                return(false);
            }

            if (response.StatusCode < 200 || response.StatusCode >= 400)
            {
                return(false);
            }

            //http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.2
            var cacheControls = response.GetHeaderValues("cache-control");

            if (cacheControls != null)
            {
                if (cacheControls.Exists(headerValue =>
                {
                    string value = headerValue.ToLower();
                    if (value.StartsWith("max-age"))
                    {
                        string[] kvp = headerValue.FindOption("max-age");
                        if (kvp != null)
                        {
                            // Some cache proxies will return float values
                            double maxAge;
                            if (double.TryParse(kvp[1], out maxAge))
                            {
                                // A negative max-age value is a no cache
                                if (maxAge <= 0)
                                {
                                    return(false);
                                }
                            }
                        }
                    }

                    // https://csswizardry.com/2019/03/cache-control-for-civilians/#no-store
                    return(value.Contains("no-store"));
                }))
                {
                    return(false);
                }
            }

            var pragmas = response.GetHeaderValues("pragma");

            if (pragmas != null)
            {
                if (pragmas.Exists(headerValue =>
                {
                    string value = headerValue.ToLower();
                    return(value.Contains("no-store") || value.Contains("no-cache"));
                }))
                {
                    return(false);
                }
            }

            // Responses with byte ranges not supported yet.
            var byteRanges = response.GetHeaderValues("content-range");

            if (byteRanges != null)
            {
                return(false);
            }

            // Store only if at least one caching header with proper value present

            var etag = response.GetFirstHeaderValue("ETag");

            if (!string.IsNullOrEmpty(etag))
            {
                return(true);
            }

            var expires = response.GetFirstHeaderValue("Expires").ToDateTime(DateTime.FromBinary(0));

            if (expires >= DateTime.UtcNow)
            {
                return(true);
            }

            if (response.GetFirstHeaderValue("Last-Modified") != null)
            {
                return(true);
            }

            return(false);
        }
Exemplo n.º 14
0
    void OnDownloadFile(HTTPRequest request, HTTPResponse response)
    {
        switch (request.State)
        {
        // The request is currently processed. With UseStreaming == true, we can get the streamed fragments here
        case HTTPRequestStates.Processing:

            // Set the DownloadLength, so we can display the progress
            if (downloadLength == 0)
            {
                string value = response.GetFirstHeaderValue("content-length");
                if (!string.IsNullOrEmpty(value))
                {
                    downloadLength = int.Parse(value);
                }
            }
            // Get the fragments, and save them
            ProcessFragments(request, response.GetStreamedFragments());
            break;

        // The request finished without any problem.
        case HTTPRequestStates.Finished:
            if (response.IsSuccess)
            {
                if (downloadLength == 0)
                {
                    string value = response.GetFirstHeaderValue("content-length");
                    if (!string.IsNullOrEmpty(value))
                    {
                        downloadLength = int.Parse(value);
                    }
                }
                // Save any remaining fragments
                ProcessFragments(request, response.GetStreamedFragments());

                // Completly finished
                if (response.IsStreamingFinished)
                {
                    request = null;
                    finishDownload(0, null);
                }
                else
                {
                    Debug.Log("Processing - continue");
                }
            }
            else
            {
                status = string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                       response.StatusCode,
                                       response.Message,
                                       response.DataAsText);
                Debug.LogError(status);
                request = null;
                finishDownload(-1, status);
            }
            break;

        // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
        case HTTPRequestStates.Error:
            status = "Request Finished with Error! " + (request.Exception != null ? (request.Exception.Message + "\n" + request.Exception.StackTrace) : "No Exception");
            Debug.LogError(status);

            request = null;
            finishDownload(-1, status);
            break;

        // The request aborted, initiated by the user.
        case HTTPRequestStates.Aborted:
            status  = "Request Aborted!";
            request = null;
            finishDownload(-1, status);
            break;

        // Ceonnecting to the server is timed out.
        case HTTPRequestStates.ConnectionTimedOut:
            status = "Connection Timed Out!";
            Debug.LogError(status);
            request = null;
            finishDownload(-1, status);
            break;

        // The request didn't finished in the given time.
        case HTTPRequestStates.TimedOut:
            status = "Processing the request Timed Out!";
            Debug.LogError(status);
            request = null;
            finishDownload(-1, status);
            break;
        }
    }
Exemplo n.º 15
0
        private void OnHalfSyncRequestFinished(HTTPRequest originalRequest, HTTPResponse response)
        {
            RequestMessageWrapper sendMessageWrapper = HttpSendingCahce.GetAndRemoveFromSendingCache(originalRequest);

            if (null == sendMessageWrapper)
            {
                Debug.LogError($"BEST HTTP : return unknown rsp {response.GetFirstHeaderValue("msgId")}");
                return;
            }
            switch (originalRequest.State)
            {
            case HTTPRequestStates.Finished:
                //Debug.Log("Request Finished Successfully!\n" + response.DataAsText);
                OnRsp(sendMessageWrapper, response);

                WorkQueueCallback(new SendMessageCallback()
                {
                    MessageId = sendMessageWrapper.MessageId,
                    Status    = NetworkModule.NetworkStatus.SYNC_SUCCEED
                });
                break;

            case HTTPRequestStates.Error:
            {
                Debug.LogError("Request Finished with Error! " + (originalRequest.Exception != null ? (originalRequest.Exception.Message + "\n" + originalRequest.Exception.StackTrace) : "No Exception"));
                WorkQueueCallback(new SendMessageCallback()
                    {
                        MessageId = sendMessageWrapper.MessageId,
                        Status    = NetworkModule.NetworkStatus.OFFLINE_WARNNING
                    });
            }
            break;

            case HTTPRequestStates.Aborted:
                Debug.LogWarning("BEST HTTP :Request Aborted!");
                WorkQueueCallback(new SendMessageCallback()
                {
                    MessageId = sendMessageWrapper.MessageId,
                    Status    = NetworkModule.NetworkStatus.OFFLINE_WARNNING
                });
                break;

            case HTTPRequestStates.ConnectionTimedOut:
                Debug.LogError("BEST HTTP :Connection Timed Out!");
                WorkQueueCallback(new SendMessageCallback()
                {
                    MessageId = sendMessageWrapper.MessageId,
                    Status    = NetworkModule.NetworkStatus.OFFLINE_WARNNING
                });
                break;

            case HTTPRequestStates.TimedOut:
                Debug.LogError("BEST HTTP :Processing the request Timed Out!");
                WorkQueueCallback(new SendMessageCallback()
                {
                    MessageId = sendMessageWrapper.MessageId,
                    Status    = NetworkModule.NetworkStatus.OFFLINE_WARNNING
                });
                break;

            default:
                break;
            }
        }
 public void ProcessHeadResponse(HTTPResponse response)
 {
     Debug.Assert(response != null, this);
     size  = Convert.ToUInt32(response.GetFirstHeaderValue("content-length"));
     state = FileFragmentDataState.ReadyForDownload;
 }