Move Updater into Main Program

This commit is contained in:
ChsBuffer
2021-02-14 13:19:58 +08:00
parent f728759bb2
commit faa3cf3770
17 changed files with 257 additions and 770 deletions

View File

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
@@ -8,6 +7,7 @@ using System.Threading.Tasks;
using Netch.Models.GitHubRelease;
using Netch.Utils;
using Newtonsoft.Json;
using static Netch.Updater.Updater;
namespace Netch.Controllers
{
@@ -19,7 +19,7 @@ namespace Netch.Controllers
public const string Name = @"Netch";
public const string Copyright = @"Copyright © 2019 - 2021";
public const string AssemblyVersion = @"1.7.4";
public const string AssemblyVersion = @"1.7.3";
private const string Suffix = @"";
public static readonly string Version = $"{AssemblyVersion}{(string.IsNullOrEmpty(Suffix) ? "" : $"-{Suffix}")}";
@@ -68,7 +68,7 @@ namespace Netch.Controllers
}
}
public static async Task UpdateNetch(DownloadProgressChangedEventHandler onDownloadProgressChanged)
public static async Task DownloadUpdate(DownloadProgressChangedEventHandler onDownloadProgressChanged)
{
using WebClient client = new();
@@ -87,7 +87,7 @@ namespace Netch.Controllers
{
if (Utils.Utils.SHA256CheckSum(fileFullPath) == sha256)
{
RunUpdater();
UpdateNetch(fileFullPath);
return;
}
@@ -108,21 +108,7 @@ namespace Netch.Controllers
if (Utils.Utils.SHA256CheckSum(fileFullPath) != sha256)
throw new Exception(i18N.Translate("The downloaded file has the wrong hash"));
RunUpdater();
void RunUpdater()
{
// if debugging process stopped, debugger will kill child processes!!!!
// 调试进程结束,调试器将会杀死子进程
// uncomment if(!Debugger.isAttach) block in NetchUpdater Project's main() method and attach to NetchUpdater process to debug
// 在 NetchUpdater 项目的 main() 方法中取消注释 if!Debugger.isAttach并附加到 NetchUpdater 进程进行调试
Process.Start(new ProcessStartInfo
{
FileName = Path.Combine(Global.NetchDir, "NetchUpdater.exe"),
Arguments =
$"{Global.Settings.UDPSocketPort} \"{fileFullPath}\" \"{Global.NetchDir}\""
});
}
UpdateNetch(fileFullPath);
}
}
}

View File

