Skip to content

Commit

Permalink
添加一键检查更新升级功能
Browse files Browse the repository at this point in the history
  • Loading branch information
noberumotto committed Dec 27, 2021
1 parent d9c9892 commit 527b5c6
Show file tree
Hide file tree
Showing 20 changed files with 1,069 additions and 13 deletions.
10 changes: 10 additions & 0 deletions Tai.sln
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UI", "UI\UI.csproj", "{2427
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TaiBug", "TaiBug\TaiBug.csproj", "{758D59B2-C438-4DE4-B135-7FF0614FE4B7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Updater", "Updater\Updater.csproj", "{7A2F2592-3079-441C-8704-E71CE75BC593}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -41,6 +43,14 @@ Global
{758D59B2-C438-4DE4-B135-7FF0614FE4B7}.Release|Any CPU.Build.0 = Release|Any CPU
{758D59B2-C438-4DE4-B135-7FF0614FE4B7}.Release|x64.ActiveCfg = Release|Any CPU
{758D59B2-C438-4DE4-B135-7FF0614FE4B7}.Release|x64.Build.0 = Release|Any CPU
{7A2F2592-3079-441C-8704-E71CE75BC593}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7A2F2592-3079-441C-8704-E71CE75BC593}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7A2F2592-3079-441C-8704-E71CE75BC593}.Debug|x64.ActiveCfg = Debug|Any CPU
{7A2F2592-3079-441C-8704-E71CE75BC593}.Debug|x64.Build.0 = Debug|Any CPU
{7A2F2592-3079-441C-8704-E71CE75BC593}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7A2F2592-3079-441C-8704-E71CE75BC593}.Release|Any CPU.Build.0 = Release|Any CPU
{7A2F2592-3079-441C-8704-E71CE75BC593}.Release|x64.ActiveCfg = Release|Any CPU
{7A2F2592-3079-441C-8704-E71CE75BC593}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
6 changes: 5 additions & 1 deletion UI/Models/SettingPageModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace UI.Models
{
Expand All @@ -29,7 +30,10 @@ public class SettingPageModel : UINotifyPropertyChanged
/// <summary>
/// 软件版本号
/// </summary>
public string Version{ get { return version; } set { version = value; OnPropertyChanged(); } }
public string Version { get { return version; } set { version = value; OnPropertyChanged(); } }

private Visibility CheckUpdateBtnVisibility_= Visibility.Visible;
public Visibility CheckUpdateBtnVisibility { get { return CheckUpdateBtnVisibility_; } set { CheckUpdateBtnVisibility_ = value; OnPropertyChanged(); } }

}
}
50 changes: 48 additions & 2 deletions UI/ViewModels/SettingPageVM.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using Core.Models.Config;
using Core.Librarys;
using Core.Models.Config;
using Core.Models.Config.Link;
using Core.Servicers.Interfaces;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
Expand All @@ -17,15 +19,59 @@ public class SettingPageVM : SettingPageModel
{
private ConfigModel config;
private readonly IAppConfig appConfig;
private readonly MainViewModel mainVM;
public Command OpenURL { get; set; }
public SettingPageVM(IAppConfig appConfig)
public Command CheckUpdate { get; set; }

public SettingPageVM(IAppConfig appConfig, MainViewModel mainVM)
{
this.appConfig = appConfig;
this.mainVM = mainVM;

OpenURL = new Command(new Action<object>(OnOpenURL));
CheckUpdate = new Command(new Action<object>(OnCheckUpdate));

Init();
}

private void OnCheckUpdate(object obj)
{
try
{
CheckUpdateBtnVisibility = System.Windows.Visibility.Collapsed;
string updaterExePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"Updater.exe");
string updaterCacheExePath = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Update",
"Updater.exe");
string updateDirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Update");
if (!Directory.Exists(updateDirPath))
{
Directory.CreateDirectory(updateDirPath);
}

if (!File.Exists(updaterExePath))
{
mainVM.Toast("升级程序似乎已被删除,请手动前往发布页查看新版本", Controls.Base.IconTypes.None);
return;
}
File.Copy(updaterExePath, updaterCacheExePath, true);

File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Newtonsoft.Json.dll"), Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Update",
"Newtonsoft.Json.dll"), true);

ProcessHelper.Run(updaterCacheExePath, new string[] { Version });
}
catch (Exception ex)
{
CheckUpdateBtnVisibility = System.Windows.Visibility.Visible;

Logger.Error(ex.Message);
mainVM.Toast("无法正确启动检查更新程序", Controls.Base.IconTypes.None);
}
}

private void OnOpenURL(object obj)
Expand Down
23 changes: 13 additions & 10 deletions UI/Views/SettingPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

<Grid Margin="20">
<StackPanel>

<TextBlock Text="设置" FontSize="18" Margin="0,5,0,20"/>
<Tabbar:Tabbar Data="{Binding TabbarData}" SelectedIndex="{Binding TabbarSelectedIndex,Mode=TwoWay}"/>

