//TODO: Refactor this behind its own object to provide download URL for character. /// <inheritdoc /> public async Task OnGameInitialized() { if (Logger.IsInfoEnabled) { Logger.Info("About to start downloading map data."); } //When we start the loading screen for the game //To know what world we should load we should CharacterSessionDataResponse characterSessionData = await CharacterService.GetCharacterSessionData(LocalCharacterData.CharacterId, AuthTokenRepo.RetrieveWithType()) .ConfigureAwait(false); if (!characterSessionData.isSuccessful) { Logger.Error($"Failed to query Character Session Data: {characterSessionData.ResultCode}:{(int)characterSessionData.ResultCode}"); return; } //TODO: Handle failure ProjectVersionStage.AssertAlpha(); //TODO: Handle throwing/error //We need to know the world the zone is it, so we can request a download URL for it. long worldId = await ZoneDataService.GetZoneWorld(characterSessionData.ZoneId) .ConfigureAwait(false); //With the worldid we can get the download URL. ContentDownloadURLResponse urlDownloadResponse = await ContentService.RequestWorldDownloadUrl(worldId, AuthTokenRepo.RetrieveWithType()) .ConfigureAwait(false); //TODO: Handle failure if (urlDownloadResponse.isSuccessful) { if (Logger.IsInfoEnabled) { Logger.Info($"Download URL: {urlDownloadResponse.DownloadURL}"); } //Can't do web request not on the main thread, sadly. await new UnityYieldAwaitable(); //TODO: Do we need to be on the main unity3d thread UnityWebRequestAsyncOperation asyncOperation = UnityWebRequestAssetBundle.GetAssetBundle(urlDownloadResponse.DownloadURL, 0).SendWebRequest(); //TODO: We should render these operations to the loading screen UI. asyncOperation.completed += operation => { AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(asyncOperation.webRequest); string[] paths = bundle.GetAllScenePaths(); foreach (string p in paths) { Debug.Log($"Found Scene in Bundle: {p}"); } AsyncOperation sceneAsync = SceneManager.LoadSceneAsync(System.IO.Path.GetFileNameWithoutExtension(paths.First())); sceneAsync.completed += operation1 => { //When the scene is finished loading we should cleanup the asset bundle //Don't clean up the WHOLE BUNDLE, just the compressed downloaded data bundle.Unload(false); //TODO: We need a way/system to reference the bundle later so it can be cleaned up inbetween scene loads. }; sceneAsync.allowSceneActivation = true; }; } }
public static UnityWebRequestAwaiter GetAwaiter(this UnityWebRequestAsyncOperation asyncOp) { return(new UnityWebRequestAwaiter(asyncOp)); }
//在LoadAsssetBundle时inUrl链接会拼入用^拆分cache路径,用&拆分连接参数 public RequestHandler(string inHelpInfo, NetCtrlManager net, string inUrl, WebQuestDelegate p = null, WebQuestDelegate eFalse = null, WebQuestDelegateText eText = null, WebQuestDelegateTexture eTexture = null, WebQuestDelegateAssetBundle eAssetBundle = null) { if (inUrl == "") { Debug.LogError("输入的URL为空!"); return; } name = inHelpInfo; netCtrlManager = net; helpInfo = inHelpInfo; Debug.Log("InputURL: <color=blue>" + inUrl + "</color>"); timing = 0; string[] splitStringGroup = inUrl.Split('^'); url = splitStringGroup[0]; //保存所有的参数 paddingArgUrlSplitGroup = url.Split('?'); if (paddingArgUrlSplitGroup.Length > 1) { //除去参数的连接 urlWithoutArg = paddingArgUrlSplitGroup[0]; paddingArgUrlSplitGroup = paddingArgUrlSplitGroup[1].Split('&'); } // string[] urlSplit = url.Split('/'); // name = urlSplit[urlSplit.Length - 1]; //Cache路径 if (splitStringGroup.Length > 1) { paddingUrl = splitStringGroup[1]; paddingUrlSplitGroup = paddingUrl.Split(','); } if (url == "") { processInfo = "url为空"; return; } isNeedProcess = true; onProgress += GetProgress; if (p != null) { onProgress += p; onTrue += p; onFalse += p; } if (eFalse != null) { onFalse += eFalse; } if (eText != null) { request = UnityWebRequest.Get(url); requestType = 0; onEndText += eText; finalTimeOut = timeOut; } else if (eTexture != null) { WWWForm form = new WWWForm(); form.AddField("downloadId", paddingArgUrlSplitGroup[0].Split('=')[1]); form.AddField("downloadType", paddingArgUrlSplitGroup[1].Split('=')[1]); form.AddField("mediaType", paddingArgUrlSplitGroup[2].Split('=')[1]); form.AddField("fileName", paddingArgUrlSplitGroup[3].Split('=')[1]); /* * Debug.Log(urlWithoutArg); * foreach (string s in paddingArgUrlSplitGroup) * { * Debug.Log(s); * } */ request = UnityWebRequest.Post(urlWithoutArg, form); requestType = 1; onEndTexture += eTexture; request.downloadHandler = new DownloadHandlerTexture(); finalTimeOut = timeOut * 12; } else if (eAssetBundle != null) { request = UnityWebRequest.Get(url); requestType = 2; onEndAssetBundle += eAssetBundle; //name包含了路径Cache request.downloadHandler = new DownloadHandlerAssetBundle("", paddingUrlSplitGroup[0], Hash128.Parse(paddingUrlSplitGroup[1]), uint.Parse(paddingUrlSplitGroup[2])); finalTimeOut = timeOut * 360; } request.timeout = finalTimeOut; asyncOpertion = request.SendWebRequest(); // asyncOpertion.allowSceneActivation = true; }
public AgonesAsyncOperationAwaiter(AgonesAsyncOperationWrapper wrapper) { asyncOp = wrapper.AsyncOp; asyncOp.completed += OnRequestCompleted; }
public void OnTimeOut() { m_WebRequestAsyncOperation.webRequest.Dispose(); m_WebRequestAsyncOperation = null; }
public override void RequestIssues(Action <List <BugReporterPlugin.IssueEntry> > requestFinishedCallback, BugReporterPlugin.IssueFilter filter) { var settings = BugReporterPlugin.settings.GetBackendSettings(backendName); string requestURL = baseURL + "/repos/" + settings.projectPath + "/issues?"; if (filter.user != null) { requestURL += "assignee=" + filter.user.name + "&"; } if (filter.labels != null && filter.labels.Length > 0) { requestURL += "labels=" + filter.labelCommaString; } var request = UnityWebRequest.Get(requestURL); request.SetRequestHeader("Accept", "application/vnd.github.v3+json"); request.SetRequestHeader("Authorization", "token " + _token); var async = request.SendWebRequest(); async.completed += op => { UnityWebRequestAsyncOperation asyncop = op as UnityWebRequestAsyncOperation; if (asyncop.webRequest.isHttpError) { Debug.LogError("couldn't get issues for repo " + settings.projectPath); Debug.LogError(asyncop.webRequest.error); } else { _issues.Clear(); string newJson = "{ \"array\": " + asyncop.webRequest.downloadHandler.text + "}"; GithubIssueData[] issues = JsonUtility.FromJson <Wrapper <GithubIssueData> >(newJson).array; for (int i = 0; i < issues.Length; ++i) { BugReporterPlugin.IssueEntry newEntry = new BugReporterPlugin.IssueEntry(); newEntry.title = issues[i].title; newEntry.description = issues[i].body; newEntry.webUrl = issues[i].url; newEntry.assignees = new BugReporterPlugin.UserEntry[0]; if (issues[i].assignees != null) { for (int j = 0; j < issues[i].assignees.Length; ++j) { //TODO : this is terrible. Use some dictionnary maybe or better typing to avoid so much silly conversion var userEntry = BugReporterPlugin.GetUserInfoByID(issues[i].assignees[j].id.ToString()); if (userEntry != null) { ArrayUtility.Add(ref newEntry.assignees, userEntry); } } } newEntry.labels = new string[0]; if (issues[i].labels != null) { for (int j = 0; j < issues[i].labels.Length; ++j) { ArrayUtility.Add(ref newEntry.labels, issues[i].labels[j].name); } } newEntry.RetrieveDataFromUnityURL(); newEntry.BuildCommaStrings(); _issues.Add(newEntry); } requestFinishedCallback(_issues); } }; }
private void SearchInOSM(string namePlace) { UnityWebRequest www = UnityWebRequest.Get(String.Format(seachUrl, System.Uri.EscapeDataString(namePlace))); request = www.SendWebRequest(); }
IEnumerator _GetPhotos() { var endpoints = new List <string>(this.result.images); for (int i = 0; i < this.cache.Count; ++i) { endpoints.Remove(this.cache[i]); } var photoViews = new List <PhotoView>(); for (int i = 0; i < endpoints.Count; ++i) { var clone = GameObject.Instantiate(this.template.gameObject); clone.transform.SetParent(this.content); clone.transform.localScale = Vector3.one; clone.transform.localRotation = Quaternion.identity; var photoView = clone.GetComponent <PhotoView>(); photoViews.Add(photoView); clone.SetActive(true); this.cache.Add(endpoints[i]); } int batch = 4; UnityWebRequestAsyncOperation[] operations = new UnityWebRequestAsyncOperation[batch]; int iterations = endpoints.Count / batch; for (int i = 0; i < iterations; ++i) { for (int j = 0; j < batch; ++j) { int index = i * batch + j; var url = this.result.url + "/" + endpoints[index]; var request = UnityWebRequest.Get(url); request.downloadHandler = new DownloadHandlerTexture(); operations[j] = request.SendWebRequest(); int func_j = j; uThread.RunCoroutine(this.Yield(operations[func_j]), () => { var operation = operations[func_j]; if (operation.webRequest.isHttpError || operation.webRequest.isNetworkError) { Debug.LogError(operation.webRequest.error); } else { photoViews[index].Texture2D = (operation.webRequest.downloadHandler as DownloadHandlerTexture).texture; } }); } yield return(new WaitUntil(() => { bool isDone = true; for (int k = 0; k < operations.Length; ++k) { int index = i * batch + k; photoViews[index].Progress = operations[k].progress; isDone &= operations[k].isDone && operations[k].progress >= 1.0F; } return isDone; })); yield return(new WaitForSecondsRealtime(0.25F)); } int remaining = endpoints.Count % batch; if (remaining > 0) { for (int i = 0; i < remaining; ++i) { int index = iterations * batch + i; var url = this.result.url + "/" + endpoints[index]; var request = UnityWebRequest.Get(url); request.downloadHandler = new DownloadHandlerTexture(); operations[i] = request.SendWebRequest(); int func_i = i; uThread.RunCoroutine(this.Yield(operations[func_i]), () => { photoViews[index].Texture2D = (operations[func_i].webRequest.downloadHandler as DownloadHandlerTexture).texture; }); } yield return(new WaitUntil(() => { bool isDone = true; for (int k = 0; k < remaining; ++k) { int index = iterations * batch + k; photoViews[index].Progress = operations[k].progress; isDone &= operations[k].isDone; } return isDone; })); } }
private IEnumerator DownloadAssetBundles() { using (UnityWebRequest req = UnityWebRequest.Get(SystemConfig.GetFilePath("/", AssetbundleInfoFile, false))) { UnityWebRequestAsyncOperation reqBin = req.SendWebRequest(); yield return(reqBin); if (req.isNetworkError || req.isHttpError) { // 重新下载 DebugUtils.Log(InfoType.Error, string.Format("DiffAssets : {0}", SystemConfig.GetFilePath("/", AssetbundleInfoFile, false))); } else { if (req.downloadHandler.isDone) { GameDataManager.ChangeDir(SystemConfig.GameDataDir); // 本地获取并解析, 全部拷贝一份 List <AssetbundleUpdateData> oldDataInfos = AssetbundleUpdateData.Select((item) => { return(item.Name != null); }); // 清理不存在本地文件的实例 int notExistsCount = oldDataInfos.RemoveAll((item) => { return(IsFileExist(item)); }); DebugUtils.Log(InfoType.Warning, string.Format("notExistsCount {0}", notExistsCount)); // 再释放 GameDataManager.ClearFileData(AssetbundleInfoFile); DebugUtils.Assert(AssetbundleUpdateData.IsOriginNull(), "wrong clear"); // 保存到 临时目录 string text = req.downloadHandler.text; File.WriteAllText(SystemConfig.LocalTempDir + "/" + AssetbundleInfoFile, text); // 切换到 临时目录 GameDataManager.ChangeDir(SystemConfig.LocalTempDir); // 全部拷贝一份 List <AssetbundleUpdateData> newDataInfos = AssetbundleUpdateData.Select((item) => { return(item.Name != null); }); // 释放 GameDataManager.ClearFileData(AssetbundleInfoFile); DebugUtils.Assert(AssetbundleUpdateData.IsOriginNull(), "wrong clear"); GameDataManager.ChangeDir(SystemConfig.GameDataDir); // 处理 List <AssetbundleUpdateData> addAssets = DiffAssetBundles(oldDataInfos, newDataInfos); mDownloadSize = 0; mTotalSize = 0; mTotalCount = 0; mDownloadCount = 0; mAssetbunlesWebRequest.Clear(); mTotalCount = addAssets.Count; addAssets.ForEach((item) => { mTotalSize += item.FileSize; }); foreach (AssetbundleUpdateData info in addAssets) { string url = SystemConfig.GetRemotePathInAssetbundle(info.Name); UnityWebRequest abReq = UnityWebRequest.Get(url); AddReq(abReq); UnityWebRequestAsyncOperation reqAssetbundleReq = abReq.SendWebRequest(); reqAssetbundleReq.completed += (AsyncOperation operation) => { if (abReq.isNetworkError || abReq.isHttpError) { // 重新下载 DebugUtils.Log(InfoType.Error, "wrong req: " + url); } else { AddDownloadCount(); byte[] data = abReq.downloadHandler.data; AddDownloadSize(data.Length); SaveLocalAssetBundle(info.Name, data); // 下载进度 SizeProgress?.Invoke(SizePercent); CountProgress?.Invoke(mDownloadCount, mTotalCount); } RemoveReq(abReq); abReq.Dispose(); }; } // 开始进度 SizeProgress?.Invoke(SizePercent); while (mAssetbunlesWebRequest.Count > 0) { yield return(Wait); } Finished?.Invoke(mVersionData.InfoTips); } } } }
// Use this for initialization void Start() { // client = new Socket(SocketType.Stream,ProtocolType.Tcp); // client.Connect("10.104.52.111",2700); video = GameObject.Find("Cube"); actions.Add("scale up", () => { Vector3 transformLocalScale = video.transform.localScale; video.transform.localScale = new Vector3( transformLocalScale.x * 1.2F, transformLocalScale.y * 1.2F, transformLocalScale.z * 1.2F ); Debug.LogError("ffffuc"); }); actions.Add("see you", () => { gameObject.transform.localScale = new Vector3( 0, 0, 0 ); Debug.LogError("ffffuc"); }); actions.Add("assistant please", () => { gameObject.transform.localScale = new Vector3( 0.2F, 0.2F, 0.2F ); Debug.LogError("ffffuc"); }); actions.Add("scale down", () => { Vector3 transformLocalScale = video.transform.localScale; video.transform.localScale = new Vector3( transformLocalScale.x / 1.2F, transformLocalScale.y / 1.2F, transformLocalScale.z / 1.2F ); Debug.LogError("ffffuc"); }); actions.Add("play", () => { VideoPlayer player = GameObject.Find("Cube").GetComponent <VideoPlayer>(); UnityWebRequest req = UnityWebRequest.Get("http://10.104.50.41:2700/charalens/api/play"); UnityWebRequestAsyncOperation op = req.SendWebRequest(); op.completed += operation => { player.time = Convert.ToDouble(req.downloadHandler.text); player.Play(); }; }); actions.Add("pause", () => { VideoPlayer player = GameObject.Find("Cube").GetComponent <VideoPlayer>(); UnityWebRequest req = UnityWebRequest.Get("http://10.104.50.41:2700/charalens/api/pause"); UnityWebRequestAsyncOperation op = req.SendWebRequest(); op.completed += operation => { player.time = Convert.ToDouble(req.downloadHandler.text); player.Pause(); }; }); recognizer = new KeywordRecognizer(actions.Keys.ToArray()); recognizer.OnPhraseRecognized += args => { actions[args.text].Invoke(); }; recognizer.Start(); }
IEnumerator Yield(UnityWebRequestAsyncOperation operation) { yield return(operation); }
private void CheckTokenRequest() { if (pending_request == null || !pending_request.isDone) { return; } #if UNITY_2020_2_OR_NEWER if (pending_request.webRequest.result == UnityWebRequest.Result.ConnectionError) { #else if (pending_request.webRequest.isNetworkError) { #endif Debug.LogError(pending_request.webRequest.responseCode == 400 ? "Invalid API Credentials" : "Something went wrong when trying to retrieve API key. Please try again later."); return; } try{ var responseDict = MiniJSON.Json.Deserialize(pending_request.webRequest .downloadHandler.text) as Dictionary <string, object>; apiToken = (string)responseDict["idToken"]; tokenExpiry = DateTime.Now.AddMinutes(30); environmentsJson = null; pending_environment_request = null; } catch { Debug.LogError("Could not parse API Token response. Are your credentials correct?"); } finally{ pending_request = null; } } void GetApiToken() { var url = "https://api.deltadna.net/api/authentication/v1/authenticate"; var dict = new Dictionary <String, String> { { "key", apiConfig.ApiKey }, { "password", apiPassword } }; var bodyJsonString = Json.Serialize(dict); var request = new UnityWebRequest(url, "POST"); byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(bodyJsonString); request.uploadHandler = new UploadHandlerRaw(bodyRaw); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); pending_request = request.SendWebRequest(); } void GetEnvironments() { var url = "https://api.deltadna.net/api/engage/v1/environments"; var request = new UnityWebRequest(url, "GET") { downloadHandler = new DownloadHandlerBuffer() }; request.SetRequestHeader("Content-Type", "application/json"); request.SetRequestHeader("Authorization", "Bearer " + apiToken); pending_environment_request = request.SendWebRequest(); }
private void OnGUI() { wantsMouseMove = true; #if UNITY_5_6_OR_NEWER wantsMouseEnterLeaveWindow = true; if (Event.current.type == EventType.MouseEnterWindow || Event.current.type == EventType.MouseLeaveWindow) { Repaint(); return; } #endif if (Event.current.type == EventType.MouseMove || Event.current.type == EventType.MouseDrag) { Repaint(); return; } if (subtitleText == null) { subtitleText = new GUIStyle(EditorStyles.centeredGreyMiniLabel) { #if UNITY_2019_1_OR_NEWER alignment = TextAnchor.LowerLeft, #else alignment = TextAnchor.MiddleLeft, #endif fontSize = 8, richText = true, contentOffset = new Vector2(0, 9.0f), padding = new RectOffset(4, 4, 0, 0) }; } if (titleText == null) { titleText = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperLeft, padding = new RectOffset(4, 4, 0, 0) }; } if (headerStyle == null) { headerStyle = new GUIStyle() { padding = new RectOffset(28, 28, 16, 8) }; } if (checkingDialogStyle == null) { checkingDialogStyle = new GUIStyle() { padding = new RectOffset(28, 28, 16, 8) }; } using (new EditorGUILayout.VerticalScope(headerStyle)) { EditorGUILayout.LabelField("AssetIcons", EditorStyles.largeLabel); EditorGUILayout.LabelField("Current Version " + ProductInformation.Version); } // If a download hasn't started, start a download. if (statusRequest == null) { statusRequest = UnityWebRequest.Get("https://fydar.github.io/AssetIcons/version/status.json"); #if UNITY_2017_2_OR_NEWER statusOperation = statusRequest.SendWebRequest(); #else statusOperation = statusRequest.Send(); #endif } // If the request is down and we haven't tried deserializing it, deserialize it if (statusRequest.isDone && statusModel == null && Event.current.type == EventType.Layout) { isComplete = true; #if !UNITY_2017_1_OR_NEWER if (statusRequest.isError) { errorMessage = statusRequest.error; } #else if (statusRequest.isHttpError) { errorMessage = "Got a bad response of " + statusRequest.responseCode + "."; } else if (statusRequest.isNetworkError) { errorMessage = statusRequest.error; } #endif else { // ErrorMessage string text = statusRequest.downloadHandler.text; try { statusModel = JsonUtility.FromJson <ProductStatusModel>(text); errorMessage = null; } catch (Exception exception) { Debug.LogError(string.Format("Got exception\"{0}\" when deserializing the network response.\n{1}", exception.GetType().Name, exception.ToString())); errorMessage = "Failed to deserialize response"; } } } if (statusModel != null) { DrawHistory(statusModel); } else { using (new EditorGUILayout.VerticalScope(headerStyle)) { if (isComplete) { EditorGUILayout.LabelField("Update Check Failed", EditorStyles.centeredGreyMiniLabel); EditorGUILayout.HelpBox(errorMessage, MessageType.Error); if (GUILayout.Button("Retry")) { statusRequest = null; errorMessage = null; isComplete = false; statusModel = null; } } else { EditorGUILayout.LabelField("Checking for Updates", EditorStyles.centeredGreyMiniLabel); var rect = GUILayoutUtility.GetRect(0, float.MaxValue, EditorGUIUtility.singleLineHeight, EditorGUIUtility.singleLineHeight); EditorGUI.ProgressBar(rect, statusOperation.progress, "Downloading..."); } } } }
private static IEnumerator DownloadSong_internal(string hash, bool refreshWhenDownloaded = true, Action <string, bool> songDownloaded = null, Action <string, float> downloadProgressChanged = null, string customHostUrl = null) { var songUrl = $"{beatSaverDownloadUrl}{hash}.zip"; if (!string.IsNullOrEmpty(customHostUrl)) { songUrl = $"{customHostUrl}{hash.ToUpper()}.zip"; } UnityWebRequest www = UnityWebRequest.Get(songUrl); bool timeout = false; float time = 0f; float lastProgress = 0f; www.SetRequestHeader("user-agent", SharedConstructs.Name); UnityWebRequestAsyncOperation asyncRequest = www.SendWebRequest(); while (!asyncRequest.isDone || asyncRequest.progress < 1f) { yield return(null); time += Time.deltaTime; if (time >= 15f && asyncRequest.progress == 0f) { www.Abort(); timeout = true; } if (lastProgress != asyncRequest.progress) { lastProgress = asyncRequest.progress; downloadProgressChanged?.Invoke($"custom_level_{hash.ToUpper()}", asyncRequest.progress); } } if (www.isNetworkError || www.isHttpError || timeout) { Logger.Error($"Error downloading song {hash}: {www.error}"); songDownloaded?.Invoke($"custom_level_{hash.ToUpper()}", false); } else { string zipPath = ""; string customSongsPath = CustomLevelPathHelper.customLevelsDirectoryPath; string customSongPath = ""; byte[] data = www.downloadHandler.data; try { customSongPath = customSongsPath + "/" + hash + "/"; zipPath = customSongPath + hash + ".zip"; if (!Directory.Exists(customSongPath)) { Directory.CreateDirectory(customSongPath); } File.WriteAllBytes(zipPath, data); } catch (Exception e) { Logger.Error($"Error writing zip: {e}"); songDownloaded?.Invoke($"custom_level_{hash.ToUpper()}", false); yield break; } try { ZipFile.ExtractToDirectory(zipPath, customSongPath); } catch (Exception e) { Logger.Error($"Unable to extract ZIP! Exception: {e}"); songDownloaded?.Invoke($"custom_level_{hash.ToUpper()}", false); yield break; } try { File.Delete(zipPath); } catch (IOException e) { Logger.Warning($"Unable to delete zip! Exception: {e}"); yield break; } Logger.Success($"Downloaded!"); if (refreshWhenDownloaded) { Action <Loader, ConcurrentDictionary <string, CustomPreviewBeatmapLevel> > songsLoaded = null; songsLoaded = (_, __) => { Loader.SongsLoadedEvent -= songsLoaded; songDownloaded?.Invoke($"custom_level_{hash.ToUpper()}", true); }; Loader.SongsLoadedEvent += songsLoaded; Loader.Instance.RefreshSongs(false); } else { songDownloaded?.Invoke($"custom_level_{hash.ToUpper()}", true); } } }
public UnityWebRequestAsyncOperationAwaiter(UnityWebRequestAsyncOperation asyncOperation) { this.asyncOperation = asyncOperation; }
protected IEnumerator OnDownTask(string url, string filePath, System.Action <float> callBack = null) { isRunning = true; isDone = false; progress = 0f; isStop = false; // ============================================ bool isError = false; // 默认没有错误 if (string.IsNullOrEmpty(url) == false && string.IsNullOrEmpty(filePath) == false) { var headRequest = UnityWebRequest.Head(url); // Get UnityWebRequestAsyncOperation requestAsync = headRequest.SendWebRequest(); yield return(requestAsync); isError = HasDownLoadError(headRequest); if (isError == false) { var totalLength = long.Parse(headRequest.GetResponseHeader("Content-Length")); var dirPath = Path.GetDirectoryName(filePath); if (Directory.Exists(dirPath) == false) { Directory.CreateDirectory(dirPath); } FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); var fileLength = fs.Length; if (fileLength < totalLength) { fs.Seek(fileLength, SeekOrigin.Begin); var request = UnityWebRequest.Get(url); if (isRangeEnd_) { request.SetRequestHeader("Range", "bytes=" + fileLength + "-"); } else { request.SetRequestHeader("Range", "bytes=" + fileLength + "-" + totalLength); } request.SendWebRequest(); var index = 0; while (request.isDone == false) { isError = HasDownLoadError(request); if (isError) { break; } if (isStop) { break; } yield return(null); Progressing(callBack, totalLength, fs, ref fileLength, request, ref index);; } if (fileLength < totalLength) { Progressing(null, totalLength, fs, ref fileLength, request, ref index); } request.Dispose(); request = null; } else { progress = 1f; } fs.Flush(); fs.Close(); fs.Dispose(); fs = null; } headRequest.Dispose(); headRequest = null; } isRunning = false; System.GC.Collect(); if (isError) { progress = 0f; isError = false; if (callBack != null) { callBack(ErrorCode_DownLoadFail); } } else if (isStop) { progress = 0f; isStop = false; if (callBack != null) { callBack(ErrorCode_DownLoadStop); } } else { if (progress >= 1f) { progress = 0f; isDone = true; if (callBack != null) { callBack(1f); } } } }
public override void LogIssue(BugReporterPlugin.IssueEntry issue) { issue.description = issue.description.Replace("\n", "\\n"); StringBuilder data = new StringBuilder(); data.AppendFormat("{{\"title\": \"{0}\", \"body\": \"{1}\"", issue.title, issue.description); if (issue.assignees.Length > 0) { data.Append(",\"assignees\":["); for (int i = 0; i < issue.assignees.Length; ++i) { data.AppendFormat("\"{0}\"", issue.assignees[i].name); if (i != issue.assignees.Length - 1) { data.Append(","); } } data.Append("]"); } if (issue.labels.Length > 0) { data.Append(",\"labels\":["); for (int i = 0; i < issue.labels.Length; ++i) { data.AppendFormat("\"{0}\"", issue.labels[i]); if (i != issue.labels.Length - 1) { data.Append(","); } } data.Append("]"); } data.Append("}"); var settings = BugReporterPlugin.settings.GetBackendSettings(backendName); var request = new UnityWebRequest(baseURL + "/repos/" + settings.projectPath + "/issues", "POST"); request.SetRequestHeader("Accept", "application/vnd.github.v3+json"); request.SetRequestHeader("Authorization", "token " + _token); request.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(data.ToString())); request.uploadHandler.contentType = "application/json"; request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); var async = request.SendWebRequest(); async.completed += op => { UnityWebRequestAsyncOperation asyncop = op as UnityWebRequestAsyncOperation; if (asyncop.webRequest.isHttpError || asyncop.webRequest.responseCode != 201) { Debug.LogError("couldn't Post issue to repo " + settings.projectPath); Debug.LogError("Error code : " + async.webRequest.responseCode + "\n Error:\n" + asyncop.webRequest.downloadHandler.text); } else { Debug.Log("Issue posted successfully"); } }; }
private void StartGetRequest(string url) { m_Request = UnityWebRequest.Get(url); m_Request.downloadHandler = new DownloadHandlerBuffer(); m_WebRequestAsyncOp = m_Request.SendWebRequest(); }
public void Download(CancellationToken cancellationToken) { try { _logger.LogDebug("Downloading..."); _logger.LogTrace("url = " + _url); _logger.LogTrace("bufferSize = " + BufferSize); _logger.LogTrace("bytesRange = " + (_bytesRange.HasValue ? _bytesRange.Value.Start + "-" + _bytesRange.Value.End : "(none)")); _logger.LogTrace("timeout = " + _timeout); Assert.MethodCalledOnlyOnce(ref _downloadHasBeenCalled, "Download"); UnityWebRequest request = null; Exception dataAvailableException = null; DateTime lastDataAvailable = DateTime.Now; UnityDispatcher.Invoke(() => { request = new UnityWebRequest(); request.uri = new Uri(_url); request.timeout = 0; if (_bytesRange.HasValue) { var bytesRangeEndText = _bytesRange.Value.End >= 0L ? _bytesRange.Value.End.ToString() : string.Empty; request.SetRequestHeader( "Range", "bytes=" + _bytesRange.Value.Start + "-" + bytesRangeEndText); } request.downloadHandler = new Handler((data, length) => { lastDataAvailable = DateTime.Now; if (DataAvailable != null && dataAvailableException == null) { try { DataAvailable.Invoke(data, length); } catch (Exception e) { dataAvailableException = e; } } }); }).WaitOne(); using (request) { using (request.downloadHandler) { UnityWebRequestAsyncOperation op = null; UnityDispatcher.Invoke(() => { op = request.SendWebRequest(); }).WaitOne(); bool requestIsDone = false; bool responseCodeHandled = false; while (!requestIsDone) { cancellationToken.ThrowIfCancellationRequested(); if ((DateTime.Now - lastDataAvailable).TotalMilliseconds > _timeout) { throw new ConnectionFailureException("Timeout."); } long requestResponseCode = 0; string requestError = null; UnityDispatcher.Invoke(() => { requestIsDone = request.isDone; requestResponseCode = request.responseCode; requestError = request.error; }).WaitOne(); if (requestError != null) { throw new ConnectionFailureException(requestError); } if (requestResponseCode > 0 && !responseCodeHandled) { _logger.LogDebug("Received response from server."); _logger.LogTrace("statusCode = " + requestResponseCode); if (Is2XXStatus((HttpStatusCode)requestResponseCode)) { _logger.LogDebug("Successful response. Reading response stream..."); } else if (Is4XXStatus((HttpStatusCode)requestResponseCode)) { throw new DataNotAvailableException(string.Format( "Request data for {0} is not available (status: {1})", _url, (HttpStatusCode)request.responseCode)); } else { throw new ServerErrorException(string.Format( "Server has experienced some issues with request for {0} which resulted in {1} status code.", _url, (HttpStatusCode)requestResponseCode)); } responseCodeHandled = true; } if (dataAvailableException != null) { throw dataAvailableException; } System.Threading.Thread.Sleep(100); } if (dataAvailableException != null) { throw dataAvailableException; } _logger.LogDebug("Stream has been read."); } } _logger.LogDebug("Downloading finished."); } catch (WebException webException) { _logger.LogError("Downloading has failed.", webException); throw new ConnectionFailureException( string.Format("Connection to server has failed while requesting {0}", _url), webException); } catch (Exception e) { _logger.LogError("Downloading has failed.", e); throw; } }
public static UnityWebRequestAsyncOperationAwaiter GetAwaiter(this UnityWebRequestAsyncOperation asyncOperation) { Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); return(new UnityWebRequestAsyncOperationAwaiter(asyncOperation)); }
public AgonesAsyncOperationWrapper(UnityWebRequestAsyncOperation unityOp) { AsyncOp = unityOp; }
public UnityWebRequestAsyncOperationAwaiter(UnityWebRequestAsyncOperation asyncOperation) { this.asyncOperation = asyncOperation; this.continuationAction = null; }
public void OnDownloadError() { m_WebRequestAsyncOperation.webRequest.Dispose(); m_WebRequestAsyncOperation = null; }
public static IAwaiter <UnityWebRequest> GetAwaiter(this UnityWebRequestAsyncOperation target) { return(new AsyncOperationAwaiter <UnityWebRequestAsyncOperation, UnityWebRequest>(target, (request) => request.webRequest)); }
public UnityWebRequestAwaiter(UnityWebRequestAsyncOperation asyncOp) { this.asyncOp = asyncOp; asyncOp.completed += OnRequestCompleted; }
private WebRequestAsyncOperation SendWebRequest <T>( T requestType, string url, DownloadHandler downloadHandler, Action <UnityWebRequest> OnSuccess, Action <UnityWebRequest> OnFail, int requestAttemps, int timeout, bool disposeOnCompleted, Dictionary <string, string> headers = null ) where T : IWebRequest { int remainingAttemps = Mathf.Clamp(requestAttemps, 1, requestAttemps); UnityWebRequest request = requestType.CreateWebRequest(url); request.timeout = timeout; if (headers != null) { foreach (var item in headers) { request.SetRequestHeader(item.Key, item.Value); } } if (downloadHandler != null) { request.downloadHandler = downloadHandler; } WebRequestAsyncOperation resultOp = new WebRequestAsyncOperation(request); resultOp.disposeOnCompleted = disposeOnCompleted; ongoingWebRequests.Add(resultOp); UnityWebRequestAsyncOperation requestOp = resultOp.webRequest.SendWebRequest(); requestOp.completed += (asyncOp) => { if (!resultOp.isDisposed) { if (resultOp.webRequest.WebRequestSucceded()) { OnSuccess?.Invoke(resultOp.webRequest); resultOp.SetAsCompleted(true); } else if (!resultOp.webRequest.WebRequestAborted() && resultOp.webRequest.WebRequestServerError()) { remainingAttemps--; if (remainingAttemps > 0) { Debug.LogWarning($"Retrying web request: {url} ({remainingAttemps} attemps remaining)"); resultOp.Dispose(); resultOp = SendWebRequest(requestType, url, downloadHandler, OnSuccess, OnFail, remainingAttemps, timeout, disposeOnCompleted); } else { OnFail?.Invoke(resultOp.webRequest); resultOp.SetAsCompleted(false); } } else { OnFail?.Invoke(resultOp.webRequest); resultOp.SetAsCompleted(false); } } ongoingWebRequests.Remove(resultOp); }; return(resultOp); }
protected IEnumerator LoadAssetBundleWithDeps(string baseUrl, string hash, Action OnSuccess, Action OnFail) { string finalUrl = baseUrl + hash; if (failedRequestUrls.Contains(finalUrl)) { OnFail?.Invoke(); yield break; } yield return(WaitForConcurrentRequestsSlot()); RegisterConcurrentRequest(); #if UNITY_EDITOR assetBundleRequest = UnityWebRequestAssetBundle.GetAssetBundle(finalUrl, Hash128.Compute(hash)); #else //NOTE(Brian): Disable in build because using the asset bundle caching uses IDB. assetBundleRequest = UnityWebRequestAssetBundle.GetAssetBundle(finalUrl); #endif asyncOp = assetBundleRequest.SendWebRequest(); if (!DependencyMapLoadHelper.dependenciesMap.ContainsKey(hash)) { CoroutineStarter.Start(DependencyMapLoadHelper.GetDepMap(baseUrl, hash)); } yield return(DependencyMapLoadHelper.WaitUntilDepMapIsResolved(hash)); if (DependencyMapLoadHelper.dependenciesMap.ContainsKey(hash)) { using (var it = DependencyMapLoadHelper.dependenciesMap[hash].GetEnumerator()) { while (it.MoveNext()) { var dep = it.Current; var promise = new AssetPromise_AB(baseUrl, dep, containerTransform); AssetPromiseKeeper_AB.i.Keep(promise); dependencyPromises.Add(promise); } } } while (!asyncOp.isDone) { yield return(null); } //NOTE(Brian): For some reason, another coroutine iteration can be triggered after Cleanup(). // So assetBundleRequest can be null here. if (assetBundleRequest == null) { OnFail?.Invoke(); yield break; } if (!assetBundleRequest.WebRequestSucceded()) { Debug.Log($"Request failed? {assetBundleRequest.error} ... {finalUrl}"); failedRequestUrls.Add(finalUrl); assetBundleRequest.Abort(); assetBundleRequest = null; OnFail?.Invoke(); yield break; } UnregisterConcurrentRequest(); foreach (var promise in dependencyPromises) { yield return(promise); } AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(assetBundleRequest); if (assetBundle == null || asset == null) { assetBundleRequest.Abort(); assetBundleRequest = null; OnFail?.Invoke(); failedRequestUrls.Add(finalUrl); yield break; } asset.ownerAssetBundle = assetBundle; asset.assetBundleAssetName = assetBundle.name; assetBundlesLoader.MarkAssetBundleForLoad(asset, assetBundle, containerTransform, OnSuccess, OnFail); }
public static UniTask <UnityWebRequest> ToUniTask(this UnityWebRequestAsyncOperation asyncOperation) { return(new UniTask <UnityWebRequest>(GetAwaiter(asyncOperation))); }
void GetProgress(NetCtrlManager.RequestHandler r, UnityWebRequestAsyncOperation a, string info) { progress = a.progress; // Debug.Log(request.downloadProgress); }
public void FetchUserInfo(int timeout, Action <Response <List <UserData> > > OnComplete) { if (tokenData == null) { throw new Exception("User has not logged in"); } UnityWebRequestAsyncOperation op = StartRequest(USER_INFO_URL, "POST", new Dictionary <string, object>() { { "idToken", tokenData.IdToken } }, timeout); op.completed += ((ao) => HandleFirebaseResponse(op, (res) => { if (res.success) { Dictionary <string, object> map = Json.Deserialize(res.data) as Dictionary <string, object>; List <object> userDatas = Json.Deserialize(Json.Serialize(map["users"])) as List <object>; List <UserData> dataToReturn = new List <UserData>(); for (int i = 0; i < userDatas.Count; i++) { Dictionary <string, object> userMap = Json.Deserialize(Json.Serialize(userDatas[i])) as Dictionary <string, object>; UserData ud = new UserData(); ud.createdAt = userMap.ContainsKey("createdAt") ? long.Parse(userMap["createdAt"].ToString()) : 0L; ud.customAuth = userMap.ContainsKey("customAuth") ? bool.Parse(userMap["customAuth"].ToString()) : false; ud.disabled = userMap.ContainsKey("disabled") ? bool.Parse(userMap["disabled"].ToString()) : false; ud.displayName = userMap.ContainsKey("displayName") ? userMap["displayName"].ToString() : null; ud.email = userMap.ContainsKey("email") ? userMap["email"].ToString() : null; ud.emailVerified = userMap.ContainsKey("emailVerified") ? bool.Parse(userMap["emailVerified"].ToString()) : false; ud.lastLoginAt = userMap.ContainsKey("lastLoginAt") ? long.Parse(userMap["lastLoginAt"].ToString()) : 0L; ud.localId = userMap.ContainsKey("localId") ? userMap["localId"].ToString() : null; ud.passwordUpdatedAt = userMap.ContainsKey("passwordUpdatedAt") ? long.Parse(userMap["passwordUpdatedAt"].ToString()) : 0L; ud.photoUrl = userMap.ContainsKey("photoUrl") ? userMap["photoUrl"].ToString() : null; ud.validSince = userMap.ContainsKey("photoUrl") ? userMap["validSince"].ToString() : null; if (userMap.ContainsKey("providerUserInfo")) { ud.providerUserInfo = new List <ProviderInfo>(); List <object> providers = Json.Deserialize(Json.Serialize(userMap["providerUserInfo"])) as List <object>; for (int j = 0; j < providers.Count; j++) { ProviderInfo providerInfo = new ProviderInfo(); Dictionary <string, object> obj = Json.Deserialize(Json.Serialize(providers[j])) as Dictionary <string, object>; providerInfo.federatedId = obj["federatedId"].ToString(); providerInfo.providerId = obj["providerId"].ToString(); ud.providerUserInfo.Add(providerInfo); } } dataToReturn.Add(ud); } if (OnComplete != null) { OnComplete(new Response <List <UserData> >("success", true, (int)op.webRequest.responseCode, dataToReturn)); } } else { if (OnComplete != null) { OnComplete(new Response <List <UserData> >(res.message, false, res.code, null)); } } })); }