private void HttpDownloadProgress(int deltaBufferLength, byte[] deltaBuffer, bool isComplete) { if (deltaBufferLength > 0) { outStream.Write(deltaBuffer, 0, deltaBufferLength); } if (isComplete) { outStream.Close(); PatchFileInfo patchFile = needLoadPatchFiles.Dequeue(); refreshPatchFiles.FileAppend(PathUtil.LocalPatchFilesPath(), patchFile.ToString()); HttpPatch(); } else { //GLog.Log("deltaBufferLength:" + deltaBufferLength + " time " + Time.time); if (deltaBuffer == null || deltaBuffer.Length < 1) { } else { } } }
private void _DownloadAssets(string listFileName, string text, PreDownloader.DownlaodToComplete userCompleteCallback) { int num = 0; BackgroundInstall.DownloadAssets downloadAssets = new BackgroundInstall.DownloadAssets(listFileName); foreach (string current in this._ParseBundleList(text)) { PatchFileInfo patchFileInfo = PatchFinalList.Instance.GetPatchFileInfo(current); if (this._IsVersionCached(current, patchFileInfo.nVersion, patchFileInfo.bUseCustomCache)) { num++; } else { downloadAssets.requestFiles.Add(current); } } int num2 = downloadAssets.requestFiles.Count + num; BackgroundInstall.Progress progress = new BackgroundInstall.Progress(num2, num); BackgroundInstall.ms_ProgressCollection[listFileName] = progress; if (downloadAssets.requestFiles.Count > 0) { progress.downloading = true; if (Option.EnableTrace) { TsLog.Log("[PreDownload] Request( \"{0}\" ) => wait for downloads (Requests={1}, Cacheds={2}, Total={3})", new object[] { listFileName, downloadAssets.requestFiles.Count, num, num2 }); } downloadAssets.userCompleteCallback = userCompleteCallback; Helper.PreDownloadRequest(downloadAssets.requestFiles, new PostProcPerList(this._DownloadComplete_Assets), downloadAssets); } else { if (Option.EnableTrace) { TsLog.Log("[PreDownload] Request( \"{0}\" ) => Complete to download: All file is chached on disk. (Progress={1}%, CachedFiles={2}, Total={3})", new object[] { listFileName, (float)num / (float)num2 * 100f, num, num2 }); } if (userCompleteCallback != null) { userCompleteCallback(listFileName, (num != num2) ? ((float)num / (float)num2) : 1f); } } }
public void Load(string content) { if (string.IsNullOrEmpty(content)) { return; } StringReader textReader = new StringReader(content); string line; while (!string.IsNullOrEmpty(line = textReader.ReadLine())) { PatchFileInfo patchFileInfo = new PatchFileInfo(line); dic[patchFileInfo.ResPath] = patchFileInfo; count++; } }
private void downloadPatches_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if (patchQueue.Count != 0) { PatchFileInfo pfi = patchQueue.Dequeue(); WebClient downloadPatches = new WebClient(); downloadPatches.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadPatches_DownloadFileCompleted); downloadPatches.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadPatches_DownloadProgressChanged); downloadPatches.DownloadFileAsync(new Uri(pfi.url), pfi.file); } else { this.Invoke(new MakeVisibleInvisible(DownloadCompleted), new object[] { false }); } }
public void SetAssetPath(string aPath) { this.assetPath = aPath.ToLower(); string resFileName = string.Empty; if (this.assetPath[0] == '/') { resFileName = this.assetPath; } else { resFileName = "/" + this.assetPath; } this.m_kItem = PatchFinalList.Instance.GetPatchFileInfo(resFileName); if (this.m_kItem != null) { this.safeSize = this.m_kItem.nFileSize; } }
/// <summary> /// Builds kdtree for specific patch. /// Kdtree is built according to specified positions type and hierarchy level. /// </summary> private static KdIntersectionTree BuildKdTreeForPatch( string patchName, int level, PatchFileInfo info, OpcPaths paths, PositionsType posType, bool saveTriangles = false, bool saveKdTree = true, float maxTriangleSize = float.PositiveInfinity) { var path = Path.Combine(paths.PatchesSubDir, patchName); var patchGeometry = new TriangleSet(); //var patchGeometryTest = new TriangleSet(); if ((maxTriangleSize < float.PositiveInfinity) && (maxTriangleSize > 0.000001f)) { patchGeometry = PatchLoadingStrategy.LoadPatchTriangleSetWithoutOversizedTriangles(info, path, posType, maxTriangleSize); //patchGeometryTest = PatchLoadingStrategy.LoadPatchTriangleSet(info, path, posType); } else { patchGeometry = PatchLoadingStrategy.LoadPatchTriangleSet(info, path, posType); } KdIntersectionTree kdIntTree = new KdIntersectionTree(patchGeometry, KdIntersectionTree.BuildFlags.MediumIntersection | KdIntersectionTree.BuildFlags.Hierarchical); if (!saveTriangles) { kdIntTree.ObjectSet = null; } if (saveKdTree) { var kdTreePath = paths.GetKdTreePath(patchName, level, posType); kdIntTree.Save(kdTreePath); } return(kdIntTree); }
private void HttpPatch() { if (needLoadPatchFiles.Count > 0) { PatchFileInfo patchFileInfo = needLoadPatchFiles.Peek(); string fileUrl = Game.Instance.gameSetting.GetPatchRootPath() + patchFileInfo.ResPath.Trim(); string localFilePath = PathUtil.PatchPath + patchFileInfo.ResPath.Trim(); string localFileDirectory = Path.GetDirectoryName(localFilePath); if (!Directory.Exists(localFileDirectory)) { Directory.CreateDirectory(localFileDirectory); } outStream = new FileStream(localFilePath, FileMode.OpenOrCreate); HttpManager.Instance.LoadFile(fileUrl, HttpDownloadProgress); } else { PatchComplete(); } }
public static bool IsVersionCached(Protocol protocol, string path, bool markAsUsed) { path = path.ToLower(); string text = Option.GetProtocolRootPath(protocol) + path; string text2 = "/" + path; PatchFileInfo patchFileInfo = PatchFinalList.Instance.GetPatchFileInfo(text2); if (patchFileInfo == null) { TsLog.LogWarning("TsBundle.WWWItem.IsVersionCached Warning! - Key:{0}", new object[] { text2.ToString() }); return(false); } bool flag = TsCaching.IsVersionCached(text, patchFileInfo.nVersion, patchFileInfo.bUseCustomCache); if (flag && markAsUsed) { TsCaching.MarkAsUsed(text, patchFileInfo.nVersion, patchFileInfo.bUseCustomCache); } return(flag); }
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { bool anyDownloads = false; string loc = WoW.DataDirectory; if (!string.IsNullOrEmpty(loc) && Directory.Exists(loc)) { using (StreamReader reader = new StreamReader(tempPath)) { string line; while ((line = reader.ReadLine()) != null) { string[] ex = line.Split(' '); string path = Path.Combine(loc, ex[1]); bool proceed = true; if (File.Exists(path)) { //Compare MD5 Hashes using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (MD5 md5 = new MD5CryptoServiceProvider()) { byte[] retVal = md5.ComputeHash(fs); fs.Close(); StringBuilder sb = new StringBuilder(); foreach (byte b in retVal) { sb.Append(string.Format("{0:X2}", b)); } if (ex[2] == sb.ToString()) { proceed = false; } } } } if (proceed) { WebClient downloadPatches = new WebClient(); downloadPatches.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadPatches_DownloadFileCompleted); downloadPatches.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadPatches_DownloadProgressChanged); PatchFileInfo pfi = new PatchFileInfo(ex[0], path); object obj = pfi; downloadBar1.Invoke((MethodInvoker) delegate { downloadBar1.BarState = DownloadBar.DownloadBarState.Playable; }); if (!anyDownloads) { downloadPatches.DownloadFileAsync(new Uri(ex[0]), path, obj); } else { patchQueue.Enqueue(pfi); } anyDownloads = true; } } } } if (!anyDownloads) { this.Invoke(new MakeVisibleInvisible(DownloadCompleted), new object[] { false }); } else { this.Invoke(new MakeVisibleInvisible(DownloadCompleted), new object[] { true }); } }
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { _length = File.ReadAllLines(tempPath).Length; using (StreamReader reader = new StreamReader(tempPath)) { string line; while ((line = reader.ReadLine()) != null) { string[] ex = line.Split(char.Parse("#")); string path = SetPath(ex[1]); bool proceed = true; if (File.Exists(path)) { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); MD5 md5 = new MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(fs); fs.Close(); StringBuilder sb = new StringBuilder(); foreach (byte b in retVal) { sb.Append(string.Format("{0:X2}", b)); } if (ex[2] == sb.ToString()) { proceed = false; _count++; } } if (proceed) { string[] link = ex[0].Split(char.Parse("Ø")); long pingValue = long.MaxValue; string bestLink = link[0]; foreach (string curLink in link) { try { Ping ping = new Ping(); PingReply pingReply = ping.Send(curLink); if (pingReply.RoundtripTime < pingValue) { bestLink = curLink; pingValue = pingReply.RoundtripTime; } } catch (PingException exception) { Console.WriteLine(curLink + ": " + exception.Message); } } PatchFileInfo pfi = new PatchFileInfo(bestLink, path, ex[1], Convert.ToInt64(ex[3]), ex[2]); patchQueue.Enqueue(pfi); totalBytes += Convert.ToInt64(ex[3]); } } } while (patchQueue.Count != 0) { sw.Start(); anyDownloads = true; Dispatcher.Invoke(new MakeVisibleInvisible(DownloadCompleted), new object[] { true }); PatchFileInfo pfi = patchQueue.Dequeue(); long existLen = 0; bool append = false; string currFile = string.Format("{0}.{1}.upd", pfi.File, pfi.Md5Hash); var httpReq = (HttpWebRequest)WebRequest.Create(pfi.Url); if (File.Exists(currFile)) { FileInfo destinationFileInfo = new FileInfo(currFile); existLen = destinationFileInfo.Length; currentFileBytes += existLen; currentBytes += existLen; httpReq.AddRange((int)existLen); append = true; } var httpRes = (HttpWebResponse)httpReq.GetResponse(); Stream resStream = httpRes.GetResponseStream(); using (var file = (append == true) ? new FileStream(currFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite) : new FileStream(currFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { int bufferSize = 1024 * 4; var buffer = new byte[bufferSize]; int bytesReceived; while ((bytesReceived = resStream.Read(buffer, 0, buffer.Length)) != 0) { file.Write(buffer, 0, bytesReceived); try { Dispatcher.Invoke(new UpdateProgress(UpdateProgressbar), new object[] { 0, (int)bytesReceived, Convert.ToInt32(pfi.FileBytes) }); if (Properties.Settings.Default.downloadSpeedLimit > 0) { if (currentFileBytes2 * 1000L / sw.Elapsed.TotalMilliseconds > Properties.Settings.Default.downloadSpeedLimit) { long wakeElapsed = currentFileBytes2 * 1000L / Properties.Settings.Default.downloadSpeedLimit; int toSleep = (int)(wakeElapsed - sw.Elapsed.TotalMilliseconds); if (toSleep > 1) { try { Thread.Sleep(toSleep); } catch (ThreadAbortException) { } } } } } catch (Exception) { } } } _count++; File.Delete(pfi.File); File.Move(currFile, pfi.File); currentFileBytes = 0; currentFileBytes2 = 0; } Dispatcher.Invoke(new MakeVisibleInvisible(DownloadCompleted), new object[] { false }); anyDownloads = false; sw.Stop(); sw.Reset(); var fileGenerationDir = new DirectoryInfo(_gPath); fileGenerationDir.GetFiles("*.upd", SearchOption.AllDirectories).ToList().ForEach(file => file.Delete()); }
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { bool anyDownloads = false; string loc = WoW.DataDirectory; if (!string.IsNullOrEmpty(loc) && Directory.Exists(loc)) { using (StreamReader reader = new StreamReader(tempPath)) { string line; while ((line = reader.ReadLine()) != null) { string[] ex = line.Split(' '); string path = Path.Combine(loc, ex[1]); bool proceed = true; if (File.Exists(path)) { //Compare MD5 Hashes using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (MD5 md5 = new MD5CryptoServiceProvider()) { byte[] retVal = md5.ComputeHash(fs); fs.Close(); StringBuilder sb = new StringBuilder(); foreach (byte b in retVal) { sb.Append(string.Format("{0:X2}", b)); } if (ex[2] == sb.ToString()) { proceed = false; } } } } if (proceed) { WebClient downloadPatches = new WebClient(); downloadPatches.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadPatches_DownloadFileCompleted); downloadPatches.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadPatches_DownloadProgressChanged); PatchFileInfo pfi = new PatchFileInfo(ex[0], path); object obj = pfi; downloadBar1.Invoke((MethodInvoker)delegate { downloadBar1.BarState = DownloadBar.DownloadBarState.Playable; }); if (!anyDownloads) downloadPatches.DownloadFileAsync(new Uri(ex[0]), path, obj); else patchQueue.Enqueue(pfi); anyDownloads = true; } } } } if (!anyDownloads) this.Invoke(new MakeVisibleInvisible(DownloadCompleted), new object[] { false }); else this.Invoke(new MakeVisibleInvisible(DownloadCompleted), new object[] { true }); }
public void Add(PatchFileInfo patchFileInfo) { dic[patchFileInfo.ResPath] = patchFileInfo; count++; }
private void _DownloadComplete_Assets(List <WWWItem> downlaodList, object param) { BackgroundInstall.DownloadAssets downloadAssets = param as BackgroundInstall.DownloadAssets; if (downloadAssets == null) { TsLog.LogWarning("[PreDownload] download to complete ( <<unknown>>, downloads = {0} )", new object[] { downlaodList.Count }); return; } int count = downloadAssets.requestFiles.Count; int num = 0; StringBuilder stringBuilder = (!Option.EnableTrace) ? null : new StringBuilder(1024); if (stringBuilder != null) { stringBuilder.AppendFormat("[PreDownload] Download to complete ( PreDownloadListFile=\"{0}\", Requests={1}, Downloads={2} )", downloadAssets.listFileName, downloadAssets.requestFiles.Count, downlaodList.Count); stringBuilder.AppendLine(); stringBuilder.AppendLine("=================================================================================================="); Dictionary <string, WWWItem> dictionary = new Dictionary <string, WWWItem>(downlaodList.Count); foreach (WWWItem current in downlaodList) { dictionary[current.assetPath] = current; } foreach (string current2 in downloadAssets.requestFiles) { string text = (!dictionary.ContainsKey(current2)) ? "<<skipped>>" : "<<download>>"; PatchFileInfo patchFileInfo = PatchFinalList.Instance.GetPatchFileInfo(current2); if (patchFileInfo.nVersion != -1) { if (this._IsVersionCached(current2, patchFileInfo.nVersion, patchFileInfo.bUseCustomCache)) { num++; stringBuilder.AppendFormat(" \"{0}\" (version={1}, {2}) => chached", current2, patchFileInfo.nVersion, text); stringBuilder.AppendLine(); } else { stringBuilder.AppendFormat(" \"{0}\" (version={1}, {2}) => download to complete, but bundle-file is not cached.", current2, patchFileInfo.nVersion, text); stringBuilder.AppendLine(); } } else { stringBuilder.AppendFormat(" \"{0}\" ({1}) => not listed FinalPatchLIst", current2, text); stringBuilder.AppendLine(); } } stringBuilder.AppendLine("=================================================================================================="); stringBuilder.AppendFormat("Total = {0}, Downloads = {1}, Cached = {2}\r\n", count, downlaodList.Count, num); stringBuilder.AppendFormat("Downloads Rate = {0} %\r\n", 100f * (float)downlaodList.Count / (float)count); stringBuilder.AppendFormat("Cached Rate = {0} %\r\n", 100f * (float)num / (float)count); TsLog.Log(stringBuilder.ToString(), new object[0]); } float cachedRate = (count != 0) ? ((num != count) ? ((float)num / (float)count) : 1f) : 0f; BackgroundInstall.Progress progress; if (BackgroundInstall.ms_ProgressCollection.TryGetValue(downloadAssets.listFileName, out progress)) { progress.count = progress.total; progress.downloading = false; } if (downloadAssets.userCompleteCallback != null) { downloadAssets.userCompleteCallback(downloadAssets.listFileName, cachedRate); } }
private float _CachingReport(string listFileName, string assetListText, bool fullLog, StringBuilder targetLog) { int num = 0; Queue <KeyValuePair <string, int> > queue = new Queue <KeyValuePair <string, int> >(); Queue <KeyValuePair <string, int> > queue2 = new Queue <KeyValuePair <string, int> >(); Queue <string> queue3 = new Queue <string>(); if (targetLog != null) { targetLog.Length = 0; targetLog.AppendLine("=================================================================================================="); } foreach (string current in this._ParseBundleList(assetListText)) { PatchFileInfo patchFileInfo = PatchFinalList.Instance.GetPatchFileInfo(current); if (patchFileInfo.nVersion != -1) { if (this._IsVersionCached(current, patchFileInfo.nVersion, patchFileInfo.bUseCustomCache)) { queue.Enqueue(new KeyValuePair <string, int>(current, patchFileInfo.nVersion)); } else { queue2.Enqueue(new KeyValuePair <string, int>(current, patchFileInfo.nVersion)); } } else { queue3.Enqueue(current); if (Option.useCache) { TsLog.LogWarning("[PreDownload] IsCached( \"{0}\" ) : {1} => not listed in FinalPathList", new object[] { listFileName, current }); } } num++; } int count = queue.Count; int count2 = queue2.Count; if (targetLog != null) { if (fullLog) { while (queue.Count > 0) { KeyValuePair <string, int> keyValuePair = queue.Dequeue(); string key = keyValuePair.Key; int value = keyValuePair.Value; targetLog.AppendFormat(" \"{0}\" (version={1}) => OK (cached)", key, value); targetLog.AppendLine(); } } while (queue2.Count > 0) { KeyValuePair <string, int> keyValuePair2 = queue2.Dequeue(); string key2 = keyValuePair2.Key; int value2 = keyValuePair2.Value; targetLog.AppendFormat(" \"{0}\" (version={1}) => not cached", key2, value2); targetLog.AppendLine(); } while (queue3.Count > 0) { string arg = queue3.Dequeue(); targetLog.AppendFormat(" \"{0}\" => error, not listed in FinalPatchList", arg); targetLog.AppendLine(); } targetLog.AppendLine("=================================================================================================="); targetLog.AppendFormat("Total = {0}, Cached = {1}, Non-Cached = {2}\r\n", num, count, count2); targetLog.AppendFormat("Cached rate = {0}% ({1}/{2})", 100f * (float)count / (float)num, count, num); targetLog.AppendLine(); } if (BackgroundInstall.ms_ProgressCollection.ContainsKey(listFileName)) { BackgroundInstall.ms_ProgressCollection[listFileName].count = count; } else { BackgroundInstall.ms_ProgressCollection.Add(listFileName, new BackgroundInstall.Progress(num, count)); } return((count != num) ? ((float)count / (float)num) : 1f); }
private void _OnCompleteDownload(IDownloadedItem wItem, object obj) { if (wItem.canAccessString) { try { string safeString = wItem.safeString; NDataReader nDataReader = new NDataReader(); if (!nDataReader.LoadFrom(safeString)) { TsLog.LogWarning(string.Format("NDataReader.LoadFromText failed: {0}", safeString), new object[0]); return; } SortedDictionary <string, PatchFileInfo> sortedDictionary = new SortedDictionary <string, PatchFileInfo>(); StringBuilder stringBuilder = new StringBuilder(512); StringBuilder stringBuilder2 = new StringBuilder(512); StringBuilder stringBuilder3 = new StringBuilder(512); if (nDataReader.BeginSection("[FinalList2]")) { while (!nDataReader.IsEndOfSection()) { NDataReader.Row currentRow = nDataReader.GetCurrentRow(); if (currentRow.LineType == NDataReader.Row.TYPE.LINE_DATA) { stringBuilder.Length = 0; stringBuilder.Append(currentRow.GetColumn(0)); stringBuilder = PatchFinalList.ReplaceWord(stringBuilder, false); if (stringBuilder[0] == '?') { stringBuilder.Remove(0, 1); stringBuilder3.Length = 0; stringBuilder3.Append(stringBuilder.ToString()); } else { PatchFileInfo patchFileInfo = new PatchFileInfo(currentRow); stringBuilder2.Length = 0; stringBuilder2.AppendFormat("{0}/{1}", stringBuilder3, stringBuilder); stringBuilder2 = stringBuilder2.Replace("//", "/"); string text = stringBuilder2.ToString(); if (!text.Contains("duplicationfilelist")) { if (sortedDictionary.ContainsKey(text)) { PatchFileInfo patchFileInfo2 = new PatchFileInfo(); sortedDictionary.TryGetValue(text, out patchFileInfo2); TsLog.Log(string.Format("Warning - duplicated patch list item : {0} / already:{1} new:{2}", text, patchFileInfo2.nVersion, patchFileInfo.nVersion), new object[0]); if (patchFileInfo2.nVersion < patchFileInfo.nVersion) { sortedDictionary[text] = patchFileInfo; } } else { sortedDictionary.Add(text, patchFileInfo); } } } } nDataReader.NextLine(); } } NrTSingleton <AssetBundleURLInfo> .Instance.CollectBundleInfo(sortedDictionary.Keys); } catch (Exception arg) { TsLog.LogWarning(string.Format("The process failed: {0}", arg), new object[0]); } } NrTSingleton <AssetBundleURLInfo> .Instance.IsLoad = true; UnityEngine.Object.Destroy(base.gameObject); }
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { _length = File.ReadAllLines(_tempPath).Length; Console.WriteLine($@"-----------------------------------------"); Console.WriteLine($@"Start initialization in {DateTime.Now:HH:mm:ss.ffffff}."); Console.WriteLine($@"-----------------------------------------"); // Get map of downloaded files if (File.Exists(_updatePath)) { _filesCompleted = JsonSerializer <Dictionary <string, string> > .FromString( File.ReadAllText(_updatePath)); } using (var reader = new StreamReader(_tempPath)) { string line; while ((line = reader.ReadLine()) != null) { var ex = line.Split(char.Parse("#")); var path = Utilities.Updater.GetPath(_gPath, ex[1]); var pfi = new PatchFileInfo(ex[0], ex[1], path, Convert.ToInt64(ex[3]), ex[2]); Console.WriteLine($@"[{_count + 1:000}/{_length:000}] Start checking {pfi.Name}."); if (File.Exists(path)) { if (_filesCompleted.TryGetValue(pfi.Name, out var hash) && hash == pfi.Md5Hash) { // Ignore downloaded file _count++; Console.WriteLine($@"{pfi.Name} is updated. {_length - _count} more left."); continue; } var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); MD5 md5 = new MD5CryptoServiceProvider(); var retVal = md5.ComputeHash(fs); fs.Close(); var sb = new StringBuilder(); foreach (var b in retVal) { sb.Append($"{b:X2}"); } if (pfi.Md5Hash == sb.ToString()) { // Ignore matched file and add to completed map _filesCompleted[pfi.Name] = pfi.Md5Hash; _count++; Console.WriteLine($@"Done with {pfi.Name}. {_length - _count} more left."); SaveCurrentCompletedFiles(); continue; } } _filesCompleted.Remove(pfi.Name); _patchQueue.Enqueue(pfi); _totalBytes += pfi.FileBytes; } } Console.WriteLine($@"--------------------------------------"); Console.WriteLine($@"End initialization in {DateTime.Now:HH:mm:ss.ffffff}."); Console.WriteLine($@"--------------------------------------"); while (_patchQueue.Count != 0) { StopWatch.Start(); AnyDownloads = true; Dispatcher.Invoke(new MakeVisibleInvisible(DownloadCompleted), true); var pfi = _patchQueue.Dequeue(); var append = false; var currentFile = $"{pfi.File}.{pfi.Md5Hash}.upd"; var httpReq = (HttpWebRequest)WebRequest.Create(pfi.Url); if (File.Exists(currentFile)) { var destinationFileInfo = new FileInfo(currentFile); var existedLength = destinationFileInfo.Length; _currentFileBytes += existedLength; _currentBytes += existedLength; httpReq.AddRange((int)existedLength); append = true; } try { var httpRes = (HttpWebResponse)httpReq.GetResponse(); var resStream = httpRes.GetResponseStream(); using (var file = append ? new FileStream(currentFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite) : new FileStream(currentFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { const int bufferSize = 1024 * 4; var buffer = new byte[bufferSize]; int bytesReceived; while (resStream != null && (bytesReceived = resStream.Read(buffer, 0, buffer.Length)) != 0) { file.Write(buffer, 0, bytesReceived); try { Dispatcher.Invoke(new UpdateProgress(UpdateProgressbar), new object[] { 0, bytesReceived, Convert.ToInt32(pfi.FileBytes) }); if (Properties.Settings.Default.DownloadSpeedLimit > 0) { if (CurrentFileBytes2 * 1000L / StopWatch.Elapsed.TotalMilliseconds > Properties.Settings.Default.DownloadSpeedLimit) { var wakeElapsed = CurrentFileBytes2 * 1000L / Properties.Settings.Default.DownloadSpeedLimit; var toSleep = (int)(wakeElapsed - StopWatch.Elapsed.TotalMilliseconds); if (toSleep > 1) { try { Thread.Sleep(toSleep); } catch (ThreadAbortException) { } } } } } catch (Exception) { // ignored } } } _count++; File.Delete(pfi.File); File.Move(currentFile, pfi.File); _filesCompleted[pfi.Name] = pfi.Md5Hash; _currentFileBytes = 0; CurrentFileBytes2 = 0; SaveCurrentCompletedFiles(); } catch (Exception ex) { var message = ex.Message; if (ex is WebException) { message = $@"{pfi.Url}{Environment.NewLine}{Environment.NewLine}{ex.Message}"; } MessageBox.Show(message, ex.Source, MessageBoxButton.OK, MessageBoxImage.Error); } } Dispatcher.Invoke(new MakeVisibleInvisible(DownloadCompleted), false); AnyDownloads = false; StopWatch.Stop(); StopWatch.Reset(); new DirectoryInfo(_gPath).GetFiles("*.upd", SearchOption.AllDirectories).ToList().ForEach(file => file.Delete()); }
/// <summary> /// Loads level N kdtree. If level N kdtree does not exist it is built from rootpatch. /// </summary> public static KdIntersectionTree BuildOrLoadKdTreeN(OpcPaths opcPaths, PositionsType posType, PatchFileInfo patchFileInfo) { KdIntersectionTree kdiTree = null; var kdTreeNPatch = opcPaths.GetKdTreeNPath(posType); if (!StorageConfig.FileExists(kdTreeNPatch)) { kdiTree = KdTreeUtils.BuildKdTreeForPatch(opcPaths.RootPatchName, -1, patchFileInfo, opcPaths, posType, saveTriangles: true); kdiTree.Save(opcPaths.RootPatchName); } else { kdiTree = Load.As <KdIntersectionTree>(opcPaths.GetKdTreeNPath(posType)); } return(kdiTree); }