Ejemplo n.º 1
0
 public override void RegistEvents()
 {
     base.RegistEvents();
     RegistEvent(UIEventType.TypeOpenMessageWin, delegate(object[] param)
     {
         type = (MessageWndType)param[0];
         Logger.DebugFormat("type:{0}", type);
         m_title.text   = (string)param[1];
         m_context.text = (string)param[2];
         okHandle       = (OKHandler)param[3];
         cancleHandle   = (CancleHandler)param[4];
     });
 }
Ejemplo n.º 2
0
 public void ShowConfirmMessage(MessageWndType type, string content, string title = "", OKHandler okHandle = null, CancleHandler cancleHandle = null)
 {
     WindowFactory.instance.CreateWindow(WindowType.MessageWindow, delegate(object[] param)
     {
         EventManager.instance.NotifyUIEvent(UIEventType.TypeOpenMessageWin, type, title, content, okHandle, cancleHandle);
     });
 }
Ejemplo n.º 3
0
    public IEnumerator Send(APIRequest req, OKHandler onOK, ErrorHandler onError = null)
    {
        bool queueing = true;

        if (!req.Validate(this))
        {
            req.error = new JsonError("ValidateError", "invalid request");
        }

        // wait until previous Send()
        float fElapsed = 0.0f;

        if (queueing)
        {
            while (isPending && fElapsed < req.timeout)
            {
                yield return(0);

                fElapsed += Time.deltaTime;
            }

            isPending = true;
        }

        string url = baseHost + req.uri;

        WWW www = null;

        bool   error     = false;
        string errorMsg  = "";
        string useragent = "";

        try
        {
            Dictionary <string, string> headers = new Dictionary <string, string>();

#if UNITY_ANDROID
            useragent = "light-elky/" + apiVersion + " gzip android";
#elif UNITY_IOS
            useragent = "light-elky/" + apiVersion + " gzip ios";
#else
            useragent = "light-elky/" + apiVersion + " gzip editor";
#endif

            headers["User-Agent"] = useragent;

            if (isAuthorized)
            {
                headers["COOKIE"] = cookie;
            }
            else
            {
                Log("  cookie: not found");
            }

            // zlib encoded
            string json       = JsonConvert.SerializeObject(req.param);
            byte[] compressed = Ionic.Zlib.GZipStream.CompressString(json);
            //headers["Accept-Encoding"] = "gzip";
            headers["Content-Type"]     = "application/json";
            headers["Content-Encoding"] = "gzip";
            www = new WWW(url, compressed, headers);             // POST only
            var strBase64 = System.Convert.ToBase64String(compressed);
            Log(strBase64);

            www.threadPriority = ThreadPriority.High;

            Log("  http request sent...");
        }
        catch (System.Exception ex)
        {
            error    = true;
            errorMsg = ex.ToString();
            LogWarning(errorMsg);
            LogError(req.uri + ":" + errorMsg);
        }

        // wait for http request
        if (!error)
        {
            while (!www.isDone && www.error == null && fElapsed < req.timeout)
            {
                yield return(0);

                fElapsed += Time.deltaTime;
            }
        }

        if (queueing)
        {
            isPending = false;
            isHandled = false;
        }

        if (error)
        {
            // handle below
            www.Dispose();
            www = null;
        }
        else if (fElapsed >= req.timeout)
        {
            www       = null;
            req.error = new JsonError("TimeoutError", fElapsed.ToString());
        }
        else if (null != www.error)
        {
            req.error = new JsonError("HttpError", www.error);
            Log(www.error);
        }
        else
        {
            try
            {
                foreach (KeyValuePair <string, string> kv in www.responseHeaders)
                {
                    Log("***** [" + kv.Key + "]" + kv.Value);
                }

                // gzip check
                string text = "";
                string contentEncoding;
                www.responseHeaders.TryGetValue("Content-Encoding", out contentEncoding);
                if (string.IsNullOrEmpty(contentEncoding))
                {
                    www.responseHeaders.TryGetValue("CONTENT-ENCODING", out contentEncoding);
                }

                if (contentEncoding == "gzip")
                {
#if UNITY_EDITOR_OSX || UNITY_IOS
                    text = www.text;
#else
                    Log("[gzip] " + www.size + "bytes");
                    Debug.LogWarning("[gzip] " + www.size + "bytes");
                    byte[] decompressed = Ionic.Zlib.GZipStream.UncompressBuffer(www.bytes);
                    text = System.Text.UTF8Encoding.UTF8.GetString(decompressed);
#endif
                }
                else if (contentEncoding == "bson")
                {
                    Log("[bson] " + www.size + "bytes");
                    Debug.LogWarning("[bson] " + www.size + "bytes");

                    MemoryStream ms = new MemoryStream(www.bytes);
                    using (BsonReader reader = new BsonReader(ms))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        object         obj        = serializer.Deserialize(reader);
                        text = obj.ToString();
                    }
                }
                else
                {
                    Debug.LogWarning("[text] " + www.size + "bytes");
                    text = www.text;
                }

                // cookie check
                string setCookie;                 // responseHeaders only have single header, until now
                bool   cookieFound = false;
                www.responseHeaders.TryGetValue("Set-Cookie", out setCookie);
                if (string.IsNullOrEmpty(setCookie))
                {
                    www.responseHeaders.TryGetValue("SET-COOKIE", out setCookie);
                }
                if (setCookie != null && setCookie.Length > 0)
                {
                    string rawCookie  = setCookie.Split(';')[0];
                    string cookieName = rawCookie.Split('=')[0]; // not to remove "
                    cookies_[cookieName] = rawCookie;
                    cookieFound          = true;
                }
                if (cookieFound)
                {
                    foreach (KeyValuePair <string, string> kv in cookies_)
                    {
                        Log("  cookie: " + kv.Value);
                    }
                }
                else if (isAuthorized)
                {
                    Log("  cookie not found from response but authorized.");
                }
                else
                {
                    Log("  cookie not found from response.");
                }

                req.responseText = text;

                // json check
                string contentType;
                bool   isJson = false;
                if (www.responseHeaders.TryGetValue("Content-Type", out contentType))
                {
                    if (contentType.Contains("json"))
                    {
                        isJson = true;
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(text) &&
                        (text[0] == '{' && text[text.Length - 1] == '}' ||
                         text[0] == '[' && text[text.Length - 1] == ']'))
                    {
                        isJson = true;
                    }
                }

                if (isJson)
                {
                    Log("json response. try to parse json...");
                    try
                    {
                        Log(text);
                        {
                            // try parse Response
                            req.Parse(text);
                        }
                    }
                    catch (Exception ex)
                    {
                        req.error = new JsonError("ParseError", ex.ToString());
                        Debug.LogError(ex);
                    }
                }
                else
                {
                    Log("non-json response. skip parsing...");
                }
            }
            catch (Exception ex)
            {
                error    = true;
                errorMsg = ex.ToString();
                LogWarning(errorMsg);
                Debug.LogError(ex);
            }
        }

        if (error)
        {
            req.error = new JsonError("ExceptionError", errorMsg);
        }

        if (req.error == null)
        {
            yield return(StartCoroutine(req.HandleResponse(this)));

            if (req.error == null && onOK != null)
            { // HandleResponse can throw error!
                yield return(StartCoroutine(onOK(req, this)));
            }
        }

        if (req.error != null)
        { // OK handler can throw error.
            yield return(StartCoroutine(req.HandleError(this)));

            if (onError != null)
            {
                yield return(StartCoroutine(onError(req, this)));
            }
            commonOnError(req);
            yield return(0);
        }

        if (queueing)
        {
            isHandled = true;
        }

        yield break;
    }