Exemplo n.º 1
0
        // cache the text because if www was disposed, can't access it.
        public UnityWebRequestErrorException(UnityWebRequest www, string text = "")
        {
            this.WWW             = www;
            this.RawErrorMessage = www.error;
            this.ResponseHeaders = www.GetResponseHeaders();
            this.HasResponse     = false;
            this.Text            = text;

            var splitted = RawErrorMessage.Split(' ', ':');

            if (splitted.Length != 0)
            {
                int statusCode;
                if (int.TryParse(splitted[0], out statusCode))
                {
                    this.HasResponse = true;
                    this.StatusCode  = (System.Net.HttpStatusCode)statusCode;
                }
            }
        }
Exemplo n.º 2
0
        public HttpResponse(UnityWebRequest unityWebRequest)
        {
            Url             = unityWebRequest.url;
            Bytes           = unityWebRequest.downloadHandler.data;
            Text            = unityWebRequest.downloadHandler.text;
            IsSuccessful    = !unityWebRequest.isHttpError && !unityWebRequest.isNetworkError;
            IsHttpError     = unityWebRequest.isHttpError;
            IsNetworkError  = unityWebRequest.isNetworkError;
            Error           = unityWebRequest.error;
            StatusCode      = unityWebRequest.responseCode;
            ResponseType    = HttpUtils.GetResponseType(StatusCode);
            ResponseHeaders = unityWebRequest.GetResponseHeaders();

            var downloadHandlerTexture = unityWebRequest.downloadHandler as DownloadHandlerTexture;

            if (downloadHandlerTexture != null)
            {
                Texture = downloadHandlerTexture.texture;
            }
        }
Exemplo n.º 3
0
    //Dectinary
    IEnumerator SendPostRequest(string data, string requestURL, Action <HTTPResponse> success, Action fail)
    {
        //서버와 약속한 건 post이지만 현재는 문제가 많아 put으로 선언
        //using 문으로 선언하여 동작하는 범위를 지정할 수 있다.
        using (UnityWebRequest www = UnityWebRequest.Put(HTTPNetworkConstant.serverURL + requestURL, data))
        {
            www.method = "Post";
            www.SetRequestHeader("Content-Type", "application/json");

            string sid = PlayerPrefs.GetString("sid", "");
            {
                if (sid != "")
                {
                    www.SetRequestHeader("Set-Cookie", sid);
                }
            }
            //보내기, sendWebRequest를 하면서 다른일을 하게 만들어줌
            yield return(www.SendWebRequest());

            long code = www.responseCode; //www.responseCode는 long 타입 , 응답에대한 코드
            HTTPResponseMessage message = JsonUtility.FromJson <HTTPResponseMessage>(www.downloadHandler.text);

            // 서버 > 클라이언트로 응답(Response) 메시지 도착
            if (www.isNetworkError)
            {
                NetworkErrorHandler();
                fail();
            }
            else if (www.isHttpError)
            {
                HTTPErrorHandler(code, message.message);
                fail();
            }
            else
            {
                Dictionary <string, string> header = www.GetResponseHeaders();// 헤더 정보, 세션아이디 포함
                HTTPResponse response = new HTTPResponse(code, message.message, header);
                success(response);
            }
        }
    }
Exemplo n.º 4
0
    IEnumerator Get(GameObject target, string targetFunc)
    {
        UnityWebRequest www = UnityWebRequest.Get(NetworkManager.Instance().SERVER_URL + ":8080" + "/users");

        yield return(www.Send());

        if (www.isError)
        {
            MDebug.Log("REST Get Error : " + www.error);
        }
        else
        {
            if (www.GetResponseHeaders().Count > 0) //.responseHeaders.Count > 0)
            {
                if (target != null)
                {
                    target.SendMessage(targetFunc, this.GetJSON(www));
                }
            }
        }
    }
Exemplo n.º 5
0
    IEnumerator Post(string url, string bodyJsonString)
    {
        var request = new UnityWebRequest(url, "POST");

        byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
        request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");

        yield return(request.SendWebRequest());

        // JSONNode jsonData = JSON.Parse(Encoding.UTF8.GetString(request.downloadHandler.data));

        Debug.Log("Status Code: " + request.responseCode);
        Dictionary <string, string> asd = request.GetResponseHeaders();

        foreach (KeyValuePair <string, string> header in asd)
        {
            Debug.Log(header);
        }
    }
Exemplo n.º 6
0
    IEnumerator Post(string url, string bodyJsonString)
    {
        var request = new UnityWebRequest(url, "POST");

        byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
        request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");

        yield return(request.SendWebRequest());

        Debug.Log("Status Code: " + request.responseCode);
        StringBuilder sb = new StringBuilder();

        foreach (System.Collections.Generic.KeyValuePair <string, string> dict in request.GetResponseHeaders())
        {
            sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n");
        }

        // Print Headers
        Debug.Log(sb.ToString());
        // Print Body
        Debug.Log(request.downloadHandler.text.ToString());
        JSONObject json = new JSONObject(request.downloadHandler.text.ToString());

        if (request.responseCode == 200)
        {
            if (json["user"]["player_datas"][0]["id"] != null)
            {
                float id = json["user"]["player_datas"][0]["id"].n;
                Settings.userId = Convert.ToInt64(id);
                Debug.Log(Settings.userId);
                SceneManager.LoadScene("menuPrincipal", LoadSceneMode.Single);
            }
        }
        else
        {
            results.text = "Usuário ou senha incorretos";
        }
    }
