예제 #1
0
    // 字符串/二进制数据
    private IEnumerator DownLoadTxt(string url)
    {
        UnityWebRequest request = UnityWebRequest.Get(url);// 文字、二进制数据

        yield return(request.SendWebRequest());

        if (request.isNetworkError || request.isHttpError)
        {
            Debug.Log(request.error);
            Debug.Log("certificateHandler " + request.certificateHandler);
        }
        else
        {
            Debug.Log("certificateHandler " + request.certificateHandler);
            /* 一般 */
            // 字符串
            string txt1 = DownloadHandlerBuffer.GetContent(request);
            // 一般用于获取原始数据
            byte[] bytes = request.downloadHandler.data;
            /* 具体 */
            DownloadHandlerBuffer buffer = (DownloadHandlerBuffer)request.downloadHandler;
            string txt2   = buffer.text;
            byte[] bytes2 = buffer.data;
            txt.text = txt1;
        }
        request.Dispose();
    }
예제 #2
0
    private IEnumerator IEDownloadFile(string url, int Index, System.Action <object, bool, string> OverFun, bool IsInsert)
    {
        if (url != null && !ListidleUrl.Contains(url))
        {
            if (IsInsert)
            {
                ListidleUrl.Insert(0, url);
            }
            else
            {
                ListidleUrl.Add(url);
            }
        }
        while (!ListDownloadIng.Contains(url))
        {
            yield return(0);
        }
        object          obj        = null;
        UnityWebRequest WebRequest = UnityWebRequest.Get(url);

        WebRequest.timeout = TimeOut;
        yield return(WebRequest.Send());

        if (WebRequest.isError)
        {
            if (OverFun != null)
            {
                OverFun(obj, true, WebRequest.error);
            }
            yield break;
        }
        switch (Index)
        {
        case 1:
            obj = WebRequest.downloadHandler.data;
            break;

        case 2:
            obj = DownloadHandlerAssetBundle.GetContent(WebRequest);
            break;

        case 3:
            obj = DownloadHandlerBuffer.GetContent(WebRequest);
            break;

        case 4:
            obj = DownloadHandlerAudioClip.GetContent(WebRequest);
            break;

        case 5:
            obj = DownloadHandlerTexture.GetContent(WebRequest);
            break;
        }
        WebRequest.Dispose();
        ListDownloadIng.Remove(url);
        if (OverFun != null)
        {
            OverFun(obj, false, null);
        }
    }
예제 #3
0
    private IEnumerator UnityLoadText(string url, string str, Text text)
    {
        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            yield return(request.SendWebRequest());

            if (request.isHttpError || request.isNetworkError)
            {
                Debug.LogError(request.error);
            }
            else
            {
                if (request.isDone)
                {
                    print(str + "      " + url + "    ");
                    string result = DownloadHandlerBuffer.GetContent(request);
                    if (string.IsNullOrEmpty(result))
                    {
                        Debug.LogError("null");
                    }
                    else
                    {
                        text.text = result;
                    }
                }
            }
        }
    }
예제 #4
0
        public override void initState()
        {
            base.initState();
            ObservableUtil.currentPath.OnChanged += OnPathChanged;
            _currentPath      = ObservableUtil.currentPath.value;
            _controller       = new ScrollController();
            _overwriteUnknown = false;
            _version          = null;
            var url =
                $"{Configuration.Instance.apiHost}/api/documentation/parse_version/v/2018.1";
            var request        = UnityWebRequest.Get(url);
            var asyncOperation = request.SendWebRequest();

            asyncOperation.completed += operation =>
            {
                if (!mounted)
                {
                    return;
                }

                using (WindowProvider.of(context).getScope())
                {
                    var content = DownloadHandlerBuffer.GetContent(request);
                    var model   = Version.FromJson(JsonValue.Parse(content));
                    setState(() => _version = model);
                }
            };
        }
