improve:自动更新

This commit is contained in:
2025-07-22 17:07:27 +08:00
parent 9491b48eb6
commit 0691293973
7 changed files with 412 additions and 27 deletions
@@ -78,6 +78,12 @@
Background="#f8fafc" BorderBrush="#cbd5e1" ToolTip="跳过此版本更新" Visibility="Visible" IsEnabled="True"/>
</ui:SimpleStackPanel>
</Border>
<!-- 下载进度条和状态 -->
<StackPanel x:Name="DownloadProgressPanel" Orientation="Vertical" HorizontalAlignment="Center" Margin="0,10,0,0" Visibility="Collapsed">
<ProgressBar x:Name="DownloadProgressBar" Width="360" Height="18" Minimum="0" Maximum="100" Value="0"/>
<TextBlock x:Name="DownloadProgressText" Text="正在下载..." FontSize="14" Foreground="#2563eb" HorizontalAlignment="Center" Margin="0,6,0,0"/>
</StackPanel>
</ui:SimpleStackPanel>
</Grid>
</ScrollViewer>
+119 -8
View File
@@ -7,6 +7,8 @@ using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using System.Threading.Tasks;
using System.IO;
namespace Ink_Canvas
{
@@ -129,16 +131,46 @@ namespace Ink_Canvas
LogHelper.WriteLogToFile("AutoUpdate | Update dialog buttons visibility ensured");
}
private void UpdateNowButton_Click(object sender, RoutedEventArgs e)
private async void UpdateNowButton_Click(object sender, RoutedEventArgs e)
{
LogHelper.WriteLogToFile("AutoUpdate | Update Now button clicked");
// 设置结果为立即更新
Result = UpdateResult.UpdateNow;
// 关闭窗口,返回到MainWindow处理后续下载和安装流程
DialogResult = true;
Close();
// 禁用按钮,显示进度条
UpdateNowButton.IsEnabled = false;
UpdateLaterButton.IsEnabled = false;
SkipVersionButton.IsEnabled = false;
DownloadProgressPanel.Visibility = Visibility.Visible;
DownloadProgressBar.Value = 0;
DownloadProgressText.Text = "正在准备下载...";
// 启动下载
bool downloadSuccess = false;
try
{
downloadSuccess = await DownloadUpdateAsync();
}
catch (Exception ex)
{
DownloadProgressText.Text = $"下载失败: {ex.Message}";
LogHelper.WriteLogToFile($"AutoUpdate | 下载异常: {ex.Message}", LogHelper.LogType.Error);
}
if (downloadSuccess)
{
DownloadProgressBar.Value = 100;
DownloadProgressText.Text = "下载完成,准备安装...";
await Task.Delay(800);
// 设置结果为立即更新
Result = UpdateResult.UpdateNow;
DialogResult = true;
Close();
}
else
{
DownloadProgressText.Text = "下载失败,请检查网络后重试。";
UpdateNowButton.IsEnabled = true;
UpdateLaterButton.IsEnabled = true;
SkipVersionButton.IsEnabled = true;
}
}
private void UpdateLaterButton_Click(object sender, RoutedEventArgs e)
@@ -279,5 +311,84 @@ namespace Ink_Canvas
}
}
}
// 下载更新并实时更新进度条(支持断点续传)
private async Task<bool> DownloadUpdateAsync()
{
string version = NewVersion;
string updatesFolderPath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "AutoUpdate");
if (!Directory.Exists(updatesFolderPath))
Directory.CreateDirectory(updatesFolderPath);
string zipFilePath = Path.Combine(updatesFolderPath, $"InkCanvasForClass.CE.{version}.zip");
string tmpFilePath = zipFilePath + ".tmp";
// 获取下载链接(此处假设主程序已将下载直链传入,或可通过AutoUpdateHelper获取)
string downloadUrl = null;
if (App.Current.Properties.Contains("UpdateDirectDownloadUrl"))
downloadUrl = App.Current.Properties["UpdateDirectDownloadUrl"] as string;
if (string.IsNullOrEmpty(downloadUrl))
{
// 兜底:用GitHub主线格式
downloadUrl = $"https://github.com/InkCanvasForClass/community/releases/download/{version}/InkCanvasForClass.CE.{version}.zip";
}
long existingLength = 0;
if (File.Exists(tmpFilePath))
existingLength = new FileInfo(tmpFilePath).Length;
try
{
using (var client = new System.Net.Http.HttpClient())
{
client.Timeout = System.TimeSpan.FromMinutes(10);
client.DefaultRequestHeaders.Add("User-Agent", "ICC-CE Auto Updater");
if (existingLength > 0)
client.DefaultRequestHeaders.Range = new System.Net.Http.Headers.RangeHeaderValue(existingLength, null);
using (var response = await client.GetAsync(downloadUrl, System.Net.Http.HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
var totalBytes = response.Content.Headers.ContentLength.HasValue
? response.Content.Headers.ContentLength.Value + existingLength
: -1L;
using (var stream = await response.Content.ReadAsStreamAsync())
using (var fs = new FileStream(tmpFilePath, FileMode.Append, FileAccess.Write, FileShare.None))
{
byte[] buffer = new byte[8192];
long totalRead = existingLength;
int read;
var lastUpdate = DateTime.Now;
while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await fs.WriteAsync(buffer, 0, read);
totalRead += read;
if ((DateTime.Now - lastUpdate).TotalMilliseconds > 200)
{
int percent = totalBytes > 0 ? (int)(totalRead * 100 / totalBytes) : 0;
DownloadProgressBar.Value = percent;
DownloadProgressText.Text = totalBytes > 0
? $"已下载 {totalRead / 1024 / 1024.0:F2} MB / {totalBytes / 1024 / 1024.0:F2} MB ({percent}%)"
: $"已下载 {totalRead / 1024 / 1024.0:F2} MB";
lastUpdate = DateTime.Now;
}
}
DownloadProgressBar.Value = 100;
DownloadProgressText.Text = "下载完成,正在校验...";
await fs.FlushAsync();
}
if (File.Exists(zipFilePath)) File.Delete(zipFilePath);
File.Move(tmpFilePath, zipFilePath);
return true;
}
}
}
catch (Exception ex)
{
LogHelper.WriteLogToFile($"AutoUpdate | 断点续传下载失败: {ex.Message}", LogHelper.LogType.Error);
// 不删除 .tmp 文件,便于下次断点续传
return false;
}
}
}
}
@@ -0,0 +1,24 @@
<Window x:Class="Ink_Canvas.HistoryRollbackWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ui="http://schemas.inkore.net/lib/ui/wpf/modern"
xmlns:mdxam="clr-namespace:MdXaml;assembly=MdXaml"
mc:Ignorable="d"
Title="历史版本回滚" Height="600" Width="850" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<Grid Background="#fafafa">
<ui:SimpleStackPanel VerticalAlignment="Stretch" Spacing="0">
<TextBlock Text="选择历史版本进行回滚" FontSize="24" FontWeight="Bold" Foreground="#2563eb" Margin="24,24,0,12"/>
<ComboBox x:Name="VersionComboBox" Width="400" Height="36" Margin="24,0,0,0" DisplayMemberPath="Version" SelectionChanged="VersionComboBox_SelectionChanged"/>
<Border BorderBrush="#3f3f46" Background="White" BorderThickness="1" CornerRadius="4" Margin="24,16,24,0" Height="180">
<mdxam:MarkdownScrollViewer x:Name="ReleaseNotesViewer" Foreground="Black" MarkdownStyleName="GithubLike"/>
</Border>
<Button x:Name="RollbackButton" Content="回滚到此版本" Width="360" Height="48" Margin="24,24,0,0" Click="RollbackButton_Click"/>
<StackPanel x:Name="DownloadProgressPanel" Orientation="Vertical" HorizontalAlignment="Center" Margin="0,10,0,0" Visibility="Collapsed">
<ProgressBar x:Name="DownloadProgressBar" Width="360" Height="18" Minimum="0" Maximum="100" Value="0"/>
<TextBlock x:Name="DownloadProgressText" Text="正在下载..." FontSize="14" Foreground="#2563eb" HorizontalAlignment="Center" Margin="0,6,0,0"/>
</StackPanel>
</ui:SimpleStackPanel>
</Grid>
</Window>
@@ -0,0 +1,165 @@
using Ink_Canvas.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace Ink_Canvas
{
public partial class HistoryRollbackWindow : Window
{
private class VersionItem
{
public string Version { get; set; }
public string DownloadUrl { get; set; }
public string ReleaseNotes { get; set; }
}
private List<VersionItem> versionList = new List<VersionItem>();
private VersionItem selectedItem = null;
public HistoryRollbackWindow()
{
InitializeComponent();
LoadVersions();
}
private async void LoadVersions()
{
RollbackButton.IsEnabled = false;
VersionComboBox.Items.Clear();
DownloadProgressPanel.Visibility = Visibility.Collapsed;
DownloadProgressBar.Value = 0;
DownloadProgressText.Text = "";
ReleaseNotesViewer.Markdown = "正在获取历史版本...";
var releases = await AutoUpdateHelper.GetAllGithubReleases();
versionList.Clear();
foreach (var (version, url, notes) in releases)
{
versionList.Add(new VersionItem { Version = version, DownloadUrl = url, ReleaseNotes = notes });
}
VersionComboBox.ItemsSource = versionList;
if (versionList.Count > 0)
{
VersionComboBox.SelectedIndex = 0;
RollbackButton.IsEnabled = true;
}
else
{
ReleaseNotesViewer.Markdown = "未获取到历史版本信息。";
}
}
private void VersionComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
selectedItem = VersionComboBox.SelectedItem as VersionItem;
if (selectedItem != null)
{
ReleaseNotesViewer.Markdown = selectedItem.ReleaseNotes ?? "无更新日志";
}
}
private async void RollbackButton_Click(object sender, RoutedEventArgs e)
{
if (selectedItem == null) return;
RollbackButton.IsEnabled = false;
VersionComboBox.IsEnabled = false;
DownloadProgressPanel.Visibility = Visibility.Visible;
DownloadProgressBar.Value = 0;
DownloadProgressText.Text = "正在准备下载...";
bool downloadSuccess = false;
try
{
downloadSuccess = await DownloadAndInstallVersion(selectedItem.Version, selectedItem.DownloadUrl);
}
catch (Exception ex)
{
DownloadProgressText.Text = $"下载失败: {ex.Message}";
}
if (downloadSuccess)
{
DownloadProgressBar.Value = 100;
DownloadProgressText.Text = "下载完成,准备安装...";
await Task.Delay(800);
this.DialogResult = true;
this.Close();
}
else
{
DownloadProgressText.Text = "下载失败,请检查网络后重试。";
RollbackButton.IsEnabled = true;
VersionComboBox.IsEnabled = true;
}
}
private async Task<bool> DownloadAndInstallVersion(string version, string downloadUrl)
{
string updatesFolderPath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "AutoUpdate");
if (!Directory.Exists(updatesFolderPath))
Directory.CreateDirectory(updatesFolderPath);
string zipFilePath = Path.Combine(updatesFolderPath, $"InkCanvasForClass.CE.{version}.zip");
string tmpFilePath = zipFilePath + ".tmp";
long existingLength = 0;
if (File.Exists(tmpFilePath))
existingLength = new FileInfo(tmpFilePath).Length;
try
{
using (var client = new System.Net.Http.HttpClient())
{
client.Timeout = TimeSpan.FromMinutes(10);
client.DefaultRequestHeaders.Add("User-Agent", "ICC-CE Auto Updater");
if (existingLength > 0)
client.DefaultRequestHeaders.Range = new System.Net.Http.Headers.RangeHeaderValue(existingLength, null);
using (var response = await client.GetAsync(downloadUrl, System.Net.Http.HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
var totalBytes = response.Content.Headers.ContentLength.HasValue
? response.Content.Headers.ContentLength.Value + existingLength
: -1L;
using (var stream = await response.Content.ReadAsStreamAsync())
using (var fs = new FileStream(tmpFilePath, FileMode.Append, FileAccess.Write, FileShare.None))
{
byte[] buffer = new byte[8192];
long totalRead = existingLength;
int read;
var lastUpdate = DateTime.Now;
while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await fs.WriteAsync(buffer, 0, read);
totalRead += read;
if ((DateTime.Now - lastUpdate).TotalMilliseconds > 200)
{
int percent = totalBytes > 0 ? (int)(totalRead * 100 / totalBytes) : 0;
DownloadProgressBar.Value = percent;
DownloadProgressText.Text = totalBytes > 0
? $"已下载 {totalRead / 1024 / 1024.0:F2} MB / {totalBytes / 1024 / 1024.0:F2} MB ({percent}%)"
: $"已下载 {totalRead / 1024 / 1024.0:F2} MB";
lastUpdate = DateTime.Now;
}
}
DownloadProgressBar.Value = 100;
DownloadProgressText.Text = "下载完成,正在校验...";
await fs.FlushAsync();
}
if (File.Exists(zipFilePath)) File.Delete(zipFilePath);
File.Move(tmpFilePath, zipFilePath);
}
}
// 下载完成后,调用现有安装流程
AutoUpdateHelper.InstallNewVersionApp(version, false);
App.IsAppExitByUser = true;
Application.Current.Dispatcher.Invoke(() => {
Application.Current.Shutdown();
});
return true;
}
catch (Exception ex)
{
if (File.Exists(tmpFilePath)) { /* 不删除,便于断点续传 */ }
return false;
}
}
}
}