@@ -1346,7 +1346,7 @@ namespace Netch.Forms
Hide();
}
private async void Exit(bool forceExit = false)
public async void Exit(bool forceExit = false)
{
if (!IsWaiting() && !Global.Settings.StopWhenExited && !forceExit)
{
@@ -1441,7 +1441,7 @@ namespace Netch.Forms
BeginInvoke(new Action(() => { NewVersionLabel.Text = $"{args.ProgressPercentage}%"; }));
}
await UpdateChecker.UpdateNetch(OnDownloadProgressChanged);
await UpdateChecker.DownloadUpdate(OnDownloadProgressChanged);
}
catch (Exception exception)
{

View File

@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
@@ -69,43 +68,11 @@ namespace Netch.Forms.Mode
{
try
{
var RDirInfo = new DirectoryInfo(DirName);
if (!RDirInfo.Exists)
{
return;
}
RuleListBox.Items.AddRange(Directory.GetFiles(DirName, "*.exe", SearchOption.AllDirectories));
}
catch (Exception)
catch (Exception e)
{
return;
}
var DirStack = new Stack<string>();
DirStack.Push(DirName);
while (DirStack.Count > 0)
{
var DirInfo = new DirectoryInfo(DirStack.Pop());
try
{
foreach (var DirChildInfo in DirInfo.GetDirectories())
{
DirStack.Push(DirChildInfo.FullName);
}
foreach (var FileChildInfo in DirInfo.GetFiles())
{
if (FileChildInfo.Name.EndsWith(".exe") && !RuleListBox.Items.Contains(FileChildInfo.Name))
{
RuleListBox.Items.Add(FileChildInfo.Name);
Edited = true;
}
}
}
catch (Exception)
{
// ignored
}
// ignored
}
}
@@ -216,7 +183,8 @@ namespace Netch.Forms.Mode
}
else
{
var fullName = ModeHelper.GetFullPath(FilenameTextBox.Text + ".txt");
var relativePath = $"Custom\\{FilenameTextBox.Text}.txt";
var fullName = ModeHelper.GetFullPath(relativePath);
if (File.Exists(fullName))
{
MessageBoxX.Show(i18N.Translate("File already exists.\n Please Change the filename"));
@@ -227,6 +195,7 @@ namespace Netch.Forms.Mode
{
BypassChina = false,
FileName = FilenameTextBox.Text,
RelativePath = relativePath,
Type = 0,
Remark = RemarkTextBox.Text
};

View File

@@ -7,6 +7,7 @@ using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
using WindowsJobAPI;
@@ -26,6 +27,8 @@ namespace Netch
/// </summary>
public static MainForm MainForm;
public static readonly Mutex Mutex = new(false, "Global\\Netch");
public static class Flags
{
public static bool SupportFakeDns => _supportFakeDns ??= new TUNTAPController().TestFakeDNS();

View File

@@ -22,69 +22,67 @@ namespace Netch
if (!NativeMethods.AttachConsole(-1))
NativeMethods.AllocConsole();
// 创建互斥体防止多次运行
using (var mutex = new Mutex(false, "Global\\Netch"))
// 设置当前目录
Directory.SetCurrentDirectory(Global.NetchDir);
Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process) + ";" + Path.Combine(Global.NetchDir, "bin"), EnvironmentVariableTarget.Process);
Updater.Updater.CleanOld();
// 预创建目录
var directories = new[] {"mode\\Custom", "data", "i18n", "logging"};
foreach (var item in directories)
if (!Directory.Exists(item))
Directory.CreateDirectory(item);
// 加载配置
Configuration.Load();
// 加载语言
i18N.Load(Global.Settings.Language);
if (!Directory.Exists("bin") || !Directory.EnumerateFileSystemEntries("bin").Any())
{
// 设置当前目录
Directory.SetCurrentDirectory(Global.NetchDir);
Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process) + ";" + Path.Combine(Global.NetchDir, "bin"), EnvironmentVariableTarget.Process);
// 预创建目录
var directories = new[] {"mode", "data", "i18n", "logging"};
foreach (var item in directories)
if (!Directory.Exists(item))
Directory.CreateDirectory(item);
// 加载配置
Configuration.Load();
// 加载语言
i18N.Load(Global.Settings.Language);
if (!Directory.Exists("bin") || !Directory.EnumerateFileSystemEntries("bin").Any())
{
MessageBoxX.Show(i18N.Translate("Please extract all files then run the program!"));
Environment.Exit(2);
}
// 检查是否已经运行
if (!mutex.WaitOne(0, false))
{
OnlyInstance.Send(OnlyInstance.Commands.Show);
Logging.Info("唤起单实例");
// 退出进程
Environment.Exit(1);
}
// 清理上一次的日志文件,防止淤积占用磁盘空间
if (Directory.Exists("logging"))
{
var directory = new DirectoryInfo("logging");
foreach (var file in directory.GetFiles())
file.Delete();
foreach (var dir in directory.GetDirectories())
dir.Delete(true);
}
Logging.Info($"版本: {UpdateChecker.Owner}/{UpdateChecker.Repo}@{UpdateChecker.Version}");
Task.Run(() => { Logging.Info($"主程序 SHA256: {Utils.Utils.SHA256CheckSum(Application.ExecutablePath)}"); });
Task.Run(() =>
{
Logging.Info("启动单实例");
OnlyInstance.Server();
});
// 绑定错误捕获
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += Application_OnException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(Global.MainForm = new MainForm());
MessageBoxX.Show(i18N.Translate("Please extract all files then run the program!"));
Environment.Exit(2);
}
// 检查是否已经运行
if (!Global.Mutex.WaitOne(0, false))
{
OnlyInstance.Send(OnlyInstance.Commands.Show);
Logging.Info("唤起单实例");
// 退出进程
Environment.Exit(1);
}
// 清理上一次的日志文件,防止淤积占用磁盘空间
if (Directory.Exists("logging"))
{
var directory = new DirectoryInfo("logging");
foreach (var file in directory.GetFiles())
file.Delete();
foreach (var dir in directory.GetDirectories())
dir.Delete(true);
}
Logging.Info($"版本: {UpdateChecker.Owner}/{UpdateChecker.Repo}@{UpdateChecker.Version}");
Task.Run(() => { Logging.Info($"主程序 SHA256: {Utils.Utils.SHA256CheckSum(Application.ExecutablePath)}"); });
Task.Run(() =>
{
Logging.Info("启动单实例");
OnlyInstance.Server();
});
// 绑定错误捕获
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += Application_OnException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(Global.MainForm = new MainForm());
}
public static void Application_OnException(object sender, ThreadExceptionEventArgs e)