예제 #5
0
        public static IPromise <T> PostForm <T>(
            string url,
            List <IMultipartFormSection> formSections,
            out Func <float> progress)
        {
            var session = Window.loginSession;
            var request = UnityWebRequest.Post(
                $"https://connect.unity.com{url}",
                formSections
                );

            request.SetRequestHeader("X-Requested-With", "XMLHTTPREQUEST");
            if (session != null && session.isNotEmpty())
            {
                request.SetRequestHeader("Cookie", $"LS={session};");
            }
            progress = () => request.uploadProgress;

            return(new Promise <T>(isSync: true, resolver: (resolve, reject) =>
            {
                request.SendWebRequest().completed += operation =>
                {
                    var content = DownloadHandlerBuffer.GetContent(request);
                    var fromProc = typeof(T).GetMethod("FromJson");
                    var response = (T)fromProc.Invoke(null, new object[] { JsonValue.Parse(content) });
                    resolve(response);
                };
            }));
        }
예제 #6
0
    IEnumerator GetWebRequest(string url)
    {
        UWebResponse <string> response;
//		using(var request = CreateGetRequest(url))
//		{
//			//request send
//			yield return request.Send();
//			//Web Response
//			response = new UWebResponse(request.responseCode,
//				request.downloadHandler.data, request.error);
        //
//		}
        //
        var req = CreateGetRequest(url);

        yield return(req.Send());

        //Web Response

//		response = new UWebResponse(req.responseCode,
//			req.downloadHandler.data, req.error);
        //
        if (req.isError)
        {
            //Handle error
            Debug.Log(string.Format("request {0} error {1}", url, req.error));
            yield break;
        }
        //
        string strResponse = DownloadHandlerBuffer.GetContent(req);        //response.ToString();

        Debug.LogFormat("Web request {0} succes.\nResponse: {1}", url, strResponse);
        //show response to TextUI
        this.textResponse.text = strResponse;
    }
예제 #7
0
        public static IPromise <T> Post <T>(
            string url,
            string data)
        {
            return(new Promise <T>(isSync: true, resolver: (resolve, reject) =>
            {
                var session = Window.loginSession;
                var request = new UnityWebRequest(
                    $"https://connect.unity.com{url}",
                    UnityWebRequest.kHttpVerbPOST
                    )
                {
                    downloadHandler = new DownloadHandlerBuffer(),
                };
                if (data != null)
                {
                    request.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(data));
                }
                request.SetRequestHeader("X-Requested-With", "XMLHTTPREQUEST");
                request.SetRequestHeader("Content-Type", "application/json");
                if (session != null && session.isNotEmpty())
                {
                    request.SetRequestHeader("Cookie", $"LS={session};");
                }

                request.SendWebRequest().completed += operation =>
                {
                    var content = DownloadHandlerBuffer.GetContent(request);
                    var fromProc = typeof(T).GetMethod("FromJson");
                    var response = (T)fromProc.Invoke(null, new object[] { JsonValue.Parse(content) });
                    resolve(response);
                };
            }));
        }
예제 #8
0
    public IEnumerator DeleteAudioClip(string fileName)
    {
        Debug.Log("Deleting an audio clip: " + fileName);
        UnityWebRequest www = UnityWebRequest.Delete("http://" + m_serverIP + ":" + m_serverPort + "?fn=" + fileName);

        www.downloadHandler = new DownloadHandlerBuffer();
        yield return(www.Send());

        if (www.isNetworkError)
        {
            Debug.Log(www.error);
        }
        else
        {
            string result = DownloadHandlerBuffer.GetContent(www);
            if (result == null)
            {
                Debug.Log("Deletion confirmation is null");
            }
            else
            {
                Debug.Log(result.ToString());
            }
        }
    }
예제 #9
0
            private void Load()
            {
                _loading    = true;
                _imageMetas = new Dictionary <string, ImageMeta>();
                var version = DocApp.of(context).version;
                var url     =
                    $"{Configuration.Instance.cdnPrefix}/{version.unityVersion}/{version.parsedVersion}/scripting/json/{widget._title.Replace('-', '_')}.json";
                var request        = UnityWebRequest.Get(url);
                var asyncOperation = request.SendWebRequest();

                asyncOperation.completed += operation =>
                {
                    if (!mounted)
                    {
                        return;
                    }

                    using (WindowProvider.of(context).getScope())
                    {
                        var content   = DownloadHandlerBuffer.GetContent(request);
                        var scripting = JsonConvert.DeserializeObject <Models.Json.Scripting>(content);
                        setState(() =>
                        {
                            _scripting  = scripting;
                            _loading    = false;
                            _imageMetas = scripting.imageMetas?.ToDictionary(
                                meta => meta.name,
                                meta => meta);
                        });
                    }
                };
            }
