Skip to content

Commit

Permalink
Merge pull request #32 from GeneralLibrary/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
JusterZhu authored Dec 27, 2023
2 parents b69ed80 + 3ac3d93 commit fdd9d25
Show file tree
Hide file tree
Showing 76 changed files with 196 additions and 1,968 deletions.
28 changes: 14 additions & 14 deletions src/c#/GeneralUpdate.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,21 @@
/**
* Push the latest version information in real time.
*/
app.MapHub<VersionHub>("/versionhub");
//app.MapHub<VersionHub>("/versionhub");

app.MapPost("/push", async Task<string> (HttpContext context) =>
{
try
{
var hubContext = context.RequestServices.GetRequiredService<IHubContext<VersionHub>>();
await hubContext.SendMessage("TESTNAME", "123");
}
catch (Exception ex)
{
return ex.Message;
}
return "OK";
});
//app.MapPost("/push", async Task<string> (HttpContext context) =>
//{
// try
// {
// var hubContext = context.RequestServices.GetRequiredService<IHubContext<VersionHub>>();
// await hubContext.SendMessage("TESTNAME", "123");
// }
// catch (Exception ex)
// {
// return ex.Message;
// }
// return "OK";
//});

/**
* Check if an update is required.
Expand Down
54 changes: 36 additions & 18 deletions src/c#/GeneralUpdate.Client/MySample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,19 @@
using System.Threading.Tasks;
using GeneralUpdate.Core.Domain.Enum;
using GeneralUpdate.Core.Events.CommonArgs;
using GeneralUpdate.Differential;

namespace GeneralUpdate.Client
{
internal class MySample
{
#region 推送功能

private const string baseUrl = @"http://127.0.0.1:5001";
private const string hubName = "versionhub";

internal MySample()
internal MySample()
{
//var md5 = FileUtil.GetFileMD5(@"F:\test\update.zip");
//Receive sample code pushed by the server
//VersionHub<string>.Instance.Subscribe($"{baseUrl}/{hubName}", "TESTNAME", new Action<string>(GetMessage));
}
Expand All @@ -32,19 +34,21 @@ private async void GetMessage(string msg)
if (isUpdate) Upgrade();
}

private void OnClicked(object sender, EventArgs e) => Upgrade();
#endregion

#region 常规更新

private void Upgrade()
public void Upgrade()
{
Task.Run(async () =>
{
var url = "http://192.168.50.203";
var appName = "GeneralUpdate.Client";
var version = "1.0.0.0";
var versionFileName = "version.json";
ParamsOSS @params = new ParamsOSS(url, appName, version, versionFileName);
await GeneralClientOSS.Start(@params);
});
//Task.Run(async () =>
//{
// var url = "http://192.168.50.203";
// var appName = "GeneralUpdate.Client";
// var version = "1.0.0.0";
// var versionFileName = "version.json";
// ParamsOSS @params = new ParamsOSS(url, appName, version, versionFileName);
// await GeneralClientOSS.Start(@params);
//});

Task.Run(async () =>
{
Expand All @@ -71,15 +75,15 @@ private void Upgrade()
//开启驱动更新
.Option(UpdateOption.Drive, true)
//开启遗言功能,需要部署GeneralUpdate.SystemService Windows服务。
.Option(UpdateOption.WillMessage, true)
//.Option(UpdateOption.WillMessage, true)
.Strategy<WindowsStrategy>()
//注入一个func让用户决定是否跳过本次更新,如果是强制更新则不生效
.SetCustomSkipOption(ShowCustomOption)
//.SetCustomSkipOption(ShowCustomOption)
//注入一个自定义方法集合,该集合会在更新启动前执行。执行自定义方法列表如果出现任何异常,将通过异常订阅通知。(推荐在更新之前检查当前软件环境)
.AddCustomOption(new List<Func<bool>>() { () => Check1(), () => Check2() })
//.AddCustomOption(new List<Func<bool>>() { () => Check1(), () => Check2() })
//默认黑名单文件: { "Newtonsoft.Json.dll" } 默认黑名单文件扩展名: { ".patch", ".7z", ".zip", ".rar", ".tar" , ".json" }
//如果不需要扩展,需要重新传入黑名单集合来覆盖。
.SetBlacklist(GetBlackFiles(), GetBlackFormats())
//.SetBlacklist(GetBlackFiles(), GetBlackFormats())
.LaunchTaskAsync();
});
}
Expand Down Expand Up @@ -206,7 +210,21 @@ private void OnMultiDownloadError(object sender, MultiDownloadErrorEventArgs e)

private void DispatchMessage(string message)
{


}

#endregion

#region 测试二进制更新包整理

public async Task TestDifferentialClean()
{
var path1 = "D:\\packet\\source";
var path2 = "D:\\packet\\target";
var path3 = "D:\\packet\\patchs";
await DifferentialCore.Instance.Clean(path1, path2, path3);
}

#endregion
}
}
5 changes: 5 additions & 0 deletions src/c#/GeneralUpdate.Client/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ internal class Program
{
static void Main(string[] args)
{
Task.Run(async() =>
{
MySample sample = new MySample();
await sample.TestDifferentialClean();
});
Console.Read();
}
}
Expand Down
21 changes: 21 additions & 0 deletions src/c#/GeneralUpdate.ClientCore/GeneralClientBootstrap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using GeneralUpdate.Core.Exceptions.CustomArgs;
using GeneralUpdate.Core.Exceptions.CustomException;
using GeneralUpdate.Core.Strategys;
using GeneralUpdate.Core.WillMessage;
using System;
using System.Collections.Generic;
using System.Diagnostics;
Expand Down Expand Up @@ -60,6 +61,7 @@ private async Task<GeneralClientBootstrap> BaseLaunch()
var versionService = new VersionService();
var mainResp = await versionService.ValidationVersion(Packet.MainUpdateUrl);
var upgradeResp = await versionService.ValidationVersion(Packet.UpdateUrl);
//if (!CheckWillMessage()) return this;
Packet.IsUpgradeUpdate = upgradeResp.Body.IsUpdate;
Packet.IsMainUpdate = mainResp.Body.IsUpdate;
//No need to update, return directly.
Expand Down Expand Up @@ -265,6 +267,25 @@ private void ClearEnvironmentVariable()
}
}

/// <summary>
/// When the update version information requested by the server contains the update failed version, the update execution flow is directly interrupted
/// </summary>
/// <returns></returns>
private bool CheckWillMessage()
{
var willMessage = WillMessageManager.Instance.GetWillMessage();
if (willMessage == null) return true;
foreach (var item in Packet.UpdateVersions)
{
var msg = willMessage.Message.Peek();
if (string.Equals(msg.Version, item.Version,StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
return true;
}

#endregion Private Methods
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@
<Compile Include="..\GeneralUpdate.Core\WillMessage\WillMessageManager.cs" Link="WillMessage\WillMessageManager.cs" />
<Compile Include="..\GeneralUpdate.Differential\Binary\BinaryHandle.cs" Link="Differential\Binary\BinaryHandle.cs" />
<Compile Include="..\GeneralUpdate.Differential\Binary\IBinary.cs" Link="Differential\Binary\IBinary.cs" />
<Compile Include="..\GeneralUpdate.Differential\Common\DirectoryComparer.cs" Link="Differential\Common\DirectoryComparer.cs" />
<Compile Include="..\GeneralUpdate.Differential\Common\Filefilter.cs" Link="Differential\Common\Filefilter.cs" />
<Compile Include="..\GeneralUpdate.Differential\Config\Cache\ConfigCache.cs" Link="Differential\Config\Cache\ConfigCache.cs" />
<Compile Include="..\GeneralUpdate.Differential\Config\Cache\ConfigEntity.cs" Link="Differential\Config\Cache\ConfigEntity.cs" />
Expand Down
2 changes: 2 additions & 0 deletions src/c#/GeneralUpdate.Core/Domain/PO/WillMessagePO.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ public class BackupPO

public string Version { get; set; }

public string Hash { get; set; }

public int AppType { get; set; }
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@ public class DriveMiddleware : IMiddleware
public async Task InvokeAsync(BaseContext context, MiddlewareStack stack)
{
var drivers = GetAllDriverDirectories(context.TargetPath);

var information = new DriverInformation.Builder()
.SetInstallDirectory(Path.Combine(context.SourcePath,context.Version.ToString()))
//TODO: TargetPath to CachePath
.SetOutPutDirectory(Path.Combine(context.TargetPath,context.Version.ToString()))
.SetDriverNames(drivers)
.Build();
Expand Down Expand Up @@ -47,9 +45,7 @@ private List<string> GetAllDriverDirectories(string path)
foreach (string filePath in Directory.GetFiles(path))
{
if (IsDriverFile(filePath))
{
driverDirectories.Add(filePath);
}
}

foreach (string directory in Directory.GetDirectories(path))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ internal class WillMessageMiddleware : IMiddleware
{
public async Task InvokeAsync(BaseContext context, MiddlewareStack stack)
{
WillMessageManager.Instance.Backup(context.SourcePath, context.TargetPath, context.Version.ToString(), context.AppType);
WillMessageManager.Instance.Backup(context.SourcePath, context.TargetPath, context.Version.ToString(), context.Version.Hash ,context.AppType);
var node = stack.Pop();
if (node != null) await node.Next.Invoke(context, stack);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,7 @@ public class WindowsStrategy : AbstractStrategy

#region Public Methods

public override void Create<T>(T parameter)
{
Packet = parameter as Packet;
}
public override void Create<T>(T parameter)=> Packet = parameter as Packet;

public override void Execute()
{
Expand All @@ -46,7 +43,7 @@ public override void Execute()
foreach (var version in updateVersions)
{
var patchPath = FileUtil.GetTempDirectory(PATCHS);
var zipFilePath = $"{Packet.TempPath}{version.Name}{Packet.Format}";
var zipFilePath = Path.Combine(Packet.TempPath, $"{version.Name}{Packet.Format}");

var context = new BaseContext.Builder()
.SetVersion(version)
Expand Down Expand Up @@ -124,7 +121,7 @@ private bool Clear()
{
try
{
if (System.IO.File.Exists(Packet.TempPath)) System.IO.File.Delete(Packet.TempPath);
if (File.Exists(Packet.TempPath)) File.Delete(Packet.TempPath);
var dirPath = Path.GetDirectoryName(Packet.TempPath);
if (Directory.Exists(dirPath)) Directory.Delete(dirPath, true);
return true;
Expand Down
95 changes: 0 additions & 95 deletions src/c#/GeneralUpdate.Core/Utils/FileUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,11 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace GeneralUpdate.Core.Utils
{
public static class FileUtil
{
public static void DirectoryCopy(string sourceDirName, string destDirName,
bool copySubDirs, bool isOverWrite, Action<string> action)
{
var dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists) return;
var dirs = dir.GetDirectories();
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
foreach (var file in dir.GetFiles())
{
var tempPath = Path.Combine(destDirName, file.Name);
file.CopyTo(tempPath, isOverWrite);
if (action != null) action.Invoke(file.Name);
}
if (copySubDirs)
{
foreach (var subdir in dirs)
{
var tempPath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, tempPath, true, isOverWrite, action);
}
}
Directory.Delete(sourceDirName, true);
}

public static string GetTempDirectory(string name)
{
var path2 = $"generalupdate_{DateTime.Now.ToString("yyyy-MM-dd")}_{name}";
Expand All @@ -46,45 +18,6 @@ public static string GetTempDirectory(string name)
return tempDir;
}

/// <summary>
/// Compare the contents of two folders for equality.
/// </summary>
/// <param name="folder1">source path</param>
/// <param name="folder2">target path</param>
/// <returns>item1 : The following files are in both folders, item2 : The following files are in list1 but not list2.</returns>
public static IEnumerable<FileInfo> Compare(string folder1, string folder2)
{
// Create two identical or different temporary folders
// on a local drive and change these file paths.
var dir1 = new DirectoryInfo(folder1);
var dir2 = new DirectoryInfo(folder2);

// Take a snapshot of the file system.
var list1 = dir1.GetFiles("*.*", SearchOption.AllDirectories);
var list2 = dir2.GetFiles("*.*", SearchOption.AllDirectories);

//A custom file comparer defined below
var fileCompare = new FileCompare();

// This query determines whether the two folders contain
// identical file lists, based on the custom file comparer
// that is defined in the FileCompare class.
// The query executes immediately because it returns a bool.
//areIdentical true : the two folders are the same; false : The two folders are not the same.
var areIdentical = list1.SequenceEqual(list2, fileCompare);

// Find the common files. It produces a sequence and doesn't
// execute until the foreach statement.
// list1.Intersect(list2, fileCompare);

// Find the set difference between the two folders.
// For this example we only check one way.
//The following files are in list1 but not list2
// (from file in list1 select file).Except(list2, fileCompare);
var result = (from file in list1 select file).Except(list2, fileCompare);
return (from file in list1 select file).Except(list2, fileCompare);
}

public static FileInfo[] GetAllFiles(string path)
{
try
Expand Down Expand Up @@ -136,32 +69,4 @@ public static void DeleteDir(string path)
Directory.Delete(path, true);
}
}

/// <summary>
/// This implementation defines a very simple comparison
/// between two FileInfo objects. It only compares the name
/// of the files being compared and their length in bytes.
/// </summary>
public class FileCompare : IEqualityComparer<FileInfo>
{
public FileCompare()
{ }

public bool Equals(FileInfo f1, FileInfo f2)
{
return (f1.Name == f2.Name &&
f1.Length == f2.Length);
}

// Return a hash that reflects the comparison criteria. According to the
// rules for IEqualityComparer<T>, if Equals is true, then the hash codes must
// also be equal. Because equality as defined here is a simple value equality, not
// reference identity, it is possible that two or more objects will produce the same
// hash code.
public int GetHashCode(FileInfo fi)
{
string s = $"{fi.Name}{fi.Length}";
return s.GetHashCode();
}
}
}
Loading

0 comments on commit fdd9d25

Please sign in to comment.