Exemplo n.º 7
0
    public IEnumerator SendIndexInfo()
    {
        WWWForm form = new WWWForm();

        form.AddField("mail_tel", dict["nicoMailField"].GetComponent <InputField>().text);
        form.AddField("password", dict["nicoPasswordField"].GetComponent <InputField>().text);

        UnityWebRequest request = UnityWebRequest.Post("https://account.nicovideo.jp/api/v1/login", form);

        request.SetRequestHeader("User-Agent", "youtube-list@LNTakeshi");
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        yield return(request.SendWebRequest());

        var header = String.Join(",", request.GetResponseHeaders().Select(r => r.Key + ":" + r.Value));

        Debug.Log(request.error + "Set-Cookie:" + header + " form:" + System.Text.Encoding.UTF8.GetString(form.data));

        request = UnityWebRequest.Get("http://flapi.nicovideo.jp/api/getflv/sm9");
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        yield return(request.SendWebRequest());

        // header = String.Join(",", request.GetResponseHeaders().Select(r => r.Key + ":" + r.Value));

        // String threadId = null;
        // var param = GetParams(request.downloadHandler.text);
        // param.TryGetValue("thread_id", out threadId);
        // Debug.Log( request.error + " Set-Cookie:" + header +" body:" + request.downloadHandler.text + " thread_id:" + threadId +  " form:" + System.Text.Encoding.UTF8.GetString(form.data));


        PlayerPrefs.SetString("nicoMail", dict["nicoMailField"].GetComponent <InputField>().text);
        PlayerPrefs.SetString("nicoPassword", dict["nicoPasswordField"].GetComponent <InputField>().text);
        PlayerPrefs.Save();
        if (Int32.Parse(request.GetResponseHeader("x-niconico-authflag")) >= 1)
        {
            dict["YoutubeListPlayer"].GetComponent <YoutubeListPlay>().SetNicoCommentEnabled();
            dict["nicoMailField"].SetActive(false);
            dict["nicoPasswordField"].SetActive(false);
            dict["nicoSubmitButton"].SetActive(false);
        }
    }
Exemplo n.º 8
0
    IEnumerator isValid(string text)
    {
        TMP_InputField input   = gameObject.GetComponent <TMP_InputField>();
        var            request = new UnityWebRequest("http://3.232.32.88:5000/api/validate", "POST");

        byte[] bodyRaw = Encoding.UTF8.GetBytes("{\"api_key\":\"" + text + "\"}");
        request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        yield return(request.SendWebRequest());

        Debug.Log("Status Code: " + request.responseCode);

        StringBuilder sb = new StringBuilder();

        foreach (System.Collections.Generic.KeyValuePair <string, string> dict in request.GetResponseHeaders())
        {
            sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n");
        }

        if (request.downloadHandler.text.Contains("Success"))
        {
            show();
            API_key.text = text;
            DontDestroyOnLoad(API_key);
            invalid.gameObject.SetActive(false);
            hide();
        }
        else
        {
            input.text = "";
            StartCoroutine(InvalidMsg());
        }
        // Print Headers
        Debug.Log("HEADERS: " + sb.ToString());

        // Print Body
        Debug.Log("BODY: " + request.downloadHandler.text);
    }
Exemplo n.º 9
0
        /// <summary>
        /// Only retrieve the headers of the file.
        /// </summary>
        /// <param name="callback">Dictionary of headers.</param>
        public IEnumerator GetHeaders(Action <Dictionary <string, string> > callback)
        {
            var manager = Request.Instance;

            using (UnityWebRequest www = manager.Generate("contents/" + Id, UnityWebRequest.kHttpVerbHEAD))
            {
                yield return(www.Send());

                if (www.isError)
                {
                    Debug.LogError("Failed to Download File Headers: " + www.error);
                }
                else
                {
                    var headers = www.GetResponseHeaders();
                    Filename  = headers["Content-Disposition"].Split('"')[1];
                    Extension = Filename.Substring(Filename.LastIndexOf('.') + 1).ToLower();
                    SetReturnType();
                    callback(headers);
                }
            }
        }
Exemplo n.º 10
0
        public IEnumerator SendPost(string urlSuffix, string jsonData, Action <Dictionary <string, string>, string> callback, Action <string, string> errorCallback, string authToken = null)
        {
            using (UnityWebRequest request = UnityWebRequest.Post(urlPrefix + url + urlSuffix, jsonData))
            {
                //request.certificateHandler = new BypassCertificate();

                /*request.SetRequestHeader("Content-Type", "application/json");
                 * request.SetRequestHeader("Accept", "text/json");*/
                if (!string.IsNullOrEmpty(jsonData))
                {
                    request.uploadHandler             = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(jsonData));
                    request.uploadHandler.contentType = defaultContentType;
                }
                if (!string.IsNullOrEmpty(authToken))
                {
                    request.SetRequestHeader(AuthHeaderKey, BearerTokenPrefix + authToken);
                }
                yield return(request.SendWebRequest());

                if (request.isNetworkError)
                {
                    //Debug.LogError(request.error);
                    errorCallback?.Invoke(request.error, "");
                }
                if (request.isDone)
                {
                    Debug.Log("Form upload complete!");
                    string responseData = System.Text.Encoding.UTF8.GetString(request.downloadHandler.data);
                    if (request.responseCode != 200)
                    {
                        errorCallback?.Invoke(request.error, responseData);
                    }
                    else
                    {
                        callback?.Invoke(request.GetResponseHeaders(), responseData);
                    }
                }
            }
        }
Exemplo n.º 11
0
        private IEnumerator LoadTimeRoutine(int breakTime)
        {
            var request = new UnityWebRequest(SERVER_URL);

            request.downloadHandler = new DownloadHandlerBuffer();
            request.timeout         = breakTime;

            yield return(request.SendWebRequest());

            if (this.NotValidResponse(request))
            {
                yield break;
            }

            var      todaysDates    = request.GetResponseHeaders()["date"];
            DateTime downloadedTime = DateTime.ParseExact(todaysDates,
                                                          "ddd, dd MMM yyyy HH:mm:ss 'GMT'",
                                                          CultureInfo.InvariantCulture.DateTimeFormat,
                                                          DateTimeStyles.AdjustToUniversal);

            this.NotifyAboutDownloadedTime(downloadedTime, NO_ERROR, null, LOADED_FROM_INTERNET);
        }
Exemplo n.º 12
0
    public IEnumerator lcv(string username, string password, string ip, System.Action failure, System.Action success)
    {
        if (username == "" || password == "")
        {
            failure();
            yield break;
        }
        WWWForm form = new WWWForm();

        form.AddField("uid", username);
        form.AddField("pwd", password);
        UnityWebRequest request = UnityWebRequest.Post("https://web.spaggiari.eu/auth/app/default/AuthApi4.php?a=aLoginPwd", form);

        yield return(request.SendWebRequest());

        LoginRequest lr = (LoginRequest)JsonUtility.FromJson(request.downloadHandler.text, typeof(LoginRequest));

        if (lr.data.auth.loggedIn)
        {
            success();
            Debug.Log(lr.data.auth.accountInfo.nome);
            userdata = lr.data.auth.accountInfo;
            if (userdata.type == "S" || userdata.type == "G")
            {
                string session;
                request.GetResponseHeaders().TryGetValue("Set-Cookie", out session);
                request = UnityWebRequest.Get("https://web.spaggiari.eu/cvv/app/default/genitori_note.php?classe_id=&studente_id=4234239&ordine=materia&filtro=tutto");
                request.SetRequestHeader("Cookie", session);
                yield return(request.SendWebRequest());

                lr.data.auth.accountInfo.materie = parseMaterie(request.downloadHandler.text);
            }
            serverConnect(ip);
        }
        else
        {
            failure();
        }
    }