예제 #10
0
        private void FinishDownload()
        {
            if (m_webrequest == null)
            {
                error = string.Format("webrequest is null ,key={0},url={1} ", cRequest.key, cRequest.url);
                return;
            }
            cRequest.responseHeaders = m_webrequest.GetResponseHeaders();
#if UNITY_2017
            if (m_webrequest.isNetworkError)
#else
            if (m_webrequest.isError)
#endif
            {
                error = string.Format("url:{0},erro:{1}", cRequest.url, m_webrequest.error);
                Debug.LogWarning(error);
                return;
            }

            if (!(m_webrequest.responseCode == 200 || m_webrequest.responseCode == 0))
            {
                error = string.Format("response error code = {0},url={1}", m_webrequest.responseCode, cRequest.url);  // m_webrequest.error;
                Debug.LogWarning(error);
                return;
            }

            var type = cRequest.assetType;
            if (CacheManager.Typeof_AudioClip.Equals(type))
            {
                m_Data = DownloadHandlerAudioClip.GetContent(m_webrequest);
            }
            else if (CacheManager.Typeof_Texture2D.Equals(type))
            {
                m_Data = DownloadHandlerTexture.GetContent(m_webrequest);
            }
            else if (CacheManager.Typeof_Bytes.Equals(type))
            {
                m_Data = m_webrequest.downloadHandler.data;
            }
            else if (CacheManager.Typeof_AssetBundle.Equals(type))
            {
                m_Data = DownloadHandlerAssetBundle.GetContent(m_webrequest);
            }
            else
            {
                m_Data = DownloadHandlerBuffer.GetContent(m_webrequest);
            }

            if (!CacheManager.Typeof_AssetBundle.Equals(type))
            {
                UriGroup.CheckWWWComplete(cRequest, m_webrequest);
            }

            cRequest.data = m_Data;
            m_webrequest.Dispose();
            m_webrequest     = null;
            m_asyncOperation = null;
        }
예제 #11
0
        public IEnumerator CollectDownloadFile()
        {
            UnityWebRequest request = UnityWebRequest.Get(GetVersionFileUrl(LoaderSpace.Streaming));

            yield return(request.SendWebRequest());

            string versionText = DownloadHandlerBuffer.GetContent(request);

            streamingVersion = GetAssetBundleVersion(versionText, LoaderSpace.Streaming);

            print(Application.persistentDataPath);
            print(GetVersionFileUrl(LoaderSpace.Persistent));
            request = UnityWebRequest.Get(GetVersionFileUrl(LoaderSpace.Persistent));
            yield return(request.SendWebRequest());

            print(request.error);
            if (string.IsNullOrEmpty(request.error))
            {
                versionText = DownloadHandlerBuffer.GetContent(request);
                print(versionText);
                persistentVersion = GetAssetBundleVersion(versionText, LoaderSpace.Persistent);
            }

            AssetBundleManager.SetDevelopmentAssetBundleServer();

            request = UnityWebRequest.Get(GetVersionFileUrl(LoaderSpace.Server));
            print(GetVersionFileUrl(LoaderSpace.Server));
            yield return(request.SendWebRequest());

            versionText   = DownloadHandlerBuffer.GetContent(request);
            serverVersion = GetAssetBundleVersion(versionText, LoaderSpace.Server);

            DownloadTotalSize = 0;
            foreach (var item in serverVersion)
            {
                if (persistentVersion.ContainsKey(item.Key))
                {
                    if (!string.Equals(item.Value.hash, persistentVersion[item.Key].hash))
                    {
                        DownloadTotalSize += item.Value.size;
                        mDownloadAssetBundleVersion.Add(item.Value);
                    }
                }
                else
                {
                    AssetBundleVersion streamInfo = null;
                    streamingVersion.TryGetValue(item.Key, out streamInfo);
                    if (streamInfo == null || !string.Equals(item.Value.hash, streamInfo.hash))
                    {
                        DownloadTotalSize += item.Value.size;
                        mDownloadAssetBundleVersion.Add(item.Value);
                    }
                }
            }
        }