Expand Down Expand Up @@ -47,25 +47,28 @@
<TabItem>
<!--关于-->
<Border Background="White" Padding="20" CornerRadius="6">
<StackPanel HorizontalAlignment="Left">
<Image Width="25" Source="/Resources/Icons/tai.ico" HorizontalAlignment="Left"/>
<TextBlock Margin="0,20,0,0">
<Run Text="Tai "/><Run Text="{Binding Version}"/>
</TextBlock>
<TextBlock Margin="0,5,0,0">
<StackPanel HorizontalAlignment="Left">
<Image Width="25" Source="/Resources/Icons/tai.ico" HorizontalAlignment="Left"/>
<StackPanel Orientation="Horizontal" Margin="0,10,0,0">
<TextBlock VerticalAlignment="Center">
<Run Text="Tai版本号 "/><Run Text="{Binding Version}"/>
</TextBlock>
<Btn:Button Visibility="{Binding CheckUpdateBtnVisibility}" Command="{Binding CheckUpdate}" Margin="20,0,0,0" VerticalAlignment="Center" Width="120" Icon="CloudImportExport" Content="检查更新"/>
</StackPanel>
<TextBlock Margin="0,30,0,0">
<Run Text="开源 "/><Hyperlink Command="{Binding OpenURL}" CommandParameter="https://github.com/Planshit/Tai">https://github.com/Planshit/Tai</Hyperlink>
</TextBlock>
<TextBlock Margin="0,5,0,0">
<Run Text="讨论 "/><Hyperlink Command="{Binding OpenURL}" CommandParameter="https://github.com/Planshit/Tai/discussions">https://github.com/Planshit/Tai/discussions</Hyperlink>
</TextBlock>
<TextBlock Margin="0,30,0,0">
<TextBlock Margin="0,10,0,0">
<Run Text="外部资源声明 "/>
</TextBlock>
<TextBlock Margin="0,5,0,0" Text="Icon 来自微软 Emoji"/>
<TextBlock Foreground="Gray" Margin="0,5,0,0" Text="Icon 来自微软 Emoji"/>
</StackPanel>
</Border>
</TabItem>

</TabControl>
</StackPanel>

Expand Down
6 changes: 6 additions & 0 deletions Updater/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
9 changes: 9 additions & 0 deletions Updater/App.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Application x:Class="Updater.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Updater"
StartupUri="MainWindow.xaml">
<Application.Resources>

</Application.Resources>
</Application>
61 changes: 61 additions & 0 deletions Updater/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace Updater
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
private System.Threading.Mutex mutex;

protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// 阻止多开和用户主动启动
if (e.Args.Length == 0 || IsRuned())
{
Shutdown();
}

Activated += (s, e2) =>
{
var mainWindow = App.Current.MainWindow;
if (mainWindow.DataContext != null)
{
var mainModel = mainWindow.DataContext as MainModel;
if (string.IsNullOrEmpty(mainModel.Version))
{
mainModel.Version = e.Args[0];
}
}
};
}





#region 获取当前程序是否已运行
/// <summary>
/// 获取当前程序是否已运行
/// </summary>
private bool IsRuned()
{
bool ret;
mutex = new System.Threading.Mutex(true, System.Reflection.Assembly.GetEntryAssembly().ManifestModule.Name, out ret);
if (!ret)
{
return true;
}
return false;
}
#endregion
}
}
113 changes: 113 additions & 0 deletions Updater/GithubRelease.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Updater
{

public class GithubRelease
{
public class VersionInfo
{
/// <summary>
/// 版本标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 版本号
/// </summary>
public string Version { get; set; }
/// <summary>
/// 是否是预览版本
/// </summary>
public bool IsPre { get; set; }
/// <summary>
/// 下载路径
/// </summary>
public string DownloadUrl { get; set; }
/// <summary>
/// 版本更新内容网页链接
/// </summary>
public string HtmlUrl { get; set; }
}
public class GithubModel
{
public string tag_name { get; set; }
public string html_url { get; set; }
public string name { get; set; }
public bool prerelease { get; set; }

public List<GithubAssetsModel> assets { get; set; }
}
public class GithubAssetsModel
{
public string browser_download_url { get; set; }
}
private string githubUrl;
private string nowVersion;
public VersionInfo Info { get; set; }

//public event UpdaterEventHandler RequestCompleteEvent;
//public event UpdaterEventHandler RequestErrorEvent;
//public delegate void UpdaterEventHandler(object sender, object value);
public GithubRelease(string githubUrl, string nowVersion)
{
this.githubUrl = githubUrl;
this.nowVersion = nowVersion;
Info = new VersionInfo();
}
public bool IsCanUpdate()
{
return !(nowVersion == Info.Version);
}
public async Task<VersionInfo> GetRequest()
{
var result = await Task.Run(() =>
{
HttpWebResponse httpWebRespones = null;
try
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest httpWebRequest = WebRequest.Create(githubUrl) as HttpWebRequest;
httpWebRequest.Timeout = 60 * 1000;
httpWebRequest.ReadWriteTimeout = 60000;
httpWebRequest.AllowAutoRedirect = true;
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";
httpWebRespones = (HttpWebResponse)httpWebRequest.GetResponse();


using (Stream stream = httpWebRespones.GetResponseStream())
{
List<byte> lst = new List<byte>();
int nRead = 0;
while ((nRead = stream.ReadByte()) != -1) lst.Add((byte)nRead);
byte[] bodyBytes = lst.ToArray();

string body = Encoding.UTF8.GetString(bodyBytes, 0, bodyBytes.Length);

var data = JsonConvert.DeserializeObject<GithubModel>(body);
Info.IsPre = data.prerelease;
Info.Title = data.name;
Info.Version = data.tag_name;
Info.DownloadUrl = data.assets[0].browser_download_url;
Info.HtmlUrl = data.html_url;
return Info;
}

}
catch (Exception ec)
{
return null;
}

});
return result;
}
}
}
17 changes: 17 additions & 0 deletions Updater/MainModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Updater
{
public class MainModel : UINotifyPropertyChanged
{
private double ProcessValue_;
public double ProcessValue { get { return ProcessValue_; } set { ProcessValue_ = value; OnPropertyChanged(); } }
private string Version_;
public string Version { get { return Version_; } set { Version_ = value; OnPropertyChanged(); } }

}
}
Loading

0 comments on commit 527b5c6

Please sign in to comment.