Exemplo n.º 13
0
        public static string AsJson(this UnityWebRequest request, int bodySize = 256)
        {
            var jsonObject = new Dictionary <string, object>();

            var code    = request.responseCode;
            var url     = request.url;
            var error   = request.error;
            var headers = request.GetResponseHeaders();
            var handler = request.downloadHandler;
            var body    = handler.AsStringBody(bodySize);

            if (0 != code)
            {
                jsonObject["code"] = code;
            }

            if (!string.IsNullOrEmpty(url))
            {
                jsonObject["url"] = url;
            }

            if (!string.IsNullOrEmpty(error))
            {
                jsonObject["error"] = error;
            }

            if (null != headers && 0 != headers.Count)
            {
                jsonObject["headers"] = headers;
            }

            if (!string.IsNullOrEmpty(body))
            {
                jsonObject["body"] = body;
            }

            return(Json.Serialize(jsonObject));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Post this instance.
        /// </summary>
        private IEnumerator Post()
        {
//			UnityWebRequest www = null;
            WWWForm form = null;

            if (fields != null)
            {
                form = new WWWForm();
                foreach (KeyValuePair <string, string> field in fields)
                {
                    form.AddField(field.Key, field.Value);
                }
            }

            WWW = UnityWebRequest.Post(url, form);

            if (headers != null)
            {
                foreach (KeyValuePair <string, string> header in headers)
                {
                    WWW.SetRequestHeader(header.Key, header.Value);
                }
            }

            WWW.Send();

            while (!WWW.isDone)
            {
                UpdateProgress(WWW.downloadProgress);
                yield return(null);
            }

            UpdateProgress(WWW.downloadProgress);

            Response res = new Response(this, url, ID, WWW.GetResponseHeaders(), WWW.responseCode);

            callback(res);
        }
Exemplo n.º 15
0
    private static async UniTask <string> GetTextAsync(UnityWebRequest req)
    {
        #if !UNITY_WEBGL || UNITY_EDITOR
        req.SetRequestHeader("Cookie", Cookie.Value);
        #endif

        var op = await req.SendWebRequest();

        if (op.error == "Cannot connect to destination host")
        {
            throw new IOException(op.error);
        }

        #if !UNITY_WEBGL || UNITY_EDITOR
        var responseHeaders = req.GetResponseHeaders();
        if (responseHeaders.ContainsKey("Set-Cookie") && responseHeaders["Set-Cookie"].StartsWith(COOKIE_NAME))
        {
            Cookie.OnNext(responseHeaders["Set-Cookie"]);
        }
        #endif

        return(op.downloadHandler.text);
    }
        public IEnumerator GetInternetTime()
        {
            using (UnityWebRequest webRequest = UnityWebRequest.Get("http://www.google.com"))
            {
                webRequest.timeout = 10;
                yield return(webRequest.SendWebRequest());

                if (webRequest.isNetworkError)
                {
                    internetTimeCached = DateTime.Now; //In case something goes wrong.
                }
                else
                {
                    internetTimeCached = DateTime.ParseExact(webRequest.GetResponseHeaders()["date"],
                                                             "ddd, dd MMM yyyy HH:mm:ss 'GMT'",
                                                             CultureInfo.InvariantCulture.DateTimeFormat,
                                                             DateTimeStyles.AssumeUniversal);
                }

                internetTimeCachedMoment = Time.realtimeSinceStartup;

                internetTimeCachedString = internetTimeCached.ToString();
            }
        }
    IEnumerator SendPostRequest(string data, string requestURL, Action <HTTPResponse> success, Action fail)
    {
        using (UnityWebRequest www = UnityWebRequest.Put(HTTPNetworkConstant.serverURL + requestURL, data))
        {
            www.method = "Post";
            www.SetRequestHeader("Content-Type", "application/json");

            string sid = PlayerPrefs.GetString("sid", "");
            if (sid != "")
            {
                www.SetRequestHeader("Set-Cookie", sid);
            }

            yield return(www.SendWebRequest());

            long code = www.responseCode;
            HTTPResponseMessage message = JsonUtility.FromJson <HTTPResponseMessage>(www.downloadHandler.text);

            if (www.isNetworkError)
            {
                NetworkErrorHandler();
                fail();
            }
            else if (www.isHttpError)
            {
                HTTPErrorHandler(code, message.message);
                fail();
            }
            else
            {
                Dictionary <string, string> headers = www.GetResponseHeaders();
                HTTPResponse response = new HTTPResponse(code, message.message, headers);
                success(response);
            }
        }
    }
Exemplo n.º 18
0
    //Ensure there is a connection to the db by querying a known user account
    //If connection cannot be established, stops the coroutine, sets to the "RESPONSE_RECEIVED" state and set response to null;
    IEnumerator CheckDbConnection()
    {
        WWWForm form = new WWWForm();

        form.AddField("username", knownUsername);
        form.AddField("password", knownPass);

        using (UnityWebRequest www = UnityWebRequest.Post(baseURL + "check_user.php", form)) {
            yield return(www.SendWebRequest());

            if (www.isNetworkError || www.isHttpError)
            {
                Debug.LogWarning("Cannot connect to the database: " + www.error);
                Debug.Log(www.downloadHandler.text);
                if (disregardNext)
                {
                    currentState = DbConnectionState.READY;
                    lastResponse = null;
                }
                else
                {
                    currentState = DbConnectionState.RESPONSE_RECEIVED;
                    lastResponse = new DbResponse(DbResponseState.NOCONNECTION, www.downloadHandler.text, www.GetResponseHeaders());
                }
                yield break;
            } //else {
              //Debug.Log("Database connection is available");
            //}
        }
    }
Exemplo n.º 19
0
    IEnumerator PostReplay0()
    {
        WWWForm form = new WWWForm();

        form.AddField("email", email);
        form.AddField("firstname", firstname);
        form.AddField("lastname", lastname);
        form.AddField("test", test);
        form.AddField("replays", replays);
        using (UnityWebRequest www = UnityWebRequest.Post(urlReplay, form))
        {
            yield return(www.SendWebRequest());

            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
            }
            else
            {
                string txt = "POST -------------------------------------\n";
                txt += "  email " + email + " ";
                txt += " firstname " + firstname;
                txt += " lastname " + lastname + " ";
                txt += " test " + test + " ";
                txt += " replays " + replays + " ";
                Debug.Log(txt + "\n");
                Debug.Log("POST replay successful!\n");
                StringBuilder sb = new StringBuilder();
                foreach (System.Collections.Generic.KeyValuePair <string, string> dict in www.GetResponseHeaders())
                {
                    sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n");
                }
                Debug.Log(sb + "\n");
                Debug.Log(www.downloadHandler.text + "\n");
            }
        }
    }
        private static IEnumerator HandleAgentRequest(SuperAgentRequest request)
        {
            var url = request.Url;

            if (request.Queries.Count > 0)
            {
                string queryStr = "?";

                foreach (var query in request.Queries)
                {
                    if (!string.IsNullOrEmpty(queryStr))
                    {
                        queryStr += "&";
                    }

                    queryStr += System.Uri.EscapeDataString(query.Key) + "=" + System.Uri.EscapeDataString(query.Value);
                }

                url += queryStr;
            }

            var unityWebRequest = new UnityWebRequest(url, request.Method);

            if (request.Payload != null && request.Payload.Length > 0)
            {
                unityWebRequest.uploadHandler = new UploadHandlerRaw(request.Payload);
            }

            foreach (var header in request.Headers)
            {
                unityWebRequest.SetRequestHeader(header.Key, header.Value);
            }

            unityWebRequest.downloadHandler = new DownloadHandlerBuffer();

            yield return(unityWebRequest.Send());

            if (unityWebRequest.isError)
            {
                request.Callback(new SyncNetworkException(unityWebRequest.error), null);
            }
            else
            {
                if (unityWebRequest.responseCode / 100 != 2)
                {
                    // parse code from unityWebRequest.downloadHandler.data;
                    ErrorResponseException err;
                    try
                    {
                        var errCode =
                            JsonUtility.FromJson <ServerErrorResponse>(
                                Encoding.UTF8.GetString(unityWebRequest.downloadHandler.data)).errorCode;
                        err = new ErrorResponseException(errCode, (HttpStatusCode)unityWebRequest.responseCode);
                    }
                    catch (Exception)
                    {
                        err = new ErrorResponseException("unknown_response",
                                                         (HttpStatusCode)unityWebRequest.responseCode);
                    }
                    request.Callback(err, null);
                }
                else
                {
                    request.Callback(null, new SuperAgentResponse
                    {
                        HttpStatusCode = (HttpStatusCode)unityWebRequest.responseCode,
                        Headers        = unityWebRequest.GetResponseHeaders(),
                        Body           = unityWebRequest.downloadHandler.data
                    });
                }
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// To attach a project an existing project, we must collect all orgs the current user is a member of.
        /// In addition the current user may be a guest of a specific project, in which case we must also look at
        /// all projects to find organizations.
        /// </summary>
        /// <param name="organizationField"></param>
        /// <param name="projectIdField"></param>
        void LoadReuseOrganizationField(PopupField <string> organizationField, PopupField <string> projectIdField = null)
        {
            ServicesConfiguration.instance.RequestCurrentUserApiUrl(currentUserApiUrl =>
            {
                var getOrganizationsRequest = new UnityWebRequest(currentUserApiUrl + "?include=orgs,projects",
                                                                  UnityWebRequest.kHttpVerbGET)
                {
                    downloadHandler = new DownloadHandlerBuffer()
                };
                getOrganizationsRequest.suppressErrorsToConsole = true;
                getOrganizationsRequest.SetRequestHeader("AUTHORIZATION", $"Bearer {UnityConnect.instance.GetUserInfo().accessToken}");
                var operation        = getOrganizationsRequest.SendWebRequest();
                operation.completed += op =>
                {
                    try
                    {
                        if (ServicesUtils.IsUnityWebRequestReadyForJsonExtract(getOrganizationsRequest))
                        {
                            var jsonParser = new JSONParser(getOrganizationsRequest.downloadHandler.text);
                            var json       = jsonParser.Parse();
                            try
                            {
                                m_OrgIdByName.Clear();
                                var sortedOrganizationNames = new List <string>();
                                foreach (var rawOrg in json.AsDict()[k_JsonOrgsNodeName].AsList())
                                {
                                    var org = rawOrg.AsDict();
                                    if (k_AnyRoleFilter.Contains(org[k_JsonRoleNodeName].AsString()))
                                    {
                                        sortedOrganizationNames.Add(org[k_JsonNameNodeName].AsString());
                                        m_OrgIdByName.Add(org[k_JsonNameNodeName].AsString(), org[k_JsonIdNodeName].AsString());
                                    }
                                }

                                foreach (var rawProject in json.AsDict()[k_JsonProjectsNodeName].AsList())
                                {
                                    var project = rawProject.AsDict();
                                    if (!project[k_JsonArchivedNodeName].AsBool() &&
                                        !sortedOrganizationNames.Contains(project[k_JsonOrgNameNodeName].AsString()))
                                    {
                                        sortedOrganizationNames.Add(project[k_JsonOrgNameNodeName].AsString());
                                        m_OrgIdByName.Add(project[k_JsonOrgNameNodeName].AsString(), project[k_JsonOrgIdNodeName].AsString());
                                    }
                                }

                                sortedOrganizationNames.Sort();
                                var popUpChoices = new List <string> {
                                    L10n.Tr(k_SelectOrganizationText)
                                };
                                organizationField.SetEnabled(true);
                                popUpChoices.AddRange(sortedOrganizationNames);
                                organizationField.choices = popUpChoices;
                                organizationField.SetValueWithoutNotify(organizationField.choices[0]);
                                if (projectIdField != null)
                                {
                                    projectIdField.choices = new List <string> {
                                        L10n.Tr(k_SelectProjectText)
                                    };
                                    projectIdField.SetValueWithoutNotify(L10n.Tr(k_SelectProjectText));
                                    projectIdField.SetEnabled(false);
                                }
                            }
                            catch (Exception ex)
                            {
                                if (exceptionCallback != null)
                                {
                                    exceptionCallback.Invoke(ex);
                                }
                                else
                                {
                                    //If there is no exception callback, we have to at least log it
                                    Debug.LogException(ex);
                                }
                            }
                        }
                        else
                        {
                            var ex = new UnityConnectWebRequestException(L10n.Tr(k_CouldNotObtainOrganizationsMessage))
                            {
                                error           = getOrganizationsRequest.error,
                                method          = getOrganizationsRequest.method,
                                timeout         = getOrganizationsRequest.timeout,
                                url             = getOrganizationsRequest.url,
                                responseHeaders = getOrganizationsRequest.GetResponseHeaders(),
                                responseCode    = getOrganizationsRequest.responseCode,
                                isHttpError     = (getOrganizationsRequest.result == UnityWebRequest.Result.ProtocolError),
                                isNetworkError  = (getOrganizationsRequest.result == UnityWebRequest.Result.ConnectionError),
                            };
                            if (exceptionCallback != null)
                            {
                                exceptionCallback.Invoke(ex);
                            }
                            else
                            {
                                //If there is no exception callback, we have to at least log it
                                Debug.LogException(ex);
                            }
                        }
                    }
                    finally
                    {
                        getOrganizationsRequest.Dispose();
                    }
                };
            });
        }
Exemplo n.º 22
0
        void LoadProjectField(string organizationName, PopupField <string> projectIdField)
        {
            ServicesConfiguration.instance.RequestOrganizationProjectsApiUrl(m_OrgIdByName[organizationName], organizationProjectsApiUrl =>
            {
                var getProjectsRequest = new UnityWebRequest(organizationProjectsApiUrl,
                                                             UnityWebRequest.kHttpVerbGET)
                {
                    downloadHandler = new DownloadHandlerBuffer()
                };
                getProjectsRequest.suppressErrorsToConsole = true;
                getProjectsRequest.SetRequestHeader("AUTHORIZATION", $"Bearer {UnityConnect.instance.GetUserInfo().accessToken}");
                var operation        = getProjectsRequest.SendWebRequest();
                operation.completed += op =>
                {
                    try
                    {
                        if (ServicesUtils.IsUnityWebRequestReadyForJsonExtract(getProjectsRequest))
                        {
                            var jsonParser = new JSONParser(getProjectsRequest.downloadHandler.text);
                            var json       = jsonParser.Parse();
                            try
                            {
                                m_ProjectInfoByName = new Dictionary <string, ProjectInfoData>();

                                var jsonProjects = json.AsDict()[k_JsonProjectsNodeName].AsList();
                                foreach (var jsonProject in jsonProjects)
                                {
                                    if (!jsonProject.AsDict()[k_JsonArchivedNodeName].AsBool())
                                    {
                                        var projectInfo = ExtractProjectInfoFromJson(jsonProject);
                                        m_ProjectInfoByName.Add(projectInfo.name, projectInfo);
                                    }
                                }

                                var projectNames = new List <string> {
                                    L10n.Tr(k_SelectProjectText)
                                };
                                var sortedProjectNames = new List <string>(m_ProjectInfoByName.Keys);
                                sortedProjectNames.Sort();
                                projectNames.AddRange(sortedProjectNames);
                                projectIdField.choices = projectNames;
                                projectIdField.SetEnabled(true);
                            }
                            catch (Exception ex)
                            {
                                if (exceptionCallback != null)
                                {
                                    exceptionCallback.Invoke(ex);
                                }
                                else
                                {
                                    //If there is no exception callback, we have to at least log it
                                    Debug.LogException(ex);
                                }
                            }
                        }
                        else
                        {
                            var ex = new UnityConnectWebRequestException(L10n.Tr(k_CouldNotObtainProjectMessage))
                            {
                                error           = getProjectsRequest.error,
                                method          = getProjectsRequest.method,
                                timeout         = getProjectsRequest.timeout,
                                url             = getProjectsRequest.url,
                                responseHeaders = getProjectsRequest.GetResponseHeaders(),
                                responseCode    = getProjectsRequest.responseCode,
                                isHttpError     = (getProjectsRequest.result == UnityWebRequest.Result.ProtocolError),
                                isNetworkError  = (getProjectsRequest.result == UnityWebRequest.Result.ConnectionError),
                            };
                            if (exceptionCallback != null)
                            {
                                exceptionCallback.Invoke(ex);
                            }
                            else
                            {
                                //If there is no exception callback, we have to at least log it
                                Debug.LogException(ex);
                            }
                        }
                    }
                    finally
                    {
                        getProjectsRequest.Dispose();
                    }
                };
            });
        }
Exemplo n.º 23
0
        void CreateOperationOnCompleted(AsyncOperation obj)
        {
            if (m_CurrentRequest == null)
            {
                //If we lost our m_CurrentRequest request reference, we can't risk doing anything.
                return;
            }

            if (ServicesUtils.IsUnityWebRequestReadyForJsonExtract(m_CurrentRequest))
            {
                var jsonParser = new JSONParser(m_CurrentRequest.downloadHandler.text);
                var json       = jsonParser.Parse();
                var abort      = false;
                try
                {
                    var projectInfo = ExtractProjectInfoFromJson(json);
                    try
                    {
                        ServicesRepository.DisableAllServices(shouldUpdateApiFlag: false);
                        //Only register before creation. Remove first in case it was already added.
                        //TODO: Review to avoid dependency on project refreshed
                        UnityConnect.instance.ProjectStateChanged -= OnProjectStateChangedAfterCreation;
                        UnityConnect.instance.ProjectStateChanged += OnProjectStateChangedAfterCreation;
                        BindProject(projectInfo);
                    }
                    catch (Exception ex)
                    {
                        if (exceptionCallback != null)
                        {
                            exceptionCallback.Invoke(ex);
                            abort = true;
                        }
                        else
                        {
                            //If there is no exception callback, we have to at least log it
                            Debug.LogException(ex);
                        }
                    }
                    if (!abort)
                    {
                        createButtonCallback?.Invoke(projectInfo);
                    }
                }
                finally
                {
                    m_CurrentRequest?.Dispose();
                    m_CurrentRequest = null;
                }
            }
            else if (m_CurrentRequest.responseCode == k_HttpStatusCodeUnprocessableEntity)
            {
                m_CurrentRequest?.Dispose();
                m_CurrentRequest = null;
                m_CreateIteration++;
                RequestCreateOperation();
            }
            else
            {
                try
                {
                    var ex = new UnityConnectWebRequestException(L10n.Tr(k_CouldNotCreateProjectMessage))
                    {
                        error           = m_CurrentRequest.error,
                        method          = m_CurrentRequest.method,
                        timeout         = m_CurrentRequest.timeout,
                        url             = m_CurrentRequest.url,
                        responseHeaders = m_CurrentRequest.GetResponseHeaders(),
                        responseCode    = m_CurrentRequest.responseCode,
                        isHttpError     = (m_CurrentRequest.result == UnityWebRequest.Result.ProtocolError),
                        isNetworkError  = (m_CurrentRequest.result == UnityWebRequest.Result.ConnectionError),
                    };
                    if (exceptionCallback != null)
                    {
                        exceptionCallback.Invoke(ex);
                    }
                    else
                    {
                        //If there is no exception callback, we have to at least log it
                        Debug.LogException(ex);
                    }
                }
                finally
                {
                    m_CurrentRequest?.Dispose();
                    m_CurrentRequest = null;
                }
            }
        }
Exemplo n.º 24
0
        public static Response FromWebResponse(IAsyncRequest request, UnityWebRequest apiResponse, Exception apiEx)
        {
            Response response = new Response();

            response.Request = request;

            if (null != apiEx)
            {
                response.AddException(apiEx);
            }

            if (apiResponse.isNetworkError)
            {
                response.AddException(new Exception(apiResponse.error));
            }

            if (null == apiResponse.downloadHandler.data)
            {
                response.AddException(new Exception("Response has no data."));
            }

#if NETFX_CORE
            StringComparison stringComp = StringComparison.OrdinalIgnoreCase;
#elif WINDOWS_UWP
            StringComparison stringComp = StringComparison.OrdinalIgnoreCase;
#else
            StringComparison stringComp = StringComparison.InvariantCultureIgnoreCase;
#endif

            Dictionary <string, string> apiHeaders = apiResponse.GetResponseHeaders();
            if (null != apiHeaders)
            {
                response.Headers = new Dictionary <string, string>();
                foreach (var apiHdr in apiHeaders)
                {
                    string key = apiHdr.Key;
                    string val = apiHdr.Value;
                    response.Headers.Add(key, val);
                    if (key.Equals("X-Rate-Limit-Interval", stringComp))
                    {
                        int limitInterval;
                        if (int.TryParse(val, out limitInterval))
                        {
                            response.XRateLimitInterval = limitInterval;
                        }
                    }
                    else if (key.Equals("X-Rate-Limit-Limit", stringComp))
                    {
                        long limitLimit;
                        if (long.TryParse(val, out limitLimit))
                        {
                            response.XRateLimitLimit = limitLimit;
                        }
                    }
                    else if (key.Equals("X-Rate-Limit-Reset", stringComp))
                    {
                        double unixTimestamp;
                        if (double.TryParse(val, out unixTimestamp))
                        {
                            response.XRateLimitReset = UnixTimestampUtils.From(unixTimestamp);
                        }
                    }
                    else if (key.Equals("Content-Type", stringComp))
                    {
                        response.ContentType = val;
                    }
                }
            }

            int statusCode = (int)apiResponse.responseCode;
            response.StatusCode = statusCode;

            if (statusCode != 200)
            {
                response.AddException(new Exception(string.Format("Status Code {0}", apiResponse.responseCode)));
            }
            if (429 == statusCode)
            {
                response.AddException(new Exception("Rate limit hit"));
            }

            response.Data = apiResponse.downloadHandler.data;

            return(response);
        }
Exemplo n.º 25
0
        private static async Task <Response> ProcessRequestAsync(UnityWebRequest webRequest, int timeout, Dictionary <string, string> headers = null, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true)
        {
            if (timeout > 0)
            {
                webRequest.timeout = timeout;
            }

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    webRequest.SetRequestHeader(header.Key, header.Value);
                }
            }

            // HACK: Workaround for extra quotes around boundary.
            if (webRequest.method == UnityWebRequest.kHttpVerbPOST ||
                webRequest.method == UnityWebRequest.kHttpVerbPUT)
            {
                string contentType = webRequest.GetRequestHeader("Content-Type");
                if (contentType != null)
                {
                    contentType = contentType.Replace("\"", "");
                    webRequest.SetRequestHeader("Content-Type", contentType);
                }
            }

            webRequest.certificateHandler = certificateHandler;
            webRequest.disposeCertificateHandlerOnDispose = disposeCertificateHandlerOnDispose;
            await webRequest.SendWebRequest();

            long          responseCode = webRequest.responseCode;
            Func <byte[]> downloadHandlerDataAction = () => webRequest.downloadHandler?.data;

#if UNITY_2020_1_OR_NEWER
            if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
#else
            if (webRequest.isNetworkError || webRequest.isHttpError)
#endif // UNITY_2020_1_OR_NEWER
            {
                if (responseCode == 401)
                {
                    return(new Response(false, "Invalid Credentials", null, responseCode));
                }

                if (webRequest.GetResponseHeaders() == null)
                {
                    return(new Response(false, "Device Unavailable", null, responseCode));
                }

                string responseHeaders     = webRequest.GetResponseHeaders().Aggregate(string.Empty, (current, header) => $"\n{header.Key}: {header.Value}");
                string downloadHandlerText = await ResponseUtils.BytesToString(downloadHandlerDataAction.Invoke());

                Debug.LogError($"REST Error: {responseCode}\n{downloadHandlerText}{responseHeaders}");
                return(new Response(false, $"{responseHeaders}\n{downloadHandlerText}", downloadHandlerDataAction.Invoke(), responseCode));
            }
            if (readResponseData)
            {
                return(new Response(true, await ResponseUtils.BytesToString(downloadHandlerDataAction.Invoke()), downloadHandlerDataAction.Invoke(), responseCode));
            }
            else // This option can be used only if action will be triggered in the same scope as the webrequest
            {
                return(new Response(true, downloadHandlerDataAction, responseCode));
            }
        }