View File

@@ -65,7 +65,6 @@
<ItemGroup>
<ProjectReference Include="..\NetchLib\NetchLib.csproj" />
<ProjectReference Include="..\NetchUpdater\NetchUpdater.csproj" />
</ItemGroup>
<ItemGroup>

View File

@@ -149,5 +149,15 @@ namespace Netch.Properties {
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] _7za {
get {
object obj = ResourceManager.GetObject("7za", resourceCulture);
return ((byte[])(obj));
}
}
}
}

View File

@@ -169,4 +169,9 @@
PublicKeyToken=b03f5f7f11d50a3a
</value>
</data>
<data name="7za" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\7za.exe;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
</value>
</data>
</root>

167
Netch/Updater/Updater.cs Normal file
View File

@@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Windows.Forms;
using Netch.Controllers;
using Netch.Forms;
using Netch.Properties;
using Netch.Utils;
namespace Netch.Updater
{
public static class Updater
{
public static void UpdateNetch(string updateFilePath)
{
var tempFolder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var extractPath = Path.Combine(tempFolder, "extract");
int exitCode;
if ((exitCode = Extract(updateFilePath, extractPath, true, tempFolder)) != 0)
{
MessageBoxX.Show($"7za exit with code {exitCode}");
return;
}
foreach (var file in Directory.GetFiles(Global.NetchDir, "*", SearchOption.AllDirectories))
{
if (new[] {"data", "mode\\Custom"}.ToList().Any(p => file.StartsWith(Path.Combine(Global.NetchDir, p))))
continue;
try
{
File.Move(file, file + ".old");
}
catch
{
throw new Exception("Updater wasn't able to rename file: " + file);
}
}
MoveDirectory(Path.Combine(extractPath, "Netch"), Global.NetchDir, true);
Global.Mutex.ReleaseMutex();
Process.Start(Application.ExecutablePath);
Global.MainForm.Exit(true);
}
private static int Extract(string archiveFileName, string destDirName, bool overwrite, string tempFolder = null)
{
tempFolder ??= Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var temp7za = Path.Combine(tempFolder, "7za.exe");
archiveFileName = Path.GetFullPath(archiveFileName);
destDirName = Path.GetFullPath(destDirName);
if (!Directory.Exists(tempFolder))
Directory.CreateDirectory(tempFolder);
if (!File.Exists(temp7za))
File.WriteAllBytes(temp7za, Resources._7za);
var argument = new StringBuilder();
argument.Append($" x \"{archiveFileName}\" -o\"{destDirName}\" ");
if (overwrite)
argument.Append(" -y ");
var process = Process.Start(new ProcessStartInfo
{
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
FileName = temp7za,
Arguments = argument.ToString()
});
process?.WaitForExit();
return process?.ExitCode ?? 2;
}
public static FileInfo FindFile(string filename, string directory)
{
var DirStack = new Stack<string>();
DirStack.Push(directory);
while (DirStack.Count > 0)
{
var DirInfo = new DirectoryInfo(DirStack.Pop());
try
{
foreach (var DirChildInfo in DirInfo.GetDirectories())
{
DirStack.Push(DirChildInfo.FullName);
}
}
catch
{
// ignored
}
try
{
foreach (var FileChildInfo in DirInfo.GetFiles())
{
if (FileChildInfo.Name == filename)
{
return FileChildInfo;
}
}
}
catch
{
// ignored
}
}
return null;
}
private static void MoveDirectory(string sourceDirName, string destDirName, bool overwrite)
{
sourceDirName = Path.GetFullPath(sourceDirName);
destDirName = Path.GetFullPath(destDirName);
if (!overwrite)
{
Directory.Move(sourceDirName, destDirName);
}
else
{
foreach (var dir in Directory.GetDirectories(sourceDirName, "*", SearchOption.AllDirectories))
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
}
foreach (var f in Directory.GetFiles(sourceDirName, "*", SearchOption.AllDirectories))
{
try
{
File.Move(f, f.Replace(sourceDirName, destDirName));
}
catch (Exception e)
{
throw new Exception("Updater wasn't able to move file: " + f);
}
}
}
}
private static bool TestFileFree(string FileName)
{
try
{
File.Move(FileName, FileName);
return true;
}
catch
{
return false;
}
}
public static void CleanOld()
{
foreach (var f in Directory.GetFiles(Global.NetchDir, "*.old", SearchOption.AllDirectories))
File.Delete(f);
}
}
}