feat: 显示后台下载进度

输出至一键长草的UI Log
This commit is contained in:
枫雨
2023-01-04 19:45:52 +08:00
parent 563bdaab1e
commit 35bc42ae24
6 changed files with 111 additions and 9 deletions

View File

@@ -27,9 +27,10 @@ namespace MaaWpfGui
/// <param name="content">The content.</param>
/// <param name="color">The font color.</param>
/// <param name="weight">The font weight.</param>
public LogItemViewModel(string content, string color = UILogColor.Message, string weight = "Regular")
/// <param name="timeColumnContent">The content in time column.</param>
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;

View File

@@ -52,5 +52,10 @@ namespace MaaWpfGui
/// The recommended color for robot operator logs.
/// </summary>
public const string RobotOperator = "DarkGray";
/// <summary>
/// The recommended color for file downloading or downloaded or download failed.
/// </summary>
public const string Download = "BlueViolet";
}
}

View File

@@ -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<TaskQueueViewModel>();
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
/// <returns>是否成功</returns>
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)

View File

@@ -159,6 +159,7 @@
<system:String x:Key="GetReleaseNoteFailed">Failed to get release note.</system:String>
<system:String x:Key="NewVersionIsBeingBuilt">The new version is being built, please try again later.</system:String>
<system:String x:Key="NewVersionDownloadPreparing">Preparing to download update package...</system:String>
<system:String x:Key="NewVersionDownloadFailedTitle">Update Package Download Failed</system:String>
<system:String x:Key="NewVersionDownloadFailedDesc">Please download the zip file manually and place it in the directory.</system:String>
<system:String x:Key="NewVersionDownloadCompletedTitle">Update Package Download Completed</system:String>

View File

@@ -158,6 +158,7 @@
<system:String x:Key="GetReleaseNoteFailed">릴리즈 노트를 받아오지 못했습니다.</system:String>
<system:String x:Key="NewVersionIsBeingBuilt">새로운 버전이 빌드되는 중입니다. 다음에 다시 시도해 주세요.</system:String>
<system:String x:Key="NewVersionDownloadPreparing">업데이트 패키지 다운로드 준비 중...</system:String>
<system:String x:Key="NewVersionDownloadFailedTitle">업데이트 패키지 다운로드 실패</system:String>
<system:String x:Key="NewVersionDownloadFailedDesc">ZIP 파일을 수동으로 다운로드해 폴더 안에 놓아 주세요.</system:String>
<system:String x:Key="NewVersionDownloadCompletedTitle">업데이트 패키지 다운로드 완료</system:String>

View File

@@ -159,6 +159,7 @@
<system:String x:Key="GetReleaseNoteFailed">获取更新信息失败</system:String>
<system:String x:Key="NewVersionIsBeingBuilt">我知道你很急但你先别急.jpg</system:String>
<system:String x:Key="NewVersionDownloadPreparing">正在准备下载更新包……</system:String>
<system:String x:Key="NewVersionDownloadFailedTitle">新版本下载失败</system:String>
<system:String x:Key="NewVersionDownloadFailedDesc">请尝试手动下载后将压缩包放到目录下_(:з」∠)_</system:String>
<system:String x:Key="NewVersionDownloadCompletedTitle">新版本下载完成</system:String>