Exemplo n.º 26
0
    IEnumerator uploadimage(string ufile, byte[] ubytes)
    {
        List <IMultipartFormSection> formData = new List <IMultipartFormSection>();
        var form = new WWWForm();

        form.AddField("frameCount", Time.frameCount.ToString());
        form.AddBinaryData("file", ubytes, ufile, "image/png");
        formData.Add(new MultipartFormFileSection("file_name", ufile));

        UnityWebRequest www = UnityWebRequest.Post("https://emotron.herokuapp.com/pictureapi", form);

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log("Form upload complete!");
            StringBuilder sb = new StringBuilder();
            foreach (System.Collections.Generic.KeyValuePair <string, string> dict in www.GetResponseHeaders())
            {
                sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n");
            }

            // Print Headers
            //Debug.Log(sb.ToString());


            // Print Body

            string[] lst        = www.downloadHandler.text.Split('"');
            string   prediction = lst[0];
            expression = prediction;
            Debug.Log(prediction);
        }
    }
Exemplo n.º 27
0
    IEnumerator Upload(string ufile, byte[] ubytes)
    {
        //Debug.Log(ufile);
        List <IMultipartFormSection> formData = new List <IMultipartFormSection>();
        WWWForm form = new WWWForm();

        form.AddBinaryData("file_name", ubytes, "myfile.wav", "audio/vnd.wav");
        // formData.Add(new MultipartFormDataSection());
        formData.Add(new MultipartFormFileSection("file_name", ufile));

        UnityWebRequest www = UnityWebRequest.Post("http://localhost:3000/pred", form);

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log("Form upload complete!");
            StringBuilder sb = new StringBuilder();
            foreach (System.Collections.Generic.KeyValuePair <string, string> dict in www.GetResponseHeaders())
            {
                sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n");
            }

            // Print Headers
            //Debug.Log(sb.ToString());


            // Print Body

            string[] lst        = www.downloadHandler.text.Split('"');
            string   prediction = lst[1];
            emotion = prediction;
            Debug.Log(prediction);
            // emot.text(prediction);
        }
    }