예제 #12
0
파일: WebRequest.cs 프로젝트: PcloD/TEDCore
        private void OnDataLoaded()
        {
            TEDDebug.LogFormat("[WebRequest] OnDataLoaded - requst id = {0}, url = {1}, data = {2}", m_requestId, m_request.url, DownloadHandlerBuffer.GetContent(m_request));

            if (null == m_onDataCallback)
            {
                return;
            }

            m_onDataCallback.Invoke(m_requestId, DownloadHandlerBuffer.GetContent(m_request), m_userData);
        }
        public static IEnumerator GetTwitchChannelBadges()
        {
            while (Plugin.TwitchChannelID == string.Empty)
            {
                yield return(null);
            }
            Plugin.Log($"Downloading twitch channel badge listing");
            using (var web = UnityWebRequest.Get($"https://badges.twitch.tv/v1/badges/channels/{Plugin.TwitchChannelID}/display")) {
                yield return(web.SendWebRequest());

                if (web.isNetworkError || web.isHttpError)
                {
                    Plugin.Log($"An error occured when requesting twitch channel badge listing, Message: \"{web.error}\"");
                }
                else
                {
                    var json = DownloadHandlerBuffer.GetContent(web);

                    if (json.Count() > 0)
                    {
                        var j = SimpleJSON.JSON.Parse(json);
                        if (j["badge_sets"]["subscriber"].IsObject)
                        {
                            var    cur  = j["badge_sets"]["subscriber"]["versions"].AsObject;
                            string name = "subscriber";

                            foreach (KeyValuePair <string, SimpleJSON.JSONNode> version in cur)
                            {
                                string versionID     = version.Key;
                                var    versionObject = version.Value.AsObject;
                                string url           = versionObject["image_url_4x"];
                                string index         = url.Substring(url.IndexOf("/v1/") + 4).Replace("/3", "");
                                string finalName     = $"{name}{versionID}";

                                while (!TwitchBadgeIDs.TryAdd(finalName, index))
                                {
                                    // Overwrite the affiliate sub badges if the channel has any custom ones
                                    if (TwitchBadgeIDs.TryGetValue(finalName, out var existing))
                                    {
                                        TwitchBadgeIDs[finalName] = index;
                                        Plugin.Log("Replaced default sub icon!");
                                        break;
                                    }
                                    yield return(null);
                                }
                            }
                        }
                    }
                    Plugin.Log("Web request completed, twitch channel badges now cached!");
                }
            }
        }
예제 #14
0
        void m_Done()
        {
            var type = cRequest.assetType;

#if UNITY_2017
            if (m_webrequest == null || m_webrequest.isNetworkError)
#else
            if (m_webrequest == null || m_webrequest.isError)
#endif
            {
                error          = string.Format("url:{0},erro:{1}", cRequest.url, m_webrequest == null?"m_webrequest is null":m_webrequest.error);
                cRequest.error = error;
                Debug.LogError(error);
            }
            else if (!(m_webrequest.responseCode == 200 || m_webrequest.responseCode == 0))
            {
                error          = string.Format("response error code = {0},url={1}", m_webrequest.responseCode, cRequest.url); // m_webrequest.error;
                cRequest.error = error;
                Debug.LogError(error);
            }
            else
            {
                object m_Data = null;
                if (LoaderType.Typeof_Bytes.Equals(type))
                {
                    m_Data = m_webrequest.downloadHandler.data;
                }
                else if (LoaderType.Typeof_Texture2D.Equals(type))
                {
                    m_Data = DownloadHandlerTexture.GetContent(m_webrequest);
                }
                else if (LoaderType.Typeof_AssetBundle.Equals(type))
                {
                    m_Data = DownloadHandlerAssetBundle.GetContent(m_webrequest);
                }
                else
                {
                    m_Data = DownloadHandlerBuffer.GetContent(m_webrequest);
                }

                cRequest.data = m_Data;
            }

            if (m_webrequest != null)
            {
                m_webrequest.Dispose();
            }
            m_webrequest     = null;
            m_asyncOperation = null;
        }
