From 35bc42ae24ad5a4bfcd93fb102e0f6a0ad779b3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=AB=E9=9B=A8?= <737345039@qq.com> Date: Wed, 4 Jan 2023 19:45:52 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=98=BE=E7=A4=BA=E5=90=8E=E5=8F=B0?= =?UTF-8?q?=E4=B8=8B=E8=BD=BD=E8=BF=9B=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 输出至一键长草的UI Log --- src/MaaWpfGui/Helper/LogItemViewModel.cs | 5 +- src/MaaWpfGui/Helper/UILogColor.cs | 5 + src/MaaWpfGui/Main/VersionUpdateViewModel.cs | 107 +++++++++++++++++-- src/MaaWpfGui/Res/Localizations/en-us.xaml | 1 + src/MaaWpfGui/Res/Localizations/ko-kr.xaml | 1 + src/MaaWpfGui/Res/Localizations/zh-cn.xaml | 1 + 6 files changed, 111 insertions(+), 9 deletions(-) diff --git a/src/MaaWpfGui/Helper/LogItemViewModel.cs b/src/MaaWpfGui/Helper/LogItemViewModel.cs index e324380ec3..836463c7bb 100644 --- a/src/MaaWpfGui/Helper/LogItemViewModel.cs +++ b/src/MaaWpfGui/Helper/LogItemViewModel.cs @@ -27,9 +27,10 @@ namespace MaaWpfGui /// The content. /// The font color. /// The font weight. - public LogItemViewModel(string content, string color = UILogColor.Message, string weight = "Regular") + /// The content in time column. + public LogItemViewModel(string content, string color = UILogColor.Message, string weight = "Regular", string timeColumnContent = null) { - Time = DateTime.Now.ToString("MM'-'dd' 'HH':'mm':'ss"); + Time = string.Concat(DateTime.Now.ToString("MM'-'dd' 'HH':'mm':'ss"), "\n", timeColumnContent); Content = content; Color = color; Weight = weight; diff --git a/src/MaaWpfGui/Helper/UILogColor.cs b/src/MaaWpfGui/Helper/UILogColor.cs index a4dcea6bcf..feefac252b 100644 --- a/src/MaaWpfGui/Helper/UILogColor.cs +++ b/src/MaaWpfGui/Helper/UILogColor.cs @@ -52,5 +52,10 @@ namespace MaaWpfGui /// The recommended color for robot operator logs. /// public const string RobotOperator = "DarkGray"; + + /// + /// The recommended color for file downloading or downloaded or download failed. + /// + public const string Download = "BlueViolet"; } } diff --git a/src/MaaWpfGui/Main/VersionUpdateViewModel.cs b/src/MaaWpfGui/Main/VersionUpdateViewModel.cs index f27a791b7f..e0cf710b77 100644 --- a/src/MaaWpfGui/Main/VersionUpdateViewModel.cs +++ b/src/MaaWpfGui/Main/VersionUpdateViewModel.cs @@ -403,6 +403,7 @@ namespace MaaWpfGui Localization.GetString("NewVersionFoundButNoPackageTitle")); if (goDownload) { + OutputDownloadProgress(downloading: false, output: Localization.GetString("NewVersionDownloadPreparing")); toast.AppendContentText(Localization.GetString("NewVersionFoundDescDownloading")); } @@ -426,6 +427,7 @@ namespace MaaWpfGui if (!goDownload || string.IsNullOrWhiteSpace(UpdatePackageName)) { + OutputDownloadProgress(string.Empty); return CheckUpdateRetT.NoNeedToUpdate; } @@ -456,6 +458,7 @@ namespace MaaWpfGui if (DownloadGithubAssets(url, _assetsObject, downloader)) { + OutputDownloadProgress(downloading: false, output: Localization.GetString("NewVersionDownloadCompletedTitle")); downloaded = true; break; } @@ -464,6 +467,7 @@ namespace MaaWpfGui if (!downloaded) { + OutputDownloadProgress(downloading: false, output: Localization.GetString("NewVersionDownloadFailedTitle")); Execute.OnUIThread(() => { using var toast = new ToastNotification(Localization.GetString("NewVersionDownloadFailedTitle")); @@ -663,9 +667,13 @@ namespace MaaWpfGui httpWebResponse.Close(); return responseContent; } - catch (Exception info) + catch (WebException) { - Console.WriteLine(info.Message); + return null; + } + catch (Exception e) + { + Logger.Error(e.ToString(), MethodBase.GetCurrentMethod().Name); return null; } } @@ -700,6 +708,7 @@ namespace MaaWpfGui private bool DownloadGithubAssets(string url, JObject assetsObject, Downloader downloader = Downloader.Native, string saveTo = null) { + _taskQueueViewModel = _container.Get(); return DownloadFile( url: url, fileName: assetsObject["name"].ToString(), contentType: @@ -739,10 +748,16 @@ namespace MaaWpfGui returned = DownloadFileForAria2(url: url, saveTo: fileDir, fileName: fileNameWithTemp, proxy); break; } + + OutputDownloadProgress(string.Empty); } - catch (Exception info) + catch (WebException) { - Console.WriteLine(info.Message); + returned = false; + } + catch (Exception e) + { + Logger.Error(e.ToString(), MethodBase.GetCurrentMethod().Name); returned = false; } @@ -783,8 +798,16 @@ namespace MaaWpfGui }, EnableRaisingEvents = true, }; + aria2Process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => + { + if (e.Data != null && e.Data.StartsWith("[")) + { + OutputDownloadProgress(e.Data); + } + }); aria2Process.Start(); + aria2Process.BeginOutputReadLine(); aria2Process.WaitForExit(); var exit_code = aria2Process.ExitCode; aria2Process.Close(); @@ -801,6 +824,8 @@ namespace MaaWpfGui /// 是否成功 private static bool DownloadFileForCSharpNative(string url, string filePath, string contentType = null, string proxy = "") { + bool downloaded = false; + // 创建 Http 请求 var httpWebRequest = WebRequest.Create(url) as HttpWebRequest; @@ -814,13 +839,81 @@ namespace MaaWpfGui } // 获取输入输出流 - using (var responseStream = httpWebRequest.GetResponse().GetResponseStream()) + using (var response = httpWebRequest.GetResponse()) { + using var responseStream = response.GetResponseStream(); using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write); - responseStream.CopyTo(fileStream); + + // 记录初始化 + long value = 0; + int valueInOneSecond = 0; + long fileMaximum = response.ContentLength; + DateTime beforDT = DateTime.Now; + OutputDownloadProgress(); + + // 输入输出初始化 + byte[] buffer = new byte[81920]; + int byteLen = responseStream.Read(buffer, 0, buffer.Length); + + while (byteLen > 0) + { + // 记录 + valueInOneSecond += byteLen; + double ts = DateTime.Now.Subtract(beforDT).TotalSeconds; + if (ts > 1) + { + beforDT = DateTime.Now; + value += valueInOneSecond; + OutputDownloadProgress(value, fileMaximum, valueInOneSecond, ts); + valueInOneSecond = 0; + } + + // 输入输出 + fileStream.Write(buffer, 0, byteLen); + byteLen = responseStream.Read(buffer, 0, buffer.Length); + } + + downloaded = true; } - return true; + return downloaded; + } + + private static TaskQueueViewModel _taskQueueViewModel = null; + + private static void OutputDownloadProgress(long value = 0, long maximum = 1, int len = 0, double ts = 1) + { + OutputDownloadProgress( + string.Format("[{0:F}MiB/{1:F}MiB({2}%) {3:F} KiB/s]", + value / 1048576.0, + maximum / 1048576.0, + value / maximum * 100, + len / ts / 1024.0)); + } + + private static void OutputDownloadProgress(string output, bool downloading = true) + { + if (_taskQueueViewModel == null) + { + return; + } + + Application.Current.Dispatcher.Invoke(() => + { + // _taskQueueViewModel.LogItemViewModels.Add(log); + if (_taskQueueViewModel.LogItemViewModels.Count > 0 && + _taskQueueViewModel.LogItemViewModels[0].Color == UILogColor.Download) + { + _taskQueueViewModel.LogItemViewModels.RemoveAt(0); + } + + if (!string.IsNullOrEmpty(output)) + { + var log = new LogItemViewModel(output, UILogColor.Download, timeColumnContent: + downloading ? Localization.GetString("NewVersionFoundDescDownloading") : string.Empty); + _taskQueueViewModel.LogItemViewModels.Insert(0, log); + } + }); } private bool isDebugVersion(string version = null) diff --git a/src/MaaWpfGui/Res/Localizations/en-us.xaml b/src/MaaWpfGui/Res/Localizations/en-us.xaml index a252794288..0445965ddc 100644 --- a/src/MaaWpfGui/Res/Localizations/en-us.xaml +++ b/src/MaaWpfGui/Res/Localizations/en-us.xaml @@ -159,6 +159,7 @@ Failed to get release note. The new version is being built, please try again later. + Preparing to download update package... Update Package Download Failed Please download the zip file manually and place it in the directory. Update Package Download Completed diff --git a/src/MaaWpfGui/Res/Localizations/ko-kr.xaml b/src/MaaWpfGui/Res/Localizations/ko-kr.xaml index 3eb9d44f40..0071cfeabf 100644 --- a/src/MaaWpfGui/Res/Localizations/ko-kr.xaml +++ b/src/MaaWpfGui/Res/Localizations/ko-kr.xaml @@ -158,6 +158,7 @@ 릴리즈 노트를 받아오지 못했습니다. 새로운 버전이 빌드되는 중입니다. 다음에 다시 시도해 주세요. + 업데이트 패키지 다운로드 준비 중... 업데이트 패키지 다운로드 실패 ZIP 파일을 수동으로 다운로드해 폴더 안에 놓아 주세요. 업데이트 패키지 다운로드 완료 diff --git a/src/MaaWpfGui/Res/Localizations/zh-cn.xaml b/src/MaaWpfGui/Res/Localizations/zh-cn.xaml index 53de1c8081..4679d1baac 100644 --- a/src/MaaWpfGui/Res/Localizations/zh-cn.xaml +++ b/src/MaaWpfGui/Res/Localizations/zh-cn.xaml @@ -159,6 +159,7 @@ 获取更新信息失败 我知道你很急但你先别急.jpg + 正在准备下载更新包…… 新版本下载失败 请尝试手动下载后,将压缩包放到目录下_(:з」∠)_ 新版本下载完成