Exemplo n.º 28
0
        void InitializeCoppaManager(VisualElement rootVisualElement)
        {
            rootVisualElement.AddStyleSheetPath(k_CoppaCommonStyleSheetPath);
            rootVisualElement.AddStyleSheetPath(EditorGUIUtility.isProSkin ? k_CoppaDarkStyleSheetPath : k_CoppaLightStyleSheetPath);
            var coppaTemplate = EditorGUIUtility.Load(k_CoppaTemplatePath) as VisualTreeAsset;

            rootVisualElement.Add(coppaTemplate.CloneTree().contentContainer);
            m_CoppaContainer = rootVisualElement.Q(coppaContainerName);
            var persistContainer = m_CoppaContainer.Q(k_PersistContainerName);
            var coppaField       = BuildPopupField(m_CoppaContainer, k_CoppaFieldName);

            //Setup dashboard link
            var learnMoreClickable = new Clickable(() =>
            {
                Application.OpenURL(k_CoppaLearnMoreUrl);
            });

            m_CoppaContainer.Q(k_CoppaLearnLinkBtnName).AddManipulator(learnMoreClickable);

            var originalCoppaValue = UnityConnect.instance.GetProjectInfo().COPPA;
            var coppaChoicesList   = new List <String>()
            {
                L10n.Tr(k_No), L10n.Tr(k_Yes)
            };

            if (originalCoppaValue == COPPACompliance.COPPAUndefined)
            {
                coppaChoicesList.Insert(0, L10n.Tr(k_Undefined));
            }
            coppaField.choices = coppaChoicesList;
            SetCoppaFieldValue(originalCoppaValue, coppaField);

            persistContainer.Q <Button>(k_SaveBtnName).clicked += () =>
            {
                try
                {
                    ServicesConfiguration.instance.RequestCurrentProjectCoppaApiUrl(projectCoppaApiUrl =>
                    {
                        var payload            = $"{{\"coppa\":\"{GetCompliancyJsonValueFromFieldValue(coppaField)}\"}}";
                        var uploadHandler      = new UploadHandlerRaw(Encoding.UTF8.GetBytes(payload));
                        var currentSaveRequest = new UnityWebRequest(projectCoppaApiUrl, UnityWebRequest.kHttpVerbPUT)
                        {
                            uploadHandler = uploadHandler
                        };
                        currentSaveRequest.suppressErrorsToConsole = true;
                        currentSaveRequest.SetRequestHeader("AUTHORIZATION", $"Bearer {UnityConnect.instance.GetUserInfo().accessToken}");
                        currentSaveRequest.SetRequestHeader("Content-Type", "application/json;charset=UTF-8");
                        var operation = currentSaveRequest.SendWebRequest();
                        SetEnabledCoppaControls(coppaContainer, false);
                        operation.completed += asyncOperation =>
                        {
                            try
                            {
                                if (currentSaveRequest.responseCode == k_HttpStatusNoContent)
                                {
                                    try
                                    {
                                        var newCompliancyValue = GetCompliancyForFieldValue(coppaField);
                                        if (!UnityConnect.instance.SetCOPPACompliance(newCompliancyValue))
                                        {
                                            EditorAnalytics.SendCoppaComplianceEvent(new CoppaState()
                                            {
                                                isCompliant = newCompliancyValue == COPPACompliance.COPPACompliant
                                            });

                                            SetCoppaFieldValue(originalCoppaValue, coppaField);
                                            SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
                                            exceptionCallback?.Invoke(originalCoppaValue, new CoppaComplianceEditorConfigurationException(k_CoppaComplianceEditorConfigurationExceptionMessage));
                                        }
                                        else
                                        {
                                            originalCoppaValue = newCompliancyValue;
                                            SetCoppaFieldValue(originalCoppaValue, coppaField);
                                            SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
                                            NotificationManager.instance.Publish(Notification.Topic.CoppaCompliance, Notification.Severity.Info,
                                                                                 L10n.Tr(CoppaComplianceChangedMessage));
                                            saveButtonCallback?.Invoke(originalCoppaValue);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        SetCoppaFieldValue(originalCoppaValue, coppaField);
                                        SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
                                        exceptionCallback?.Invoke(originalCoppaValue, new CoppaComplianceEditorConfigurationException(k_CoppaComplianceEditorConfigurationExceptionMessage, ex));
                                    }
                                    finally
                                    {
                                        currentSaveRequest.Dispose();
                                        currentSaveRequest = null;
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        SetCoppaFieldValue(originalCoppaValue, coppaField);
                                        SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
                                        exceptionCallback?.Invoke(originalCoppaValue, new CoppaComplianceWebConfigurationException(L10n.Tr(k_CoppaUnexpectedSaveRequestBehaviorMessage))
                                        {
                                            error           = currentSaveRequest.error,
                                            method          = currentSaveRequest.method,
                                            timeout         = currentSaveRequest.timeout,
                                            url             = currentSaveRequest.url,
                                            responseHeaders = currentSaveRequest.GetResponseHeaders(),
                                            responseCode    = currentSaveRequest.responseCode,
                                            isHttpError     = (currentSaveRequest.result == UnityWebRequest.Result.ProtocolError),
                                            isNetworkError  = (currentSaveRequest.result == UnityWebRequest.Result.ConnectionError),
                                        });
                                    }
                                    finally
                                    {
                                        currentSaveRequest.Dispose();
                                        currentSaveRequest = null;
                                    }
                                }
                            }
                            finally
                            {
                                SetEnabledCoppaControls(coppaContainer, true);
                            }
                        };
                    });
                }
                catch (Exception ex)
                {
                    SetCoppaFieldValue(originalCoppaValue, coppaField);
                    SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
                    exceptionCallback?.Invoke(originalCoppaValue, ex);
                }
            };

            persistContainer.Q <Button>(k_CancelBtnName).clicked += () =>
            {
                SetCoppaFieldValue(originalCoppaValue, coppaField);
                SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
                cancelButtonCallback?.Invoke(originalCoppaValue);
            };

            persistContainer.style.display = DisplayStyle.None;
            coppaField.RegisterValueChangedCallback(evt =>
            {
                SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
            });
        }
Exemplo n.º 29
0
        System.Collections.IEnumerator WaitForExitpollResponse(UnityWebRequest www, string hookname, Response callback, float timeout)
        {
            float time = 0;

            while (time < timeout)
            {
                yield return(null);

                if (www.isDone)
                {
                    break;
                }
                time += Time.deltaTime;
            }

            var headers      = www.GetResponseHeaders();
            int responsecode = (int)www.responseCode;

            lastDataResponse = responsecode;
            //check cvr header to make sure not blocked by capture portal

            if (!www.isDone)
            {
                Util.logWarning("Network::WaitForExitpollResponse timeout");
            }
            if (responsecode != 200)
            {
                Util.logWarning("Network::WaitForExitpollResponse responsecode is " + responsecode);
            }

            if (headers != null)
            {
                if (!headers.ContainsKey("cvr-request-time"))
                {
                    Util.logWarning("Network::WaitForExitpollResponse does not contain cvr-request-time header");
                }
            }

            if (!www.isDone || responsecode != 200 || (headers != null && !headers.ContainsKey("cvr-request-time")))
            {
                if (LocalCache.LocalStorageActive)
                {
                    string text;
                    if (LocalCache.GetExitpoll(hookname, out text))
                    {
                        if (callback != null)
                        {
                            callback.Invoke(responsecode, "", text);
                        }
                    }
                    else
                    {
                        if (callback != null)
                        {
                            callback.Invoke(responsecode, "", "");
                        }
                    }
                }
                else
                {
                    if (callback != null)
                    {
                        callback.Invoke(responsecode, "", "");
                    }
                }
            }
            else
            {
                if (callback != null)
                {
                    callback.Invoke(responsecode, www.error, www.downloadHandler.text);
                }
                if (LocalCache.LocalStorageActive)
                {
                    LocalCache.WriteExitpoll(hookname, www.downloadHandler.text);
                }
            }
            www.Dispose();
            activeRequests.Remove(www);
        }
Exemplo n.º 30
0
    //Try create a new user in the DB
    //When called, sets to the AWAITING_RESPONSE state
    //Once a response is received, changes to RESPONSE_RECEIVED
    //Sets response based on
    // 200 & "ok" - SUCCESS (user created)
    // 200 & "username" - username already exists in db
    // 200 & "email" - email already exists in db
    // 200 & "pass" - passwords did not match
    // 404 - NOTFOUND (malformed post request)
    // ?   - OTHER (something else)
    IEnumerator CreateNewUser(string username, string name, string email, string password1, string password2)
    {
        Debug.Log("Checking user credentials are valid");

        if (currentState != DbConnectionState.READY)
        {
            Debug.LogWarning("Tried to connect to the DB before receiving response, will not process this request");
            yield break;
        }

        currentState = DbConnectionState.AWAITING_RESPONSE;
        yield return(StartCoroutine(CheckDbConnection()));

        if (currentState != DbConnectionState.AWAITING_RESPONSE)
        {
            yield break;
        }

        WWWForm form = new WWWForm();

        form.AddField("username", username);
        form.AddField("name", name);
        form.AddField("password1", password1);
        form.AddField("password2", password2);
        form.AddField("email", email);

        using (UnityWebRequest www = UnityWebRequest.Post(baseURL + "create_new_user.php", form)) {
            yield return(www.SendWebRequest());

            DbResponseState state;

            string responseText = www.downloadHandler.text;

            if (www.responseCode == 200)
            {
                if (responseText.ToLower().Equals("username"))
                {
                    state = DbResponseState.USERNAME_EXISTS;
                }
                else if (responseText.ToLower().Equals("email"))
                {
                    state = DbResponseState.EMAIL_EXISTS;
                }
                else if (responseText.ToLower().Equals("pass"))
                {
                    state = DbResponseState.PASSWORDS_DONT_MATCH;
                }
                else if (responseText.ToLower().Equals("ok"))
                {
                    state = DbResponseState.SUCCESS;
                }
                else
                {
                    Debug.Log("Unexpected HTTP message when adding new user: "******"Unexpected response when trying to save scores: " + www.error);
                Debug.Log(www.downloadHandler.text);
                state = DbResponseState.OTHER;
            }

            if (disregardNext)
            {
                currentState = DbConnectionState.READY;
                lastResponse = null;
            }
            else
            {
                currentState = DbConnectionState.RESPONSE_RECEIVED;
                lastResponse = new DbResponse(state, www.downloadHandler.text, www.GetResponseHeaders());
            }
        }
    }