예제 #15
0
        private void FinishDownload()
        {
            if (m_webrequest == null)
            {
                error = string.Format("webrequest is null , {0} ", cRequest.key);;
                return;
            }

            if (m_webrequest.isError)
            {
                error = m_webrequest.error;
                Debug.LogError(error);
                return;
            }

            if (m_webrequest.responseCode != 200)
            {
                error = string.Format("response error code = {0}", m_webrequest.responseCode); // m_webrequest.error;
                Debug.LogError(error);
                return;
            }

            var type = cRequest.assetType;

            if (CacheManager.Typeof_AudioClip.Equals(type))
            {
                m_Data = DownloadHandlerAudioClip.GetContent(m_webrequest);
            }
            else if (CacheManager.Typeof_Texture2D.Equals(type))
            {
                m_Data = DownloadHandlerTexture.GetContent(m_webrequest);
            }
            else if (CacheManager.Typeof_Bytes.Equals(type))
            {
                m_Data = m_webrequest.downloadHandler.data;
            }
            else
            {
                m_Data = DownloadHandlerBuffer.GetContent(m_webrequest);
            }

            UriGroup.CheckWWWComplete(cRequest, m_webrequest);

            cRequest.data = m_Data;
            m_webrequest.Dispose();
            m_webrequest     = null;
            m_asyncOperation = null;
        }
        public static IEnumerator GetTwitchGlobalBadges()
        {
            Plugin.Log($"Downloading twitch global badge listing");

            using (var web = UnityWebRequest.Get("https://badges.twitch.tv/v1/badges/global/display")) {
                yield return(web.SendWebRequest());

                if (web.isNetworkError || web.isHttpError)
                {
                    Plugin.Log($"An error occured when requesting twitch global badge listing, Message: \"{web.error}\"");
                }
                else
                {
                    var json = DownloadHandlerBuffer.GetContent(web);

                    if (json.Count() > 0)
                    {
                        var j = SimpleJSON.JSON.Parse(json);
                        if (j["badge_sets"].IsObject)
                        {
                            foreach (KeyValuePair <string, SimpleJSON.JSONNode> kvp in j["badge_sets"])
                            {
                                string name = kvp.Key;
                                var    o    = kvp.Value.AsObject;
                                foreach (KeyValuePair <string, SimpleJSON.JSONNode> version in o["versions"].AsObject)
                                {
                                    string versionID     = version.Key;
                                    var    versionObject = version.Value.AsObject;
                                    string url           = versionObject["image_url_4x"];
                                    string index         = url.Substring(url.IndexOf("/v1/") + 4).Replace("/3", "");
                                    while (!TwitchBadgeIDs.TryAdd($"{name}{versionID}", index))
                                    {
                                        if (name == "subscriber")
                                        {
                                            Plugin.Log("Subscriber badge already exists! Skipping!");
                                            break;
                                        }
                                        yield return(null);
                                    }
                                }
                            }
                        }
                    }
                    Plugin.Log("Web request completed, twitch global badges now cached!");
                }
            }
        }
        public static IEnumerator GetBTTVGlobalEmotes()
        {
            Plugin.Log("Downloading BTTV global emote listing");

            using (var web = UnityWebRequest.Get("https://api.betterttv.net/2/emotes")) {
                yield return(web.SendWebRequest());

                if (web.isNetworkError || web.isHttpError)
                {
                    Plugin.Log($"An error occured when requesting BTTV global emote listing, Message: \"{web.error}\"");
                }
                else
                {
                    var json = DownloadHandlerBuffer.GetContent(web);
                    if (json.Count() > 0)
                    {
                        var j = SimpleJSON.JSON.Parse(json);
                        if (j["status"].AsInt == 200)
                        {
                            var emotes = j["emotes"].AsArray;
                            foreach (SimpleJSON.JSONObject o in emotes)
                            {
                                if (o["channel"] == null)
                                {
                                    if (o["imageType"] != "gif")
                                    {
                                        while (!BTTVEmoteIDs.TryAdd(o["code"], o["id"]))
                                        {
                                            yield return(null);
                                        }
                                    }
                                    else
                                    {
                                        while (!AnimatedSpriteLoader.BTTVAnimatedEmoteIDs.TryAdd(o["code"], o["id"]))
                                        {
                                            yield return(null);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    Plugin.Log("Web request completed, BTTV global emotes now cached!");
                }
            }
        }
예제 #18
0
    IEnumerator RequestSoundList(string eventId)
    {
        string responseBody;

        using (UnityWebRequest req = UnityWebRequest.Get("https://echoes.etc.cmu.edu/api/viewer/events/" + eventId + "/sound"))
        {
            req.SetRequestHeader("Authorization", "Bearer " + PlayerPrefs.GetString("token"));

            yield return(req.SendWebRequest());


            if (req.isNetworkError || req.isHttpError)
            {
                Debug.Log(req.error + " : " + req.downloadHandler.text);
            }

            responseBody = DownloadHandlerBuffer.GetContent(req);
            PlayerPrefs.SetString("body", responseBody);
        }
        StartCoroutine(GetSoundList());
    }
예제 #19
0
            private void Load()
            {
                _loading = true;
                var version = DocApp.of(context).version;
                var url     =
                    $"{Configuration.Instance.cdnPrefix}/{version.unityVersion}/{version.parsedVersion}/manual/json/{widget._title.Replace('-', '_')}.json";
                var request        = UnityWebRequest.Get(url);
                var asyncOperation = request.SendWebRequest();

                asyncOperation.completed += operation =>
                {
                    if (!mounted)
                    {
                        return;
                    }

                    using (WindowProvider.of(context).getScope())
                    {
                        if (request.responseCode == 404)
                        {
                            DocApp.of(context).ForceUnknown();
                        }
                        else
                        {
                            var content = DownloadHandlerBuffer.GetContent(request);
                            var model   = JsonConvert.DeserializeObject <ManualModel>(content);
                            setState(() =>
                            {
                                _tokens      = model.tokens;
                                _prevLink    = model.prev;
                                _nextLink    = model.next;
                                _breadcrumbs = model.breadcrumbs;
                                _imageMetas  = model.imageMetas;
                                _loading     = false;
                            });
                        }
                    }
                };
            }
예제 #20
0
        public IEnumerator Download(string url, Action <DownloadResponse <T> > result)
        {
            Downloading.Next(true);

            using (UnityWebRequest uwr = UnityWebRequest.Get(url)) {
                yield return(uwr.SendWebRequest());

                if (uwr.HasErrors())
                {
                    result(new DownloadResponse <T>(default(T), uwr));
                }
                else
                {
                    // save
                    string text = DownloadHandlerBuffer.GetContent(uwr);
                    T      json = JsonUtility.FromJson <T>(text);
                    result(new DownloadResponse <T>(json, uwr));
                }

                Downloading.Next(false);
            }
        }
예제 #21
0
        // Translate
        public async Task <string> TranslateAsync(string text, string language = "en")
        {
            // Compose url
            var url = $"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to={language}";

            using (var www = UnityWebRequest.Post(url, string.Empty))
            {
                www.timeout = 10;

                // Set headers
                www.SetRequestHeader("Ocp-Apim-Subscription-Key", ApiKey);
                www.SetRequestHeader("Content-Type", "application/json; charset=UTF-8");

                // Set data
                var data = new List <AzureTranslationText>()
                {
                    new AzureTranslationText(text)
                };
                www.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data)));

                // Send request
                await www.SendWebRequest();

                // Handle response
                if (www.isNetworkError || www.isHttpError)
                {
                    Debug.LogError($"Error occured while processing text-to-speech voice: {www.error}");
                }
                else if (www.isDone)
                {
                    var responseString      = DownloadHandlerBuffer.GetContent(www);
                    var translationResponse = JsonConvert.DeserializeObject <List <AzureTranslationResponse> >(responseString);
                    var translatedText      = translationResponse[0].Translations[0].Text;
                    return(translatedText);
                }
            }
            return(null);
        }
        public static IEnumerator GetFFZChannelEmotes()
        {
            Plugin.Log($"Downloading FFZ emotes for channel {Plugin.Instance.Config.TwitchChannel}");

            using (var web = UnityWebRequest.Get($"https://api.frankerfacez.com/v1/room/{Plugin.Instance.Config.TwitchChannel}")) {
                yield return(web.SendWebRequest());

                if (web.isNetworkError || web.isHttpError)
                {
                    Plugin.Log($"An error occured when requesting FFZ channel emote listing, Message: \"{web.error}\"");
                }
                else
                {
                    var json = DownloadHandlerBuffer.GetContent(web);
                    if (json.Count() > 0)
                    {
                        var j = SimpleJSON.JSON.Parse(json);
                        if (j["sets"].IsObject)
                        {
                            var emotes = j["sets"][j["room"]["set"].ToString()]["emoticons"].AsArray;
                            foreach (SimpleJSON.JSONObject o in emotes)
                            {
                                var    urls  = o["urls"].AsObject;
                                string url   = urls[urls.Count - 1];
                                string index = url.Substring(url.IndexOf(".com/") + 5);

                                while (!FFZEmoteIDs.TryAdd(o["name"], index))
                                {
                                    yield return(null);
                                }
                            }
                        }
                    }
                    Plugin.Log("Web request completed, FFZ channel emotes now cached!");
                }
            }
        }
예제 #23
0
        // Translate
        public async Task <string> TranslateAsync(string text, string language = "en")
        {
            // Compose url
            var url = $"https://translation.googleapis.com/language/translate/v2";

            // Set data
            var data = new WWWForm();

            data.AddField("key", ApiKey);
            data.AddField("q", text);
            data.AddField("target", language);
            data.AddField("source", "ja");
            data.AddField("model", "nmt");

            using (var www = UnityWebRequest.Post(url, data))
            {
                www.timeout = 10;

                // Send request
                await www.SendWebRequest();

                // Handle response
                if (www.isNetworkError || www.isHttpError)
                {
                    Debug.LogError($"Error occured while processing text-to-speech voice: {www.error}");
                }
                else if (www.isDone)
                {
                    var responseString      = DownloadHandlerBuffer.GetContent(www);
                    var translationResponse = JsonConvert.DeserializeObject <GoogleTranslationResponse>(responseString);
                    var translatedText      = translationResponse.Data.Translations[0].TranslatedText;
                    return(translatedText);
                }
            }
            return(null);
        }
예제 #24
0
        /// <summary>
        /// Loads assets from a remote server and internally populates the list of
        /// items in the game
        /// </summary>
        public void LoadAssets()
        {
            downloadQueue.Clear();
            downloadStatus = DownloadStatus.Downloading;

            var manifestRequest = UnityWebRequest.Get(assetListUrl);
            var manifestWWW     = manifestRequest.SendWebRequest();

            Debug.Log("[Item Catalog] Starting download...");

            manifestWWW.completed += c => {
                var json = DownloadHandlerBuffer.GetContent(manifestRequest);
                var data = ProcessBundleJsonData(json);

                for (var i = 0; i < data.Length; ++i)
                {
                    downloadQueue.Enqueue(data[i]);
                }

                DownloadFromQueue(downloadQueue);

                manifestRequest.Dispose();
            };
        }
예제 #25
0
            public override void initState()
            {
                base.initState();

                _currentLastSegment = LastSegment(ObservableUtil.currentPath.value);
                ObservableUtil.currentPath.OnChanged += OnPathChanged;

                var version        = DocApp.of(context).version;
                var request        = UnityWebRequest.Get($"{Configuration.Instance.cdnPrefix}/{version.unityVersion}/{version.parsedVersion}/{widget._type.TocFileName()}");
                var asyncOperation = request.SendWebRequest();

                asyncOperation.completed += operation =>
                {
                    if (!mounted)
                    {
                        return;
                    }
                    var content = DownloadHandlerBuffer.GetContent(request);
                    using (WindowProvider.of(context).getScope())
                    {
                        setState(() => _menu = JsonConvert.DeserializeObject <Models.Json.Menu>(content));
                    }
                };
            }
예제 #26
0
            private void DoSearch()
            {
                _keyword    = Uri.UnescapeDataString(widget._keyword);
                _page       = widget._page;
                _filterType = widget._filterType;

                if (_keyword == string.Empty)
                {
                    return;
                }

                _searching = true;
                var url =
                    $"{Configuration.Instance.apiHost}/api/documentation/search/v/2018.1/t/{_filterType}?query={_keyword}&page={_page}&pageSize=10";
                var request        = UnityWebRequest.Get(url);
                var asyncOperation = request.SendWebRequest();

                asyncOperation.completed += operation =>
                {
                    if (!mounted)
                    {
                        return;
                    }

                    using (WindowProvider.of(context).getScope())
                    {
                        var content = DownloadHandlerBuffer.GetContent(request);
                        var results = SearchResults.FromJson(JsonValue.Parse(content));
                        setState(() =>
                        {
                            _results   = results;
                            _searching = false;
                        });
                    }
                };
            }
예제 #27
0
        /// <summary>
        /// 毎フレーム更新
        /// </summary>
        /// <returns>進行中の処理が完了したらfalse</returns>
        public bool Update()
        {
            // 初期値が入っていたらリクエストを飛ばす
            if (this._sendRequestTime <= -1f)
            {
                this.SendRequest();
            }

            float realtimeSinceStartup = Time.realtimeSinceStartup;

            // リトライ処理
            float retryWaitTimeCount = this._retryWaitTimeCount;

            if (retryWaitTimeCount > 0f)
            {
                // リトライ開始前の待機
                if ((realtimeSinceStartup - retryWaitTimeCount) >= WebRequestOperation.RetryWaitTime)
                {
                    return(true);
                }
                this._retryWaitTimeCount = -1f;
                this.SendRequest();
            }

            // 通信完了待機
            if (!this._request.isDone && (this._errorType == ErrorType.None))
            {
                if ((realtimeSinceStartup - this._sendRequestTime) >= WebRequestOperation.TimeOut)
                {
                    // タイムアウト判定
                    this._errorType = ErrorType.TimeOut;
                }
                else
                {
                    return(true);
                }
            }

            // エラー判定
            if ((this._errorType == ErrorType.None) && (this._request.isNetworkError || this._request.responseCode != 200))
            {
                // HACK. 内容を見てもっと細分化した方が良い
                this._errorType = ErrorType.Other;
            }

            string responseText = null;

            if (this._errorType != ErrorType.None)
            {
                // 通信失敗 + リトライ
#if WEB_REQUEST_OPERATION_ENABLE_API_LOG
                Debug.LogWarningFormat(
                    "Error.... [url : {0}], [code : {1}], [type : {2}], [message : {3}], [count : {4}]",
                    this._request.url, this._request.responseCode, this._errorType, this._request.error, this._currentRetryCount);
#endif
                if (this.Retry())
                {
                    return(true);
                }
            }
            else
            {
                // 通信成功
                responseText = DownloadHandlerBuffer.GetContent(this._request);
#if WEB_REQUEST_OPERATION_ENABLE_API_LOG
                Debug.LogFormat(
                    "Success... [url : {0}], [code : {1}], [response : {2}]",
                    this._request.url, this._request.responseCode, responseText);
#endif
            }

            this._finishedCallback(new Response(responseText, this._request.error));
            this._request.Dispose();
            return(false);
        }
예제 #28
0
        IEnumerator LoadingInspector(UnityWebRequest www, Request info)
        {
            www.timeout = delayTime;
            yield return(www.SendWebRequest());

            if (!string.IsNullOrEmpty(www.error) || www.isHttpError || www.isNetworkError)
            {
                if (www.isHttpError)
                {
                    RequestException(info, Status.ServerError, "http error");
                }
                else if (www.isNetworkError)
                {
                    RequestException(info, Status.NetworkError, "network error");
                }
                else
                {
                    RequestException(info, Status.ServerError, www.error);
                }
                if (!info.isLoop)
                {
                    ZLog.Warning("no loop the remove the request that id = " + info.uid);
                    RemoveRequestInfo(info.uid);
                }
            }
            else
            {
                Response response = new Response
                {
                    uid   = info.uid,
                    param = info.param
                };

                if (info.callFun != null)
                {
                    if (!string.IsNullOrEmpty(www.error))
                    {
                        ZLog.Warning("Http exception...." + info.uid + "---" + www.error);
                        response.state = Status.ServerError;
                        response.data  = www.error;

                        info.callFun.Invoke(response);
                    }
                    else
                    {
                        string mess = DownloadHandlerBuffer.GetContent(www);
                        responseDataSize += mess.Length;

                        response.state = Status.Normal;
                        response.data  = mess;
                        info.callFun.Invoke(response);
                    }
                }
                RemoveRequestInfo(info.uid);
            }
            yield return(null);

            www.Dispose();

            yield return(null);

            isLoading = false;
            StartLoadNext();
        }