From 9090854988f85be54d378957b3b806034ede9350 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Sun, 14 Jan 2024 13:55:01 +0800 Subject: [PATCH 01/11] =?UTF-8?q?test=EF=BC=9A=20will=20message?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/c#/GeneralUpdate.Client/MySample.cs | 23 ++++++++++++++++++ .../Pipelines/Context/BaseContext.cs | 5 +--- .../WillMessage/WillMessageManager.cs | 24 +++++++++---------- 3 files changed, 36 insertions(+), 16 deletions(-) diff --git a/src/c#/GeneralUpdate.Client/MySample.cs b/src/c#/GeneralUpdate.Client/MySample.cs index 6bc123e..ba98593 100644 --- a/src/c#/GeneralUpdate.Client/MySample.cs +++ b/src/c#/GeneralUpdate.Client/MySample.cs @@ -15,6 +15,7 @@ using System.IO; using GeneralUpdate.Core.Driver; using Microsoft.VisualBasic; using System.Diagnostics; +using GeneralUpdate.Core.WillMessage; namespace GeneralUpdate.Client { @@ -299,5 +300,27 @@ namespace GeneralUpdate.Client string.Equals(Path.GetExtension(filePath), ".inf", StringComparison.OrdinalIgnoreCase); #endregion + + #region 测试WillMessage + + public void TestWillMessage() + { + var path1 = "D:\\packet\\source"; + var path2 = "D:\\packet\\target"; + var hash = ""; + + for (int i = 0; i < 1; i++) + { + var version = "1.0.0" + i; + WillMessageManager.Instance.Backup(path1,path2, version, hash, 1); + } + WillMessageManager.Instance.Builder(); + WillMessageManager.Instance.GetWillMessage(); + WillMessageManager.Instance.Check(); + WillMessageManager.Instance.Restore(); + WillMessageManager.Instance.Clear(); + } + + #endregion } } diff --git a/src/c#/GeneralUpdate.Core/Pipelines/Context/BaseContext.cs b/src/c#/GeneralUpdate.Core/Pipelines/Context/BaseContext.cs index ae70b98..63f2558 100644 --- a/src/c#/GeneralUpdate.Core/Pipelines/Context/BaseContext.cs +++ b/src/c#/GeneralUpdate.Core/Pipelines/Context/BaseContext.cs @@ -81,10 +81,7 @@ namespace GeneralUpdate.Core.Pipelines.Context return this; } - public BaseContext Build() - { - return _context; - } + public BaseContext Build() => _context; } } } \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs b/src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs index c7916ee..b5f014e 100644 --- a/src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs +++ b/src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs @@ -7,18 +7,18 @@ using System.Linq; namespace GeneralUpdate.Core.WillMessage { - internal class WillMessageManager + public class WillMessageManager { #region Private Members - internal const string DEFULT_WILL_MESSAGE_DIR = @"C:\generalupdate_willmessages"; - internal const string DEFULT_WILL_MESSAGE_FILE = "will_message.json"; + public const string DEFULT_WILL_MESSAGE_DIR = @"C:\generalupdate_willmessages"; + public const string DEFULT_WILL_MESSAGE_FILE = "will_message.json"; - internal const string BACKUP_ROOT_PATH = @"C:\generalupdate_backup"; + public const string BACKUP_ROOT_PATH = @"C:\generalupdate_backup"; private string _packetPath; private string _appPath; private string _backupPath; - private Stack _backupStack = new Stack(); + private readonly Stack _backupStack = new Stack(); private string _willMessageFile; private WillMessagePO _willMessage; @@ -37,7 +37,7 @@ namespace GeneralUpdate.Core.WillMessage #region Public Properties - internal static WillMessageManager Instance + public static WillMessageManager Instance { get { @@ -59,13 +59,13 @@ namespace GeneralUpdate.Core.WillMessage #region Public Methods - internal WillMessagePO GetWillMessage(string path = null) + public WillMessagePO GetWillMessage(string path = null) { _willMessageFile = string.IsNullOrWhiteSpace(path) ? GetWillMessagePath() : path; return _willMessage = FileUtil.GetJson(_willMessageFile); } - internal void Clear() + public void Clear() { _packetPath = null; _appPath = null; @@ -77,7 +77,7 @@ namespace GeneralUpdate.Core.WillMessage FileUtil.DeleteDir(BACKUP_ROOT_PATH); } - internal void Backup(string appPath, string packetPath, string version,string hash,int appType) + public void Backup(string appPath, string packetPath, string version,string hash,int appType) { if (!Directory.Exists(BACKUP_ROOT_PATH)) Directory.CreateDirectory(BACKUP_ROOT_PATH); @@ -93,7 +93,7 @@ namespace GeneralUpdate.Core.WillMessage _backupStack.Push(new BackupPO { Version = version, AppType = appType, AppPath = _appPath, BackupPath = _backupPath , Hash = hash }); } - internal void Restore() + public void Restore() { if (_willMessage == null || _willMessage.Message == null) return; while (_willMessage.Message.Any()) @@ -105,7 +105,7 @@ namespace GeneralUpdate.Core.WillMessage } } - internal void Builder() + public void Builder() { if (!_backupStack.Any()) return; @@ -118,7 +118,7 @@ namespace GeneralUpdate.Core.WillMessage FileUtil.CreateJson(Path.Combine(DEFULT_WILL_MESSAGE_DIR, DateTime.Now.ToString("yyyyMMdd")), DEFULT_WILL_MESSAGE_FILE, _willMessage); } - internal void Check() + public void Check() { var message = GetWillMessage(); if (message == null) return; -- Gitee From fb03c7130bfd58e410f6c8db8b848c6f832c3ed1 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Mon, 15 Jan 2024 21:50:32 +0800 Subject: [PATCH 02/11] remvoe: remove MacStrategy.cs --- .../Strategys/PlatformMac/MacStrategy.cs | 24 ------------------- 1 file changed, 24 deletions(-) delete mode 100644 src/c#/GeneralUpdate.Core/Strategys/PlatformMac/MacStrategy.cs diff --git a/src/c#/GeneralUpdate.Core/Strategys/PlatformMac/MacStrategy.cs b/src/c#/GeneralUpdate.Core/Strategys/PlatformMac/MacStrategy.cs deleted file mode 100644 index 0ca9234..0000000 --- a/src/c#/GeneralUpdate.Core/Strategys/PlatformMac/MacStrategy.cs +++ /dev/null @@ -1,24 +0,0 @@ -using GeneralUpdate.Core.Domain.Enum; - -namespace GeneralUpdate.Core.Strategys.PlatformMac -{ - public class MacStrategy : AbstractStrategy - { - public override string GetPlatform() => PlatformType.Mac; - - public override void Create(T parameter) - { - base.Create(parameter); - } - - public override void Execute() - { - base.Execute(); - } - - public override bool StartApp(string appName, int appType) - { - return base.StartApp(appName, appType); - } - } -} \ No newline at end of file -- Gitee From 9ee82200dab479911a49b260a7531aca81e4d10f Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Tue, 16 Jan 2024 22:59:58 +0800 Subject: [PATCH 03/11] feature:Encapsulate file processing classes --- .../GeneralUpdate.Client.csproj | 1 + src/c#/GeneralUpdate.Client/MySample.cs | 9 +- src/c#/GeneralUpdate.Client/Program.cs | 30 +- .../ContentProvider/FileNode.cs | 148 ++++++++++ .../ContentProvider/FileProvider.cs | 261 ++++++++++++++++++ .../ContentProvider/FileTree.cs | 173 ++++++++++++ src/c#/GeneralUpdate.Core/Utils/FileUtil.cs | 7 +- .../WillMessage/WillMessageManager.cs | 24 +- .../DifferentialCore.cs | 2 +- 9 files changed, 622 insertions(+), 33 deletions(-) create mode 100644 src/c#/GeneralUpdate.Core/ContentProvider/FileNode.cs create mode 100644 src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs create mode 100644 src/c#/GeneralUpdate.Core/ContentProvider/FileTree.cs diff --git a/src/c#/GeneralUpdate.Client/GeneralUpdate.Client.csproj b/src/c#/GeneralUpdate.Client/GeneralUpdate.Client.csproj index 02b2970..94ea81d 100644 --- a/src/c#/GeneralUpdate.Client/GeneralUpdate.Client.csproj +++ b/src/c#/GeneralUpdate.Client/GeneralUpdate.Client.csproj @@ -5,6 +5,7 @@ net8.0 enable enable + diff --git a/src/c#/GeneralUpdate.Client/MySample.cs b/src/c#/GeneralUpdate.Client/MySample.cs index ba98593..3a35b76 100644 --- a/src/c#/GeneralUpdate.Client/MySample.cs +++ b/src/c#/GeneralUpdate.Client/MySample.cs @@ -301,24 +301,25 @@ namespace GeneralUpdate.Client #endregion + #region 测试WillMessage public void TestWillMessage() { var path1 = "D:\\packet\\source"; var path2 = "D:\\packet\\target"; - var hash = ""; + var hash = "28d10f1fc2a23dd1afe0af40d132b25c72ea56005963f653c27889f03d381c8d"; for (int i = 0; i < 1; i++) { - var version = "1.0.0" + i; + var version = "1.0.0." + i; WillMessageManager.Instance.Backup(path1,path2, version, hash, 1); } WillMessageManager.Instance.Builder(); - WillMessageManager.Instance.GetWillMessage(); + var obj = WillMessageManager.Instance.GetWillMessage(); WillMessageManager.Instance.Check(); WillMessageManager.Instance.Restore(); - WillMessageManager.Instance.Clear(); + //WillMessageManager.Instance.Clear(); } #endregion diff --git a/src/c#/GeneralUpdate.Client/Program.cs b/src/c#/GeneralUpdate.Client/Program.cs index 99480e1..6bc7d2b 100644 --- a/src/c#/GeneralUpdate.Client/Program.cs +++ b/src/c#/GeneralUpdate.Client/Program.cs @@ -6,22 +6,24 @@ namespace GeneralUpdate.Client { static void Main(string[] args) { - Task.Run(async() => - { - //415eed05eb310f480d1e4d15516fa00e484ddb9f416908b217f17b782ded2030 - //var zip1 = @"D:\github_project\WpfClient\WebApi\UpdateFiles\WpfClient_1_24.1.5.1218.zip"; - //94bd3d806d39cd1b8813298ec0637c7f377658e766845a06cc50917306cb4ad9 - //var zip2 = @"D:\github_project\WpfClient\WebApi\UpdateFiles\WpfClient_1_24.1.5.1224.zip"; + MySample sample = new MySample(); + sample.TestWillMessage(); + //Task.Run(async() => + //{ + // //415eed05eb310f480d1e4d15516fa00e484ddb9f416908b217f17b782ded2030 + // //var zip1 = @"D:\github_project\WpfClient\WebApi\UpdateFiles\WpfClient_1_24.1.5.1218.zip"; + // //94bd3d806d39cd1b8813298ec0637c7f377658e766845a06cc50917306cb4ad9 + // //var zip2 = @"D:\github_project\WpfClient\WebApi\UpdateFiles\WpfClient_1_24.1.5.1224.zip"; - //var hashAlgorithm = new Sha256HashAlgorithm(); - //var hashSha256 = hashAlgorithm.ComputeHash(zip1); - //var hashSha2561 = hashAlgorithm.ComputeHash(zip2); + // //var hashAlgorithm = new Sha256HashAlgorithm(); + // //var hashSha256 = hashAlgorithm.ComputeHash(zip1); + // //var hashSha2561 = hashAlgorithm.ComputeHash(zip2); - MySample sample = new MySample(); - //await sample.TestDifferentialClean(); - //await sample.TestDifferentialDirty(); - await sample.Upgrade(); - }); + // MySample sample = new MySample(); + // //await sample.TestDifferentialClean(); + // //await sample.TestDifferentialDirty(); + // await sample.Upgrade(); + //}); Console.Read(); } } diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileNode.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileNode.cs new file mode 100644 index 0000000..bb0851f --- /dev/null +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileNode.cs @@ -0,0 +1,148 @@ +using System; + +namespace GeneralUpdate.Differential.ContentProvider +{ + public class FileNode + { + #region Public Properties + + public long Id { get; set; } + + public string Name { get; set; } + + public string FullName { get; set; } + + public string Path { get; set; } + + public string Hash { get; set; } + + public FileNode Left { get; set; } + + public FileNode Right { get; set; } + + public int LeftType { get; set; } + + public int RightType { get; set; } + + public string RelativePath { get; set; } + + #endregion Public Properties + + #region Constructors + + public FileNode() + { } + + public FileNode(int id) + { + Id = id; + } + + #endregion Constructors + + #region Public Methods + + public void Add(FileNode node) + { + if (node == null) return; + + if (node.Id < Id) + { + if (Left == null) + { + Left = node; + } + else + { + Left.Add(node); + } + } + else + { + if (Right == null) + { + Right = node; + } + else + { + Right.Add(node); + } + } + } + + public void InfixOrder() + { + if (Left != null) + { + Left.InfixOrder(); + } + if (Right != null) + { + Right.InfixOrder(); + } + } + + public FileNode Search(long id) + { + if (id == Id) + { + return this; + } + else if (id < Id) + { + if (Left == null) return null; + return Left.Search(id); + } + else + { + if (Right == null) return null; + return Right.Search(id); + } + } + + /// + /// Find the parent node of the node that you want to delete. + /// + /// + /// + public FileNode SearchParent(long id) + { + if (Left != null && Left.Id == id || Right != null && Right.Id == id) + { + return this; + } + else + { + if (id < Id && Left != null) + { + return Left.SearchParent(id); + } + else if (id >= Id && Right != null) + { + return Right.SearchParent(id); + } + else + { + return null; + } + } + } + + /// + /// Compare tree nodes equally by Hash and file names. + /// + /// + /// + public override bool Equals(object obj) + { + if (obj == null) return false; + var tempNode = obj as FileNode; + if (tempNode == null) throw new ArgumentException(nameof(tempNode)); + return string.Equals(Hash, tempNode.Hash,StringComparison.OrdinalIgnoreCase) && string.Equals(Name, tempNode.Name,StringComparison.OrdinalIgnoreCase); + } + + public override int GetHashCode() => base.GetHashCode(); + + #endregion Public Methods + } +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs new file mode 100644 index 0000000..7a03954 --- /dev/null +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs @@ -0,0 +1,261 @@ +using GeneralUpdate.Core.HashAlgorithms; +using GeneralUpdate.Differential.Common; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace GeneralUpdate.Differential.ContentProvider +{ + public enum FileOperations + { + Query, + Delete, + Update, + Add, + Copy + } + + public enum SetOperations + { + Intersection, + Union, + Difference + } + + public class FileProvider + { + private long _fileCount = 0; + + #region Public Methods + + /// + /// Compare two binary trees with different children. + /// + /// Left tree folder path. + /// Right tree folder path. + /// ValueTuple(leftFileNodes,rightFileNodes, differentTreeNode) + public async Task, IEnumerable, IEnumerable>> Compare(string leftPath, string rightPath) + { + return await Task.Run(() => + { + ResetId(); + var leftFileNodes = Read(leftPath); + var rightFileNodes = Read(rightPath); + var leftTree = new FileTree(leftFileNodes); + var rightTree = new FileTree(rightFileNodes); + var differentTreeNode = new List(); + leftTree.Compare(leftTree.GetRoot(), rightTree.GetRoot(), ref differentTreeNode); + return ValueTuple.Create(leftFileNodes, rightFileNodes, differentTreeNode); + }); + } + + /// + /// Using the list on the left as a baseline, find the set of differences between the two file lists. + /// + /// Previous version file list path + /// The current version file list path + /// Except collection + public async Task> Except(string leftPath, string rightPath) + { + return await Task.Run(() => + { + var leftFileNodes = Read(leftPath); + var rightFileNodes = Read(rightPath); + var rightNodeDic = rightFileNodes.ToDictionary(x => x.RelativePath, x => x); + var filesOnlyInLeft = leftFileNodes.Where(f => !rightNodeDic.ContainsKey(f.RelativePath)).ToList(); + return filesOnlyInLeft; + }); + } + + #endregion Public Methods + + #region Private Methods + + /// + /// Recursively read all files in the folder path. + /// + /// folder path. + /// folder root path. + /// different chalders. + private IEnumerable Read(string path, string rootPath = null) + { + var resultFiles = new List(); + if (string.IsNullOrEmpty(rootPath)) rootPath = path; + if (!rootPath.EndsWith("/")) rootPath += "/"; + Uri rootUri = new Uri(rootPath); + foreach (var subPath in Directory.GetFiles(path)) + { + if (IsMatchBlacklist(subPath)) continue; + + var hashAlgorithm = new Sha256HashAlgorithm(); + var hash = hashAlgorithm.ComputeHash(subPath); + var subFileInfo = new FileInfo(subPath); + Uri subUri = new Uri(subFileInfo.FullName); + resultFiles.Add(new FileNode() { Id = GetId(), Path = path, Name = subFileInfo.Name, Hash = hash, FullName = subFileInfo.FullName, RelativePath = rootUri.MakeRelativeUri(subUri).ToString() }); + } + foreach (var subPath in Directory.GetDirectories(path)) + { + resultFiles.AddRange(Read(subPath, rootPath)); + } + return resultFiles; + } + + /// + /// Self-growing file tree node ID. + /// + /// + private long GetId() => Interlocked.Increment(ref _fileCount); + + private void ResetId() => Interlocked.Exchange(ref _fileCount, 0); + + /// + /// Whether the file name in the file path can match the blacklisted file. + /// + /// + /// + private bool IsMatchBlacklist(string subPath) + { + var blackList = Filefilter.GetBlackFiles(); + if (blackList == null) return false; + foreach (var file in blackList) + { + if (subPath.Contains(file)) return true; + } + return false; + } + + #endregion Private Methods + + /// + /// ݲɸѡsourceDirtargetDirļ·зҪļϢ + /// + /// ԴĿ¼ + /// ĿĿ¼ + /// ɸѡĿ¼ + /// ɸѡļļ׺ + /// ļִеIJɾ顢ġ + /// 㣺 + /// IJǷݹִ + /// Ƿ񱣳Ŀ¼ṹ + /// + //public List Handle(string sourceDir,string targetDir, string resultDir, List condition, FileOperations fileOption, SetOperations setOperations,bool recursion,bool integrality) + //{ + // return new List(); + //} + + public List Handle(string sourceDir, string targetDir, string resultDir, List condition, FileOperations fileOption, SetOperations setOperations, bool recursion, bool integrality) + { + // ȻȡԴĿ¼ĿĿ¼еļϢ + IEnumerable sourceFiles = Directory.EnumerateFiles(sourceDir, "*.*", recursion ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) + .Select(path => new FileInfo(path)) + .Select(fileInfo => new FileNode + { + Id = fileInfo.GetHashCode(), + Name = fileInfo.Name, + FullName = fileInfo.FullName, + Path = fileInfo.DirectoryName, + Hash = CalculateFileHash(fileInfo) + }); + IEnumerable targetFiles = Directory.EnumerateFiles(targetDir, "*.*", recursion ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) + .Select(path => new FileInfo(path)) + .Select(fileInfo => new FileNode + { + Id = fileInfo.GetHashCode(), + Name = fileInfo.Name, + FullName = fileInfo.FullName, + Path = fileInfo.DirectoryName, + Hash = CalculateFileHash(fileInfo) + }); + + // ȻɸѡҪļ + IEnumerable filteredSourceFiles = sourceFiles.Where(file => condition.Any(c => file.Name.Contains(c) || file.Name.EndsWith(c))); + IEnumerable filteredTargetFiles = targetFiles.Where(file => condition.Any(c => file.Name.Contains(c) || file.Name.EndsWith(c))); + + // мԵõյĽ + IEnumerable resultFiles; + switch (setOperations) + { + case SetOperations.Intersection: + resultFiles = filteredSourceFiles.Intersect(filteredTargetFiles); + break; + case SetOperations.Union: + resultFiles = filteredSourceFiles.Union(filteredTargetFiles); + break; + case SetOperations.Difference: + resultFiles = filteredSourceFiles.Except(filteredTargetFiles); + break; + default: + throw new ArgumentException("Invalid operation.", nameof(setOperations)); + } + + // ִļ + foreach (FileNode file in resultFiles) + { + ExecuteFileOperation(file, fileOption, resultDir, integrality); + } + + return resultFiles.ToList(); + } + + /// + /// ļĹϣֵ. + /// + /// ļ. + /// + private string CalculateFileHash(FileInfo file) + { + // ֻһռλʵҪʵһļϣֵ. + return string.Empty; + } + + /// + /// ִļ. + /// + /// ļ. + /// ҪִеIJ. + /// Ŀ¼. + /// Ƿṹ. + private void ExecuteFileOperation(FileNode file, FileOperations operation, string resultDir, bool retainStructure) + { + string destinationPath = Path.Combine(resultDir, retainStructure ? file.RelativePath : file.Name); + + switch (operation) + { + case FileOperations.Add: + // ļѴڣ˲ļ + File.Copy(file.Path, destinationPath, true); + break; + case FileOperations.Delete: + if (File.Exists(destinationPath)) + { + File.Delete(destinationPath); + } + break; + case FileOperations.Update: + // Ǽٶ²ζŸԴļĿλãļ + File.Copy(file.Path, destinationPath, true); + break; + case FileOperations.Copy: + // ȷĿĿ¼ + string directoryName = Path.GetDirectoryName(destinationPath); + if (!Directory.Exists(directoryName)) + { + Directory.CreateDirectory(directoryName); + } + // ļµλ + File.Copy(file.Path, destinationPath, true); + break; + case FileOperations.Query: + // ڡѯDzִκļֻڿ̨дӡϢ + Console.WriteLine($"Found file: {file.FullName}"); + break; + default: + throw new ArgumentException("Invalid operation", nameof(operation)); + } + } + + } +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileTree.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileTree.cs new file mode 100644 index 0000000..b77d54f --- /dev/null +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileTree.cs @@ -0,0 +1,173 @@ +using System.Collections.Generic; +using System.Diagnostics; + +namespace GeneralUpdate.Differential.ContentProvider +{ + /// + /// Simple file binary tree. + /// + public class FileTree + { + #region Private Members + + private FileNode _root; + + #endregion Private Members + + #region Constructors + + public FileTree() + { } + + public FileTree(IEnumerable nodes) + { + foreach (var node in nodes) Add(node); + } + + #endregion Constructors + + #region Public Methods + + public void Add(FileNode node) + { + if (_root == null) + { + _root = node; + } + else + { + _root.Add(node); + } + } + + public void InfixOrder() + { + if (_root != null) + { + _root.InfixOrder(); + } + else + { + Debug.WriteLine("The binary sort tree is empty and cannot be traversed!"); + } + } + + public FileNode Search(long id) => _root == null ? null : _root.Search(id); + + public FileNode SearchParent(long id) => _root == null ? null : _root.SearchParent(id); + + public long DelRightTreeMin(FileNode node) + { + FileNode target = node; + while (target.Left != null) + { + target = target.Left; + } + DelNode(target.Id); + return target.Id; + } + + public void DelNode(long id) + { + if (_root == null) + { + return; + } + else + { + FileNode targetNode = Search(id); + if (targetNode == null) + { + return; + } + if (_root.Left == null && _root.Right == null) + { + _root = null; + return; + } + + FileNode parent = SearchParent(id); + if (targetNode.Left == null && targetNode.Right == null) + { + if (parent.Left != null && parent.Left.Id == id) + { + parent.Left = null; + } + else if (parent.Right != null && parent.Right.Id == id) + { + parent.Right = null; + } + } + else if (targetNode.Left != null && targetNode.Right != null) + { + long minVal = DelRightTreeMin(targetNode.Right); + targetNode.Id = minVal; + } + else + { + if (targetNode.Left != null) + { + if (parent.Left.Id == id) + { + parent.Left = targetNode.Left; + } + else + { + parent.Right = targetNode.Left; + } + } + else + { + if (parent.Left.Id == id) + { + parent.Left = targetNode.Right; + } + else + { + parent.Right = targetNode.Right; + } + } + } + } + } + + /// + /// Starting from the root node, recursively compares two different child nodes of the binary tree and nodes that are not included. + /// + /// + /// + /// + public void Compare(FileNode node, FileNode node0, ref List nodes) + { + if (node != null && node.Left != null) + { + if (!node.Equals(node0) && node0 != null) nodes.Add(node0); + Compare(node.Left, node0.Left, ref nodes); + } + else if (node0 != null && node0.Left != null) + { + nodes.Add(node0); + Compare(node.Left, node0.Left, ref nodes); + } + + if (node != null && node.Right != null) + { + if (!node.Equals(node0) && node0 != null) nodes.Add(node0); + Compare(node.Right, node0 == null ? null : node0.Right, ref nodes); + } + else if (node0 != null && node0.Right != null) + { + nodes.Add(node0); + Compare(node == null ? null : node.Right, node0.Right, ref nodes); + } + else if (node0 != null) + { + nodes.Add(node0); + } + } + + public FileNode GetRoot() => _root; + + #endregion Public Methods + } +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Utils/FileUtil.cs b/src/c#/GeneralUpdate.Core/Utils/FileUtil.cs index 482dec9..c11d676 100644 --- a/src/c#/GeneralUpdate.Core/Utils/FileUtil.cs +++ b/src/c#/GeneralUpdate.Core/Utils/FileUtil.cs @@ -37,13 +37,12 @@ namespace GeneralUpdate.Core.Utils } } - public static void CreateJson(string targetPath,string fileName,T obj) + public static void CreateJson(string targetPath,T obj) { if (!Directory.Exists(targetPath)) Directory.CreateDirectory(targetPath); - var fileFullPath = Path.Combine(targetPath,fileName); - if (File.Exists(fileFullPath)) File.Delete(fileFullPath); + if (File.Exists(targetPath)) File.Delete(targetPath); var jsonString = JsonConvert.SerializeObject(obj); - File.WriteAllText(fileFullPath, jsonString); + File.WriteAllText(targetPath, jsonString); } public static T GetJson(string path) diff --git a/src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs b/src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs index b5f014e..43bc50b 100644 --- a/src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs +++ b/src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs @@ -10,11 +10,11 @@ namespace GeneralUpdate.Core.WillMessage public class WillMessageManager { #region Private Members - - public const string DEFULT_WILL_MESSAGE_DIR = @"C:\generalupdate_willmessages"; + private string TempPath = Path.GetTempPath(); + public const string DEFULT_WILL_MESSAGE_DIR = "generalupdate_willmessages"; + public const string BACKUP_DIR = "generalupdate_backup"; public const string DEFULT_WILL_MESSAGE_FILE = "will_message.json"; - - public const string BACKUP_ROOT_PATH = @"C:\generalupdate_backup"; + private string _packetPath; private string _appPath; private string _backupPath; @@ -74,15 +74,15 @@ namespace GeneralUpdate.Core.WillMessage _willMessageFile = null; _backupStack.Clear(); FileUtil.DeleteDir(DEFULT_WILL_MESSAGE_DIR); - FileUtil.DeleteDir(BACKUP_ROOT_PATH); + FileUtil.DeleteDir(GetBackupPath()); } public void Backup(string appPath, string packetPath, string version,string hash,int appType) { - if (!Directory.Exists(BACKUP_ROOT_PATH)) - Directory.CreateDirectory(BACKUP_ROOT_PATH); + if (!Directory.Exists(GetBackupPath())) + Directory.CreateDirectory(GetBackupPath()); - var versionDir = Path.Combine(BACKUP_ROOT_PATH, version, appType == 1 ? "ClientApp" : "UpgradeApp"); + var versionDir = Path.Combine(GetBackupPath(), version, appType == 1 ? "ClientApp" : "UpgradeApp"); if (!Directory.Exists(versionDir)) Directory.CreateDirectory(versionDir); @@ -115,7 +115,7 @@ namespace GeneralUpdate.Core.WillMessage .SetCreateTime(DateTime.Now) .SetChangeTime(DateTime.Now) .Build(); - FileUtil.CreateJson(Path.Combine(DEFULT_WILL_MESSAGE_DIR, DateTime.Now.ToString("yyyyMMdd")), DEFULT_WILL_MESSAGE_FILE, _willMessage); + FileUtil.CreateJson(GetWillMessagePath(), _willMessage); } public void Check() @@ -146,7 +146,11 @@ namespace GeneralUpdate.Core.WillMessage #region Private Methods - private string GetWillMessagePath() => Path.Combine(DEFULT_WILL_MESSAGE_DIR, DateTime.Now.ToString("yyyyMMdd"), DEFULT_WILL_MESSAGE_FILE); + private string GetWillMessagePath() => + Path.Combine(TempPath, DEFULT_WILL_MESSAGE_DIR, DateTime.Now.ToString("yyyyMMdd"), DEFULT_WILL_MESSAGE_FILE); + + private string GetBackupPath() => + Path.Combine(TempPath, BACKUP_DIR); private void ProcessDirectory(string targetDirectory, string basePath, string destPath) { diff --git a/src/c#/GeneralUpdate.Differential/DifferentialCore.cs b/src/c#/GeneralUpdate.Differential/DifferentialCore.cs index 44ec20b..a63a336 100644 --- a/src/c#/GeneralUpdate.Differential/DifferentialCore.cs +++ b/src/c#/GeneralUpdate.Differential/DifferentialCore.cs @@ -117,7 +117,7 @@ namespace GeneralUpdate.Differential //If a file is found that needs to be deleted, a list of files is written to the update package. var exceptFiles = await fileProvider.Except(sourcePath, targetPath); if(exceptFiles != null && exceptFiles.Count() > 0) - FileUtil.CreateJson(patchPath, DELETE_FILES_NAME, exceptFiles); + FileUtil.CreateJson(Path.Combine(patchPath, DELETE_FILES_NAME), exceptFiles); } catch (Exception ex) { -- Gitee From e01e20ac1bd9b2b1a5b9423382d66b0f609aa391 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Wed, 17 Jan 2024 23:13:22 +0800 Subject: [PATCH 04/11] fix: Complete operation --- .../ContentProvider/FileProvider.cs | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-) diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs index 7a03954..2b33396 100644 --- a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs @@ -141,14 +141,8 @@ namespace GeneralUpdate.Differential.ContentProvider /// IJǷݹִ /// Ƿ񱣳Ŀ¼ṹ /// - //public List Handle(string sourceDir,string targetDir, string resultDir, List condition, FileOperations fileOption, SetOperations setOperations,bool recursion,bool integrality) - //{ - // return new List(); - //} - public List Handle(string sourceDir, string targetDir, string resultDir, List condition, FileOperations fileOption, SetOperations setOperations, bool recursion, bool integrality) { - // ȻȡԴĿ¼ĿĿ¼еļϢ IEnumerable sourceFiles = Directory.EnumerateFiles(sourceDir, "*.*", recursion ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) .Select(path => new FileInfo(path)) .Select(fileInfo => new FileNode @@ -174,7 +168,6 @@ namespace GeneralUpdate.Differential.ContentProvider IEnumerable filteredSourceFiles = sourceFiles.Where(file => condition.Any(c => file.Name.Contains(c) || file.Name.EndsWith(c))); IEnumerable filteredTargetFiles = targetFiles.Where(file => condition.Any(c => file.Name.Contains(c) || file.Name.EndsWith(c))); - // мԵõյĽ IEnumerable resultFiles; switch (setOperations) { @@ -191,8 +184,7 @@ namespace GeneralUpdate.Differential.ContentProvider throw new ArgumentException("Invalid operation.", nameof(setOperations)); } - // ִļ - foreach (FileNode file in resultFiles) + foreach (var file in resultFiles) { ExecuteFileOperation(file, fileOption, resultDir, integrality); } @@ -200,15 +192,10 @@ namespace GeneralUpdate.Differential.ContentProvider return resultFiles.ToList(); } - /// - /// ļĹϣֵ. - /// - /// ļ. - /// private string CalculateFileHash(FileInfo file) { - // ֻһռλʵҪʵһļϣֵ. - return string.Empty; + var hashAlgorithm = new Sha256HashAlgorithm(); + return hashAlgorithm.ComputeHash(file.FullName); } /// -- Gitee From daab9da5635c23f57ec6a0c6cc7a09667bf753d6 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Thu, 18 Jan 2024 21:20:26 +0800 Subject: [PATCH 05/11] remove: files --- .../GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj | 4 ---- .../GeneralUpdate.ClientCore/Strategys/PlatformMac/.gitkeep | 0 2 files changed, 4 deletions(-) delete mode 100644 src/c#/GeneralUpdate.ClientCore/Strategys/PlatformMac/.gitkeep diff --git a/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj b/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj index 523523f..2309b8a 100644 --- a/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj +++ b/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj @@ -62,7 +62,6 @@ - @@ -150,7 +149,6 @@ - @@ -244,10 +242,8 @@ - - diff --git a/src/c#/GeneralUpdate.ClientCore/Strategys/PlatformMac/.gitkeep b/src/c#/GeneralUpdate.ClientCore/Strategys/PlatformMac/.gitkeep deleted file mode 100644 index e69de29..0000000 -- Gitee From cd0190f344d9edcd6962067b4ed1547cad219db9 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Thu, 18 Jan 2024 22:14:04 +0800 Subject: [PATCH 06/11] update: Namespace modification --- src/c#/GeneralUpdate.Client/MySample.cs | 13 +- .../GeneralUpdate.ClientCore.csproj | 7 +- .../ContentProvider/FileNode.cs | 2 +- .../ContentProvider/FileProvider-Manage.cs | 143 +++++++++++++++ .../ContentProvider/FileProvider.cs | 136 +------------- .../ContentProvider/FileTree.cs | 2 +- .../ContentProvider/.gitkeep | 0 .../ContentProvider/FileNode.cs | 148 --------------- .../ContentProvider/FileProvider.cs | 116 ------------ .../ContentProvider/FileTree.cs | 173 ------------------ .../DifferentialCore.cs | 5 +- .../GeneralUpdate.Differential.csproj | 6 + 12 files changed, 170 insertions(+), 581 deletions(-) create mode 100644 src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs create mode 100644 src/c#/GeneralUpdate.Differential/ContentProvider/.gitkeep delete mode 100644 src/c#/GeneralUpdate.Differential/ContentProvider/FileNode.cs delete mode 100644 src/c#/GeneralUpdate.Differential/ContentProvider/FileProvider.cs delete mode 100644 src/c#/GeneralUpdate.Differential/ContentProvider/FileTree.cs diff --git a/src/c#/GeneralUpdate.Client/MySample.cs b/src/c#/GeneralUpdate.Client/MySample.cs index 3a35b76..f8f0a7a 100644 --- a/src/c#/GeneralUpdate.Client/MySample.cs +++ b/src/c#/GeneralUpdate.Client/MySample.cs @@ -13,9 +13,9 @@ using GeneralUpdate.Core.Events.CommonArgs; using GeneralUpdate.Differential; using System.IO; using GeneralUpdate.Core.Driver; -using Microsoft.VisualBasic; using System.Diagnostics; using GeneralUpdate.Core.WillMessage; +using GeneralUpdate.Core.ContentProvider; namespace GeneralUpdate.Client { @@ -301,7 +301,6 @@ namespace GeneralUpdate.Client #endregion - #region 测试WillMessage public void TestWillMessage() @@ -323,5 +322,15 @@ namespace GeneralUpdate.Client } #endregion + + #region 文件管理测试 + + public void TestFileProvider() + { + //FileProvider fileProvider = new FileProvider(); + //fileProvider.Handle(); + } + + #endregion } } diff --git a/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj b/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj index 2309b8a..2955dea 100644 --- a/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj +++ b/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj @@ -74,6 +74,10 @@ + + + + @@ -169,9 +173,6 @@ - - - diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileNode.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileNode.cs index bb0851f..26c8ee6 100644 --- a/src/c#/GeneralUpdate.Core/ContentProvider/FileNode.cs +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileNode.cs @@ -1,6 +1,6 @@ using System; -namespace GeneralUpdate.Differential.ContentProvider +namespace GeneralUpdate.Core.ContentProvider { public class FileNode { diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs new file mode 100644 index 0000000..7f9c56c --- /dev/null +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs @@ -0,0 +1,143 @@ +using GeneralUpdate.Core.HashAlgorithms; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace GeneralUpdate.Core.ContentProvider +{ + public enum FileOperations + { + Query, + Delete, + Update, + Add, + Copy + } + + public enum SetOperations + { + Intersection, + Union, + Difference + } + + public partial class FileProvider + { + /// + /// 根据参数内容筛选出sourceDir、targetDir两个文件路径中符合要求的文件信息 + /// + /// 源目录 + /// 目标目录 + /// 筛选结果保存目录 + /// 筛选条件,可以是文件名,可以是文件后缀名 + /// 文件可执行的操作:增、删、查、改、拷贝 + /// 集合运算:交集、并集、差集 + /// 整个方法里的操作是否递归执行 + /// 是否保持目录结构的完整性 + /// + public List Handle(string sourceDir, string targetDir, string resultDir, List condition, FileOperations fileOption, SetOperations setOperations, bool recursion, bool integrality) + { + IEnumerable sourceFiles = Directory.EnumerateFiles(sourceDir, "*.*", recursion ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) + .Select(path => new FileInfo(path)) + .Select(fileInfo => new FileNode + { + Id = fileInfo.GetHashCode(), + Name = fileInfo.Name, + FullName = fileInfo.FullName, + Path = fileInfo.DirectoryName, + Hash = CalculateFileHash(fileInfo) + }); + IEnumerable targetFiles = Directory.EnumerateFiles(targetDir, "*.*", recursion ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) + .Select(path => new FileInfo(path)) + .Select(fileInfo => new FileNode + { + Id = fileInfo.GetHashCode(), + Name = fileInfo.Name, + FullName = fileInfo.FullName, + Path = fileInfo.DirectoryName, + Hash = CalculateFileHash(fileInfo) + }); + + // 然后根据条件筛选满足要求的文件 + IEnumerable filteredSourceFiles = sourceFiles.Where(file => condition.Any(c => file.Name.Contains(c) || file.Name.EndsWith(c))); + IEnumerable filteredTargetFiles = targetFiles.Where(file => condition.Any(c => file.Name.Contains(c) || file.Name.EndsWith(c))); + + IEnumerable resultFiles; + switch (setOperations) + { + case SetOperations.Intersection: + resultFiles = filteredSourceFiles.Intersect(filteredTargetFiles); + break; + case SetOperations.Union: + resultFiles = filteredSourceFiles.Union(filteredTargetFiles); + break; + case SetOperations.Difference: + resultFiles = filteredSourceFiles.Except(filteredTargetFiles); + break; + default: + throw new ArgumentException("Invalid operation.", nameof(setOperations)); + } + + foreach (var file in resultFiles) + { + ExecuteFileOperation(file, fileOption, resultDir, integrality); + } + + return resultFiles.ToList(); + } + + private string CalculateFileHash(FileInfo file) + { + var hashAlgorithm = new Sha256HashAlgorithm(); + return hashAlgorithm.ComputeHash(file.FullName); + } + + /// + /// 执行文件操作. + /// + /// 文件对象. + /// 要执行的操作. + /// 结果目录. + /// 是否保留结构. + private void ExecuteFileOperation(FileNode file, FileOperations operation, string resultDir, bool retainStructure) + { + string destinationPath = Path.Combine(resultDir, retainStructure ? file.RelativePath : file.Name); + + switch (operation) + { + case FileOperations.Add: + // 如果文件已存在,此操作将覆盖现有文件 + File.Copy(file.Path, destinationPath, true); + break; + case FileOperations.Delete: + if (File.Exists(destinationPath)) + { + File.Delete(destinationPath); + } + break; + case FileOperations.Update: + // 在这里,我们假定更新操作意味着复制源文件到目标位置,覆盖现有文件 + File.Copy(file.Path, destinationPath, true); + break; + case FileOperations.Copy: + // 确保目标目录存在 + string directoryName = Path.GetDirectoryName(destinationPath); + if (!Directory.Exists(directoryName)) + { + Directory.CreateDirectory(directoryName); + } + // 拷贝文件到新的位置 + File.Copy(file.Path, destinationPath, true); + break; + case FileOperations.Query: + // 对于“查询”操作,我们不执行任何文件操作,只在控制台中打印出相关信息 + Console.WriteLine($"Found file: {file.FullName}"); + break; + default: + throw new ArgumentException("Invalid operation", nameof(operation)); + } + } + + } +} diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs index 2b33396..4250a40 100644 --- a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs @@ -7,25 +7,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -namespace GeneralUpdate.Differential.ContentProvider +namespace GeneralUpdate.Core.ContentProvider { - public enum FileOperations - { - Query, - Delete, - Update, - Add, - Copy - } - - public enum SetOperations - { - Intersection, - Union, - Difference - } - - public class FileProvider + public partial class FileProvider { private long _fileCount = 0; @@ -128,121 +112,5 @@ namespace GeneralUpdate.Differential.ContentProvider } #endregion Private Methods - - /// - /// ݲɸѡsourceDirtargetDirļ·зҪļϢ - /// - /// ԴĿ¼ - /// ĿĿ¼ - /// ɸѡĿ¼ - /// ɸѡļļ׺ - /// ļִеIJɾ顢ġ - /// 㣺 - /// IJǷݹִ - /// Ƿ񱣳Ŀ¼ṹ - /// - public List Handle(string sourceDir, string targetDir, string resultDir, List condition, FileOperations fileOption, SetOperations setOperations, bool recursion, bool integrality) - { - IEnumerable sourceFiles = Directory.EnumerateFiles(sourceDir, "*.*", recursion ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) - .Select(path => new FileInfo(path)) - .Select(fileInfo => new FileNode - { - Id = fileInfo.GetHashCode(), - Name = fileInfo.Name, - FullName = fileInfo.FullName, - Path = fileInfo.DirectoryName, - Hash = CalculateFileHash(fileInfo) - }); - IEnumerable targetFiles = Directory.EnumerateFiles(targetDir, "*.*", recursion ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) - .Select(path => new FileInfo(path)) - .Select(fileInfo => new FileNode - { - Id = fileInfo.GetHashCode(), - Name = fileInfo.Name, - FullName = fileInfo.FullName, - Path = fileInfo.DirectoryName, - Hash = CalculateFileHash(fileInfo) - }); - - // ȻɸѡҪļ - IEnumerable filteredSourceFiles = sourceFiles.Where(file => condition.Any(c => file.Name.Contains(c) || file.Name.EndsWith(c))); - IEnumerable filteredTargetFiles = targetFiles.Where(file => condition.Any(c => file.Name.Contains(c) || file.Name.EndsWith(c))); - - IEnumerable resultFiles; - switch (setOperations) - { - case SetOperations.Intersection: - resultFiles = filteredSourceFiles.Intersect(filteredTargetFiles); - break; - case SetOperations.Union: - resultFiles = filteredSourceFiles.Union(filteredTargetFiles); - break; - case SetOperations.Difference: - resultFiles = filteredSourceFiles.Except(filteredTargetFiles); - break; - default: - throw new ArgumentException("Invalid operation.", nameof(setOperations)); - } - - foreach (var file in resultFiles) - { - ExecuteFileOperation(file, fileOption, resultDir, integrality); - } - - return resultFiles.ToList(); - } - - private string CalculateFileHash(FileInfo file) - { - var hashAlgorithm = new Sha256HashAlgorithm(); - return hashAlgorithm.ComputeHash(file.FullName); - } - - /// - /// ִļ. - /// - /// ļ. - /// ҪִеIJ. - /// Ŀ¼. - /// Ƿṹ. - private void ExecuteFileOperation(FileNode file, FileOperations operation, string resultDir, bool retainStructure) - { - string destinationPath = Path.Combine(resultDir, retainStructure ? file.RelativePath : file.Name); - - switch (operation) - { - case FileOperations.Add: - // ļѴڣ˲ļ - File.Copy(file.Path, destinationPath, true); - break; - case FileOperations.Delete: - if (File.Exists(destinationPath)) - { - File.Delete(destinationPath); - } - break; - case FileOperations.Update: - // Ǽٶ²ζŸԴļĿλãļ - File.Copy(file.Path, destinationPath, true); - break; - case FileOperations.Copy: - // ȷĿĿ¼ - string directoryName = Path.GetDirectoryName(destinationPath); - if (!Directory.Exists(directoryName)) - { - Directory.CreateDirectory(directoryName); - } - // ļµλ - File.Copy(file.Path, destinationPath, true); - break; - case FileOperations.Query: - // ڡѯDzִκļֻڿ̨дӡϢ - Console.WriteLine($"Found file: {file.FullName}"); - break; - default: - throw new ArgumentException("Invalid operation", nameof(operation)); - } - } - } } \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileTree.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileTree.cs index b77d54f..31fd7f0 100644 --- a/src/c#/GeneralUpdate.Core/ContentProvider/FileTree.cs +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileTree.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Diagnostics; -namespace GeneralUpdate.Differential.ContentProvider +namespace GeneralUpdate.Core.ContentProvider { /// /// Simple file binary tree. diff --git a/src/c#/GeneralUpdate.Differential/ContentProvider/.gitkeep b/src/c#/GeneralUpdate.Differential/ContentProvider/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/c#/GeneralUpdate.Differential/ContentProvider/FileNode.cs b/src/c#/GeneralUpdate.Differential/ContentProvider/FileNode.cs deleted file mode 100644 index bb0851f..0000000 --- a/src/c#/GeneralUpdate.Differential/ContentProvider/FileNode.cs +++ /dev/null @@ -1,148 +0,0 @@ -using System; - -namespace GeneralUpdate.Differential.ContentProvider -{ - public class FileNode - { - #region Public Properties - - public long Id { get; set; } - - public string Name { get; set; } - - public string FullName { get; set; } - - public string Path { get; set; } - - public string Hash { get; set; } - - public FileNode Left { get; set; } - - public FileNode Right { get; set; } - - public int LeftType { get; set; } - - public int RightType { get; set; } - - public string RelativePath { get; set; } - - #endregion Public Properties - - #region Constructors - - public FileNode() - { } - - public FileNode(int id) - { - Id = id; - } - - #endregion Constructors - - #region Public Methods - - public void Add(FileNode node) - { - if (node == null) return; - - if (node.Id < Id) - { - if (Left == null) - { - Left = node; - } - else - { - Left.Add(node); - } - } - else - { - if (Right == null) - { - Right = node; - } - else - { - Right.Add(node); - } - } - } - - public void InfixOrder() - { - if (Left != null) - { - Left.InfixOrder(); - } - if (Right != null) - { - Right.InfixOrder(); - } - } - - public FileNode Search(long id) - { - if (id == Id) - { - return this; - } - else if (id < Id) - { - if (Left == null) return null; - return Left.Search(id); - } - else - { - if (Right == null) return null; - return Right.Search(id); - } - } - - /// - /// Find the parent node of the node that you want to delete. - /// - /// - /// - public FileNode SearchParent(long id) - { - if (Left != null && Left.Id == id || Right != null && Right.Id == id) - { - return this; - } - else - { - if (id < Id && Left != null) - { - return Left.SearchParent(id); - } - else if (id >= Id && Right != null) - { - return Right.SearchParent(id); - } - else - { - return null; - } - } - } - - /// - /// Compare tree nodes equally by Hash and file names. - /// - /// - /// - public override bool Equals(object obj) - { - if (obj == null) return false; - var tempNode = obj as FileNode; - if (tempNode == null) throw new ArgumentException(nameof(tempNode)); - return string.Equals(Hash, tempNode.Hash,StringComparison.OrdinalIgnoreCase) && string.Equals(Name, tempNode.Name,StringComparison.OrdinalIgnoreCase); - } - - public override int GetHashCode() => base.GetHashCode(); - - #endregion Public Methods - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Differential/ContentProvider/FileProvider.cs b/src/c#/GeneralUpdate.Differential/ContentProvider/FileProvider.cs deleted file mode 100644 index f8a6f8f..0000000 --- a/src/c#/GeneralUpdate.Differential/ContentProvider/FileProvider.cs +++ /dev/null @@ -1,116 +0,0 @@ -using GeneralUpdate.Core.HashAlgorithms; -using GeneralUpdate.Differential.Common; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - -namespace GeneralUpdate.Differential.ContentProvider -{ - public class FileProvider - { - private long _fileCount = 0; - - #region Public Methods - - /// - /// Compare two binary trees with different children. - /// - /// Left tree folder path. - /// Right tree folder path. - /// ValueTuple(leftFileNodes,rightFileNodes, differentTreeNode) - public async Task, IEnumerable, IEnumerable>> Compare(string leftPath, string rightPath) - { - return await Task.Run(() => - { - ResetId(); - var leftFileNodes = Read(leftPath); - var rightFileNodes = Read(rightPath); - var leftTree = new FileTree(leftFileNodes); - var rightTree = new FileTree(rightFileNodes); - var differentTreeNode = new List(); - leftTree.Compare(leftTree.GetRoot(), rightTree.GetRoot(), ref differentTreeNode); - return ValueTuple.Create(leftFileNodes, rightFileNodes, differentTreeNode); - }); - } - - /// - /// Using the list on the left as a baseline, find the set of differences between the two file lists. - /// - /// Previous version file list path - /// The current version file list path - /// Except collection - public async Task> Except(string leftPath, string rightPath) - { - return await Task.Run(() => - { - var leftFileNodes = Read(leftPath); - var rightFileNodes = Read(rightPath); - var rightNodeDic = rightFileNodes.ToDictionary(x => x.RelativePath, x => x); - var filesOnlyInLeft = leftFileNodes.Where(f => !rightNodeDic.ContainsKey(f.RelativePath)).ToList(); - return filesOnlyInLeft; - }); - } - - #endregion Public Methods - - #region Private Methods - - /// - /// Recursively read all files in the folder path. - /// - /// folder path. - /// folder root path. - /// different chalders. - private IEnumerable Read(string path, string rootPath = null) - { - var resultFiles = new List(); - if (string.IsNullOrEmpty(rootPath)) rootPath = path; - if (!rootPath.EndsWith("/")) rootPath += "/"; - Uri rootUri = new Uri(rootPath); - foreach (var subPath in Directory.GetFiles(path)) - { - if (IsMatchBlacklist(subPath)) continue; - - var hashAlgorithm = new Sha256HashAlgorithm(); - var hash = hashAlgorithm.ComputeHash(subPath); - var subFileInfo = new FileInfo(subPath); - Uri subUri = new Uri(subFileInfo.FullName); - resultFiles.Add(new FileNode() { Id = GetId(), Path = path, Name = subFileInfo.Name, Hash = hash, FullName = subFileInfo.FullName, RelativePath = rootUri.MakeRelativeUri(subUri).ToString() }); - } - foreach (var subPath in Directory.GetDirectories(path)) - { - resultFiles.AddRange(Read(subPath, rootPath)); - } - return resultFiles; - } - - /// - /// Self-growing file tree node ID. - /// - /// - private long GetId() => Interlocked.Increment(ref _fileCount); - - private void ResetId() => Interlocked.Exchange(ref _fileCount, 0); - - /// - /// Whether the file name in the file path can match the blacklisted file. - /// - /// - /// - private bool IsMatchBlacklist(string subPath) - { - var blackList = Filefilter.GetBlackFiles(); - if (blackList == null) return false; - foreach (var file in blackList) - { - if (subPath.Contains(file)) return true; - } - return false; - } - - #endregion Private Methods - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Differential/ContentProvider/FileTree.cs b/src/c#/GeneralUpdate.Differential/ContentProvider/FileTree.cs deleted file mode 100644 index b77d54f..0000000 --- a/src/c#/GeneralUpdate.Differential/ContentProvider/FileTree.cs +++ /dev/null @@ -1,173 +0,0 @@ -using System.Collections.Generic; -using System.Diagnostics; - -namespace GeneralUpdate.Differential.ContentProvider -{ - /// - /// Simple file binary tree. - /// - public class FileTree - { - #region Private Members - - private FileNode _root; - - #endregion Private Members - - #region Constructors - - public FileTree() - { } - - public FileTree(IEnumerable nodes) - { - foreach (var node in nodes) Add(node); - } - - #endregion Constructors - - #region Public Methods - - public void Add(FileNode node) - { - if (_root == null) - { - _root = node; - } - else - { - _root.Add(node); - } - } - - public void InfixOrder() - { - if (_root != null) - { - _root.InfixOrder(); - } - else - { - Debug.WriteLine("The binary sort tree is empty and cannot be traversed!"); - } - } - - public FileNode Search(long id) => _root == null ? null : _root.Search(id); - - public FileNode SearchParent(long id) => _root == null ? null : _root.SearchParent(id); - - public long DelRightTreeMin(FileNode node) - { - FileNode target = node; - while (target.Left != null) - { - target = target.Left; - } - DelNode(target.Id); - return target.Id; - } - - public void DelNode(long id) - { - if (_root == null) - { - return; - } - else - { - FileNode targetNode = Search(id); - if (targetNode == null) - { - return; - } - if (_root.Left == null && _root.Right == null) - { - _root = null; - return; - } - - FileNode parent = SearchParent(id); - if (targetNode.Left == null && targetNode.Right == null) - { - if (parent.Left != null && parent.Left.Id == id) - { - parent.Left = null; - } - else if (parent.Right != null && parent.Right.Id == id) - { - parent.Right = null; - } - } - else if (targetNode.Left != null && targetNode.Right != null) - { - long minVal = DelRightTreeMin(targetNode.Right); - targetNode.Id = minVal; - } - else - { - if (targetNode.Left != null) - { - if (parent.Left.Id == id) - { - parent.Left = targetNode.Left; - } - else - { - parent.Right = targetNode.Left; - } - } - else - { - if (parent.Left.Id == id) - { - parent.Left = targetNode.Right; - } - else - { - parent.Right = targetNode.Right; - } - } - } - } - } - - /// - /// Starting from the root node, recursively compares two different child nodes of the binary tree and nodes that are not included. - /// - /// - /// - /// - public void Compare(FileNode node, FileNode node0, ref List nodes) - { - if (node != null && node.Left != null) - { - if (!node.Equals(node0) && node0 != null) nodes.Add(node0); - Compare(node.Left, node0.Left, ref nodes); - } - else if (node0 != null && node0.Left != null) - { - nodes.Add(node0); - Compare(node.Left, node0.Left, ref nodes); - } - - if (node != null && node.Right != null) - { - if (!node.Equals(node0) && node0 != null) nodes.Add(node0); - Compare(node.Right, node0 == null ? null : node0.Right, ref nodes); - } - else if (node0 != null && node0.Right != null) - { - nodes.Add(node0); - Compare(node == null ? null : node.Right, node0.Right, ref nodes); - } - else if (node0 != null) - { - nodes.Add(node0); - } - } - - public FileNode GetRoot() => _root; - - #endregion Public Methods - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Differential/DifferentialCore.cs b/src/c#/GeneralUpdate.Differential/DifferentialCore.cs index a63a336..7e47993 100644 --- a/src/c#/GeneralUpdate.Differential/DifferentialCore.cs +++ b/src/c#/GeneralUpdate.Differential/DifferentialCore.cs @@ -1,9 +1,8 @@ -using GeneralUpdate.Core.HashAlgorithms; +using GeneralUpdate.Core.ContentProvider; +using GeneralUpdate.Core.HashAlgorithms; using GeneralUpdate.Core.Utils; using GeneralUpdate.Differential.Binary; using GeneralUpdate.Differential.Common; -using GeneralUpdate.Differential.ContentProvider; -using GeneralUpdate.Zip.Events; using System; using System.Collections.Generic; using System.IO; diff --git a/src/c#/GeneralUpdate.Differential/GeneralUpdate.Differential.csproj b/src/c#/GeneralUpdate.Differential/GeneralUpdate.Differential.csproj index 00fffc8..aa6072f 100644 --- a/src/c#/GeneralUpdate.Differential/GeneralUpdate.Differential.csproj +++ b/src/c#/GeneralUpdate.Differential/GeneralUpdate.Differential.csproj @@ -14,6 +14,7 @@ + @@ -25,6 +26,10 @@ + + + + @@ -54,6 +59,7 @@ + -- Gitee From 1b1a4a1515462d4363075d26aa6056550896334f Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Thu, 18 Jan 2024 23:51:04 +0800 Subject: [PATCH 07/11] =?UTF-8?q?clear=EF=BC=9A=20clear=20all=20code=20fil?= =?UTF-8?q?es?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/c#/GeneralUpdate.Api/Program.cs | 2 - .../Services/GeneralUpdateService.cs | 5 +- .../Services/IUpdateService.cs | 4 +- src/c#/GeneralUpdate.Client/MySample.cs | 50 +++++----- src/c#/GeneralUpdate.Client/Program.cs | 12 +-- .../GeneralClientBootstrap.cs | 14 +-- .../GeneralClientOSS.cs | 14 +-- .../GeneralUpdate.ClientCore.csproj | 5 +- .../Bootstrap/AbstractBootstrap.cs | 20 ++-- .../ContentProvider/FileNode.cs | 4 +- .../ContentProvider/FileProvider-Manage.cs | 51 +++++++++- .../ContentProvider/FileProvider.cs | 2 +- .../Entity/Assembler/ProcessAssembler.cs | 39 +++++++- .../Domain/Entity/ProcessInfo.cs | 37 ++++++- .../Domain/PO/Assembler/VersionAssembler.cs | 2 +- .../GeneralUpdate.Core/Domain/PO/VersionPO.cs | 2 +- .../Domain/PO/WillMessagePO.cs | 10 +- .../Domain/Service/VersionService.cs | 47 ++++++++- .../Driver/BackupDriverCommand.cs | 4 +- .../Driver/CommandExecutor.cs | 2 +- .../Driver/DeleteDriverCommand.cs | 4 +- .../Driver/DriverInformation.cs | 10 +- .../Driver/InstallDriverCommand.cs | 4 +- .../Driver/RestoreDriverCommand.cs | 6 +- .../Events/CommonArgs/ExceptionEventArgs.cs | 2 +- .../Events/OSSArgs/OSSDownloadArgs.cs | 2 +- .../CustomException/GeneralUpdateException.cs | 2 +- .../Exceptions/ThrowExceptionUtility.cs | 8 +- .../GeneralUpdateBootstrap.cs | 6 +- src/c#/GeneralUpdate.Core/GeneralUpdateOSS.cs | 10 +- .../HashAlgorithms/Md5HashAlgorithm.cs | 4 +- .../HashAlgorithms/Sha1HashAlgorithm.cs | 4 +- .../HashAlgorithms/Sha256HashAlgorithm.cs | 4 +- .../Pipelines/Context/BaseContext.cs | 3 +- .../Pipelines/Middleware/DriveMiddleware.cs | 12 +-- .../Pipelines/Middleware/HashMiddleware.cs | 1 - .../Middleware/MiddlewareExtensions.cs | 6 +- .../Middleware/WillMessageMiddleware.cs | 4 +- .../Strategys/AbstractStrategy.cs | 2 +- .../Strategys/OSSStrategy.cs | 20 ++-- .../PlatformWindows/WindowsStrategy.cs | 6 +- .../GeneralUpdate.Core/Utils/ConvertUtil.cs | 77 --------------- src/c#/GeneralUpdate.Core/Utils/FileUtil.cs | 71 ------------- src/c#/GeneralUpdate.Core/Utils/HttpUtil.cs | 87 ---------------- .../WillMessage/WillMessageManager.cs | 40 ++++---- .../Common/DirectoryComparer.cs | 2 +- .../Config/ConfigFactory.cs | 1 - .../Config/Handles/IniHandle.cs | 8 +- .../Config/Handles/JsonHandle.cs | 3 +- .../DifferentialCore.cs | 19 ++-- .../GeneralUpdate.Differential.csproj | 2 +- .../GeneralUpdate.Maui.OSS.csproj | 10 +- .../GeneralUpdateOSS.cs | 6 +- .../Platforms/Android/AndroidManifest.xml | 2 +- .../Platforms/Android/Strategy.cs | 6 +- src/c#/GeneralUpdate.Maui.OSS/Utils/.gitkeep | 0 src/c#/GeneralUpdate.OSSClient/App.xaml | 2 +- src/c#/GeneralUpdate.OSSClient/AppShell.xaml | 3 +- src/c#/GeneralUpdate.OSSClient/MainPage.xaml | 4 +- src/c#/GeneralUpdate.OSSClient/MauiProgram.cs | 2 +- .../Platforms/Android/MainActivity.cs | 1 - .../Resources/Styles/Colors.xaml | 29 +++--- .../Resources/Styles/Styles.xaml | 99 +++++++++---------- .../GeneralUpdate.SystemService.csproj | 41 +++++++- .../Properties/launchSettings.json | 2 +- .../Services/WillMessageService.cs | 19 ++-- .../appsettings.Development.json | 2 +- .../appsettings.json | 2 +- src/c#/GeneralUpdate.Upgrad/Program.cs | 2 - 69 files changed, 474 insertions(+), 514 deletions(-) delete mode 100644 src/c#/GeneralUpdate.Core/Utils/ConvertUtil.cs delete mode 100644 src/c#/GeneralUpdate.Core/Utils/FileUtil.cs delete mode 100644 src/c#/GeneralUpdate.Core/Utils/HttpUtil.cs delete mode 100644 src/c#/GeneralUpdate.Maui.OSS/Utils/.gitkeep diff --git a/src/c#/GeneralUpdate.Api/Program.cs b/src/c#/GeneralUpdate.Api/Program.cs index 16c966a..8babcdf 100644 --- a/src/c#/GeneralUpdate.Api/Program.cs +++ b/src/c#/GeneralUpdate.Api/Program.cs @@ -1,9 +1,7 @@ using GeneralUpdate.AspNetCore.DTO; -using GeneralUpdate.AspNetCore.Hubs; using GeneralUpdate.AspNetCore.Services; using GeneralUpdate.Core.Domain.DTO; using GeneralUpdate.Core.Domain.Enum; -using Microsoft.AspNetCore.SignalR; using Newtonsoft.Json; var builder = WebApplication.CreateBuilder(args); diff --git a/src/c#/GeneralUpdate.AspNetCore/Services/GeneralUpdateService.cs b/src/c#/GeneralUpdate.AspNetCore/Services/GeneralUpdateService.cs index d65c713..042b984 100644 --- a/src/c#/GeneralUpdate.AspNetCore/Services/GeneralUpdateService.cs +++ b/src/c#/GeneralUpdate.AspNetCore/Services/GeneralUpdateService.cs @@ -64,10 +64,9 @@ namespace GeneralUpdate.AspNetCore.Services if (string.IsNullOrEmpty(clientAppkey) || string.IsNullOrEmpty(appSecretKey)) throw new NullReferenceException("The APP key does not exist !"); } - public string Report(int clientType, string clientVersion, string clientAppkey, string appSecretKey, string meesage, string dumpBase64, string logBase64, Exception exception) => string.Empty; - - private void ParameterVerification(int clientType, string clientVersion, string clientAppkey, string appSecretKey, string meesage, string dumpBase64, string logBase64, Exception exception) { } + private void ParameterVerification(int clientType, string clientVersion, string clientAppkey, string appSecretKey, string meesage, string dumpBase64, string logBase64, Exception exception) + { } } } \ No newline at end of file diff --git a/src/c#/GeneralUpdate.AspNetCore/Services/IUpdateService.cs b/src/c#/GeneralUpdate.AspNetCore/Services/IUpdateService.cs index 7e49511..d32b541 100644 --- a/src/c#/GeneralUpdate.AspNetCore/Services/IUpdateService.cs +++ b/src/c#/GeneralUpdate.AspNetCore/Services/IUpdateService.cs @@ -20,8 +20,8 @@ namespace GeneralUpdate.AspNetCore.Services string Update(int clientType, string clientVersion, string serverLastVersion, string clientAppKey, string appSecretKey, bool isForce, List versions); /// - /// When this web api is called at the end of the automatic update, it does not mean that every call is successful. - /// Failure, rollback, and success scenarios will inform the server of the result of the update through this web api. + /// When this web api is called at the end of the automatic update, it does not mean that every call is successful. + /// Failure, rollback, and success scenarios will inform the server of the result of the update through this web api. /// If there is an exception let the decision maker decide whether to fix the problem by pushing the latest version of the update again. /// /// 1:ClientApp 2:UpdateApp diff --git a/src/c#/GeneralUpdate.Client/MySample.cs b/src/c#/GeneralUpdate.Client/MySample.cs index f8f0a7a..d125ce7 100644 --- a/src/c#/GeneralUpdate.Client/MySample.cs +++ b/src/c#/GeneralUpdate.Client/MySample.cs @@ -1,21 +1,16 @@ using GeneralUpdate.ClientCore; using GeneralUpdate.Core.Bootstrap; +using GeneralUpdate.Core.ContentProvider; using GeneralUpdate.Core.Domain.Entity; -using GeneralUpdate.Core.Events.MultiEventArgs; -using GeneralUpdate.Core.Strategys.PlatformWindows; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using GeneralUpdate.Core.Domain.Enum; +using GeneralUpdate.Core.Driver; using GeneralUpdate.Core.Events.CommonArgs; +using GeneralUpdate.Core.Events.MultiEventArgs; +using GeneralUpdate.Core.Strategys.PlatformWindows; +using GeneralUpdate.Core.WillMessage; using GeneralUpdate.Differential; -using System.IO; -using GeneralUpdate.Core.Driver; using System.Diagnostics; -using GeneralUpdate.Core.WillMessage; -using GeneralUpdate.Core.ContentProvider; +using System.Text; namespace GeneralUpdate.Client { @@ -39,7 +34,7 @@ namespace GeneralUpdate.Client if (isUpdate) Upgrade(); } - #endregion + #endregion 推送功能 #region 常规更新 @@ -212,14 +207,13 @@ namespace GeneralUpdate.Client private void DispatchMessage(string message) { - } - #endregion + #endregion 常规更新 #region 测试二进制更新包整理 - public async Task TestDifferentialClean() + public async Task TestDifferentialClean() { var path1 = "D:\\packet\\source"; var path2 = "D:\\packet\\target"; @@ -227,14 +221,14 @@ namespace GeneralUpdate.Client await DifferentialCore.Instance.Clean(path1, path2, path3); } - public async Task TestDifferentialDirty() + public async Task TestDifferentialDirty() { var path1 = "D:\\packet\\source"; var path2 = "D:\\packet\\patchs"; await DifferentialCore.Instance.Dirty(path1, path2); } - #endregion + #endregion 测试二进制更新包整理 #region 测试驱动功能 @@ -299,7 +293,7 @@ namespace GeneralUpdate.Client private bool IsDriverFile(string filePath) => string.Equals(Path.GetExtension(filePath), ".inf", StringComparison.OrdinalIgnoreCase); - #endregion + #endregion 测试驱动功能 #region 测试WillMessage @@ -312,7 +306,7 @@ namespace GeneralUpdate.Client for (int i = 0; i < 1; i++) { var version = "1.0.0." + i; - WillMessageManager.Instance.Backup(path1,path2, version, hash, 1); + WillMessageManager.Instance.Backup(path1, path2, version, hash, 1); } WillMessageManager.Instance.Builder(); var obj = WillMessageManager.Instance.GetWillMessage(); @@ -321,16 +315,22 @@ namespace GeneralUpdate.Client //WillMessageManager.Instance.Clear(); } - #endregion + #endregion 测试WillMessage #region 文件管理测试 - public void TestFileProvider() + public void TestFileProvider() { - //FileProvider fileProvider = new FileProvider(); - //fileProvider.Handle(); + var sourcePath = "D:\\packet\\source"; + var targetPath = "D:\\packet\\target"; + var resultPath = "D:\\packet\\patchs"; + + FileProvider fileProvider = new FileProvider(); + var list = fileProvider.Handle(sourcePath, targetPath, resultPath, null, FileOperations.Query, SetOperations.Intersection, true, true); + foreach (var item in list) + Console.WriteLine(item.Name); } - #endregion + #endregion 文件管理测试 } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Client/Program.cs b/src/c#/GeneralUpdate.Client/Program.cs index 6bc7d2b..1b9dd51 100644 --- a/src/c#/GeneralUpdate.Client/Program.cs +++ b/src/c#/GeneralUpdate.Client/Program.cs @@ -1,14 +1,12 @@ -using GeneralUpdate.Core.HashAlgorithms; - -namespace GeneralUpdate.Client +namespace GeneralUpdate.Client { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { MySample sample = new MySample(); - sample.TestWillMessage(); - //Task.Run(async() => + sample.TestFileProvider(); + //Task.Run(async() => //{ // //415eed05eb310f480d1e4d15516fa00e484ddb9f416908b217f17b782ded2030 // //var zip1 = @"D:\github_project\WpfClient\WebApi\UpdateFiles\WpfClient_1_24.1.5.1218.zip"; @@ -27,4 +25,4 @@ namespace GeneralUpdate.Client Console.Read(); } } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.ClientCore/GeneralClientBootstrap.cs b/src/c#/GeneralUpdate.ClientCore/GeneralClientBootstrap.cs index d5d74d5..da78726 100644 --- a/src/c#/GeneralUpdate.ClientCore/GeneralClientBootstrap.cs +++ b/src/c#/GeneralUpdate.ClientCore/GeneralClientBootstrap.cs @@ -158,7 +158,7 @@ namespace GeneralUpdate.ClientCore } /// - /// Add an asynchronous custom operation. + /// Add an asynchronous custom operation. /// In theory, any custom operation can be done. It is recommended to register the environment check method to ensure that there are normal dependencies and environments after the update is completed. /// /// @@ -172,7 +172,7 @@ namespace GeneralUpdate.ClientCore } /// - /// Add a synchronization custom operation. + /// Add a synchronization custom operation. /// In theory, any custom operation can be done. It is recommended to register the environment check method to ensure that there are normal dependencies and environments after the update is completed. /// /// @@ -223,10 +223,10 @@ namespace GeneralUpdate.ClientCore } /// - /// Performs all injected custom operations. + /// Performs all injected custom operations. /// /// - private async Task ExecuteCustomOptions() + private async Task ExecuteCustomOptions() { if (_customTaskOptions.Any()) { @@ -242,7 +242,7 @@ namespace GeneralUpdate.ClientCore foreach (var option in _customOptions) { var isSuccess = option.Invoke(); - if (!isSuccess) + if (!isSuccess) Core.Events.EventManager.Instance.Dispatch>(this, new Core.Events.CommonArgs.ExceptionEventArgs($"{nameof(option)}Execution failure!")); } } @@ -251,7 +251,7 @@ namespace GeneralUpdate.ClientCore /// /// The values passed between processes during previous updates are cleared when the client starts. /// - private void ClearEnvironmentVariable() + private void ClearEnvironmentVariable() { try { @@ -278,7 +278,7 @@ namespace GeneralUpdate.ClientCore foreach (var item in Packet.UpdateVersions) { var msg = willMessage.Message.Peek(); - if (string.Equals(msg.Version, item.Version,StringComparison.OrdinalIgnoreCase)) + if (string.Equals(msg.Version, item.Version, StringComparison.OrdinalIgnoreCase)) { return false; } diff --git a/src/c#/GeneralUpdate.ClientCore/GeneralClientOSS.cs b/src/c#/GeneralUpdate.ClientCore/GeneralClientOSS.cs index fb5af43..c08f1e5 100644 --- a/src/c#/GeneralUpdate.ClientCore/GeneralClientOSS.cs +++ b/src/c#/GeneralUpdate.ClientCore/GeneralClientOSS.cs @@ -1,7 +1,7 @@ -using GeneralUpdate.Core.Domain.Entity; +using GeneralUpdate.Core.ContentProvider; +using GeneralUpdate.Core.Domain.Entity; using GeneralUpdate.Core.Domain.Entity.Assembler; using GeneralUpdate.Core.Domain.PO; -using GeneralUpdate.Core.Utils; using System; using System.Collections.Generic; using System.Diagnostics; @@ -32,7 +32,7 @@ namespace GeneralUpdate.ClientCore var versionsFilePath = Path.Combine(basePath, configParams.VersionFileName); DownloadFile(configParams.Url + "/" + configParams.VersionFileName, versionsFilePath); if (!File.Exists(versionsFilePath)) return; - var versions = FileUtil.GetJson>(versionsFilePath); + var versions = FileProvider.GetJson>(versionsFilePath); if (versions == null || versions.Count == 0) return; versions = versions.OrderByDescending(x => x.PubTime).ToList(); var newVersion = versions.First(); @@ -49,7 +49,7 @@ namespace GeneralUpdate.ClientCore GeneralUpdate.Core.Events.EventManager.Instance.Dispatch>(typeof(GeneralClientOSS), new GeneralUpdate.Core.Events.CommonArgs.ExceptionEventArgs(ex)); throw new Exception($"GeneralClientOSS update exception ! {ex.Message}", ex.InnerException); } - finally + finally { Process.GetCurrentProcess().Kill(); } @@ -62,19 +62,19 @@ namespace GeneralUpdate.ClientCore /// /// /// true: Upgrade required , false: No upgrade is required - private static bool IsUpgrade(string clientVersion,string serverVersion) + private static bool IsUpgrade(string clientVersion, string serverVersion) { if (string.IsNullOrWhiteSpace(clientVersion) || string.IsNullOrWhiteSpace(serverVersion)) return false; Version currentClientVersion = null; Version currentServerVersion = null; bool isParseClientVersion = Version.TryParse(clientVersion, out currentClientVersion); bool isParseServerVersion = Version.TryParse(serverVersion, out currentServerVersion); - if(!isParseClientVersion || !isParseServerVersion) return false; + if (!isParseClientVersion || !isParseServerVersion) return false; if (currentClientVersion < currentServerVersion) return true; return false; } - private static void DownloadFile(string url,string path) + private static void DownloadFile(string url, string path) { using (var webClient = new WebClient()) { diff --git a/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj b/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj index 2955dea..f2f1d0e 100644 --- a/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj +++ b/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj @@ -64,6 +64,7 @@ + @@ -76,6 +77,7 @@ + @@ -154,9 +156,6 @@ - - - diff --git a/src/c#/GeneralUpdate.Core/Bootstrap/AbstractBootstrap.cs b/src/c#/GeneralUpdate.Core/Bootstrap/AbstractBootstrap.cs index 9b45207..081f6ec 100644 --- a/src/c#/GeneralUpdate.Core/Bootstrap/AbstractBootstrap.cs +++ b/src/c#/GeneralUpdate.Core/Bootstrap/AbstractBootstrap.cs @@ -1,11 +1,11 @@ -using GeneralUpdate.Core.Domain.Entity; +using GeneralUpdate.Core.ContentProvider; +using GeneralUpdate.Core.Domain.Entity; using GeneralUpdate.Core.Domain.Enum; using GeneralUpdate.Core.Download; using GeneralUpdate.Core.Events; using GeneralUpdate.Core.Events.CommonArgs; using GeneralUpdate.Core.Events.MultiEventArgs; using GeneralUpdate.Core.Strategys; -using GeneralUpdate.Core.Utils; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -62,7 +62,7 @@ namespace GeneralUpdate.Core.Bootstrap Packet.Encoding = GetOption(UpdateOption.Encoding) ?? Encoding.Default; Packet.DownloadTimeOut = GetOption(UpdateOption.DownloadTimeOut); Packet.AppName = $"{Packet.AppName ?? GetOption(UpdateOption.MainApp)}{EXECUTABLE_FILE}"; - Packet.TempPath = $"{FileUtil.GetTempDirectory(Packet.LastVersion)}{Path.DirectorySeparatorChar}"; + Packet.TempPath = $"{FileProvider.GetTempDirectory(Packet.LastVersion)}{Path.DirectorySeparatorChar}"; Packet.DriveEnabled = GetOption(UpdateOption.Drive) ?? false; Packet.WillMessageEnabled = GetOption(UpdateOption.WillMessage) ?? false; var manager = new DownloadManager(Packet.TempPath, Packet.Format, Packet.DownloadTimeOut); @@ -95,7 +95,7 @@ namespace GeneralUpdate.Core.Bootstrap return _strategy; } - protected string GetPlatform()=> _strategy.GetPlatform(); + protected string GetPlatform() => _strategy.GetPlatform(); protected IStrategy ExecuteStrategy() { @@ -173,17 +173,17 @@ namespace GeneralUpdate.Core.Bootstrap #region Callback event. - public TBootstrap AddListenerMultiAllDownloadCompleted(Action callbackAction)=> AddListener(callbackAction); + public TBootstrap AddListenerMultiAllDownloadCompleted(Action callbackAction) => AddListener(callbackAction); - public TBootstrap AddListenerMultiDownloadProgress(Action callbackAction)=> AddListener(callbackAction); + public TBootstrap AddListenerMultiDownloadProgress(Action callbackAction) => AddListener(callbackAction); - public TBootstrap AddListenerMultiDownloadCompleted(Action callbackAction)=> AddListener(callbackAction); + public TBootstrap AddListenerMultiDownloadCompleted(Action callbackAction) => AddListener(callbackAction); - public TBootstrap AddListenerMultiDownloadError(Action callbackAction)=> AddListener(callbackAction); + public TBootstrap AddListenerMultiDownloadError(Action callbackAction) => AddListener(callbackAction); - public TBootstrap AddListenerMultiDownloadStatistics(Action callbackAction)=> AddListener(callbackAction); + public TBootstrap AddListenerMultiDownloadStatistics(Action callbackAction) => AddListener(callbackAction); - public TBootstrap AddListenerException(Action callbackAction)=> AddListener(callbackAction); + public TBootstrap AddListenerException(Action callbackAction) => AddListener(callbackAction); protected TBootstrap AddListener(Action callbackAction) where TArgs : EventArgs { diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileNode.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileNode.cs index 26c8ee6..b74a059 100644 --- a/src/c#/GeneralUpdate.Core/ContentProvider/FileNode.cs +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileNode.cs @@ -25,7 +25,7 @@ namespace GeneralUpdate.Core.ContentProvider public int RightType { get; set; } public string RelativePath { get; set; } - + #endregion Public Properties #region Constructors @@ -138,7 +138,7 @@ namespace GeneralUpdate.Core.ContentProvider if (obj == null) return false; var tempNode = obj as FileNode; if (tempNode == null) throw new ArgumentException(nameof(tempNode)); - return string.Equals(Hash, tempNode.Hash,StringComparison.OrdinalIgnoreCase) && string.Equals(Name, tempNode.Name,StringComparison.OrdinalIgnoreCase); + return string.Equals(Hash, tempNode.Hash, StringComparison.OrdinalIgnoreCase) && string.Equals(Name, tempNode.Name, StringComparison.OrdinalIgnoreCase); } public override int GetHashCode() => base.GetHashCode(); diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs index 7f9c56c..df65f26 100644 --- a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs @@ -22,7 +22,7 @@ namespace GeneralUpdate.Core.ContentProvider Difference } - public partial class FileProvider + public partial class FileProvider { /// /// 根据参数内容筛选出sourceDir、targetDir两个文件路径中符合要求的文件信息 @@ -69,12 +69,15 @@ namespace GeneralUpdate.Core.ContentProvider case SetOperations.Intersection: resultFiles = filteredSourceFiles.Intersect(filteredTargetFiles); break; + case SetOperations.Union: resultFiles = filteredSourceFiles.Union(filteredTargetFiles); break; + case SetOperations.Difference: resultFiles = filteredSourceFiles.Except(filteredTargetFiles); break; + default: throw new ArgumentException("Invalid operation.", nameof(setOperations)); } @@ -110,16 +113,19 @@ namespace GeneralUpdate.Core.ContentProvider // 如果文件已存在,此操作将覆盖现有文件 File.Copy(file.Path, destinationPath, true); break; + case FileOperations.Delete: if (File.Exists(destinationPath)) { File.Delete(destinationPath); } break; + case FileOperations.Update: // 在这里,我们假定更新操作意味着复制源文件到目标位置,覆盖现有文件 File.Copy(file.Path, destinationPath, true); break; + case FileOperations.Copy: // 确保目标目录存在 string directoryName = Path.GetDirectoryName(destinationPath); @@ -130,14 +136,55 @@ namespace GeneralUpdate.Core.ContentProvider // 拷贝文件到新的位置 File.Copy(file.Path, destinationPath, true); break; + case FileOperations.Query: // 对于“查询”操作,我们不执行任何文件操作,只在控制台中打印出相关信息 Console.WriteLine($"Found file: {file.FullName}"); break; + default: throw new ArgumentException("Invalid operation", nameof(operation)); } } + public static string GetTempDirectory(string name) + { + var path2 = $"generalupdate_{DateTime.Now.ToString("yyyy-MM-dd")}_{name}"; + var tempDir = Path.Combine(Path.GetTempPath(), path2); + if (!Directory.Exists(tempDir)) + { + Directory.CreateDirectory(tempDir); + } + return tempDir; + } + + public static FileInfo[] GetAllFiles(string path) + { + try + { + var files = new List(); + files.AddRange(new DirectoryInfo(path).GetFiles()); + var tmpDir = new DirectoryInfo(path).GetDirectories(); + foreach (var dic in tmpDir) + { + files.AddRange(GetAllFiles(dic.FullName)); + } + return files.ToArray(); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete the backup file directory and recursively delete all backup content. + /// + public static void DeleteDir(string path) + { + if (string.IsNullOrWhiteSpace(path)) return; + if (Directory.Exists(path)) + Directory.Delete(path, true); + } } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs index 4250a40..7767c84 100644 --- a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs @@ -44,7 +44,7 @@ namespace GeneralUpdate.Core.ContentProvider /// Except collection public async Task> Except(string leftPath, string rightPath) { - return await Task.Run(() => + return await Task.Run(() => { var leftFileNodes = Read(leftPath); var rightFileNodes = Read(rightPath); diff --git a/src/c#/GeneralUpdate.Core/Domain/Entity/Assembler/ProcessAssembler.cs b/src/c#/GeneralUpdate.Core/Domain/Entity/Assembler/ProcessAssembler.cs index 62a8928..39a1c69 100644 --- a/src/c#/GeneralUpdate.Core/Domain/Entity/Assembler/ProcessAssembler.cs +++ b/src/c#/GeneralUpdate.Core/Domain/Entity/Assembler/ProcessAssembler.cs @@ -1,5 +1,6 @@ using GeneralUpdate.Core.Utils; using System; +using System.Text; namespace GeneralUpdate.Core.Domain.Entity.Assembler { @@ -27,11 +28,47 @@ namespace GeneralUpdate.Core.Domain.Entity.Assembler packet.ClientVersion = info.CurrentVersion; packet.LastVersion = info.LastVersion; packet.UpdateLogUrl = info.LogUrl; - packet.Encoding = ConvertUtil.ToEncoding(info.CompressEncoding); + packet.Encoding = ToEncoding(info.CompressEncoding); packet.Format = info.CompressFormat; packet.DownloadTimeOut = info.DownloadTimeOut; packet.UpdateVersions = info.UpdateVersions; return packet; } + + private static Encoding ToEncoding(int type) + { + Encoding encoding = Encoding.Default; + switch (type) + { + case 1: + encoding = Encoding.UTF8; + break; + + case 2: + encoding = Encoding.UTF7; + break; + + case 3: + encoding = Encoding.UTF32; + break; + + case 4: + encoding = Encoding.Unicode; + break; + + case 5: + encoding = Encoding.BigEndianUnicode; + break; + + case 6: + encoding = Encoding.ASCII; + break; + + case 7: + encoding = Encoding.Default; + break; + } + return encoding; + } } } \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Domain/Entity/ProcessInfo.cs b/src/c#/GeneralUpdate.Core/Domain/Entity/ProcessInfo.cs index 9788378..4082dd9 100644 --- a/src/c#/GeneralUpdate.Core/Domain/Entity/ProcessInfo.cs +++ b/src/c#/GeneralUpdate.Core/Domain/Entity/ProcessInfo.cs @@ -1,6 +1,5 @@ using GeneralUpdate.Core.Domain.DTO; using GeneralUpdate.Core.Domain.DTO.Assembler; -using GeneralUpdate.Core.Utils; using System; using System.Collections.Generic; using System.IO; @@ -22,7 +21,7 @@ namespace GeneralUpdate.Core.Domain.Entity LastVersion = lastVersion ?? throw new ArgumentNullException(nameof(lastVersion)); LogUrl = logUrl; compressEncoding = compressEncoding ?? Encoding.Default; - CompressEncoding = ConvertUtil.ToEncodingType(compressEncoding); + CompressEncoding = ToEncodingType(compressEncoding); CompressFormat = compressFormat; if (downloadTimeOut < 0) throw new ArgumentException("Timeout must be greater than 0 !"); DownloadTimeOut = downloadTimeOut; @@ -31,6 +30,40 @@ namespace GeneralUpdate.Core.Domain.Entity UpdateVersions = VersionAssembler.ToEntitys(updateVersions); } + private int ToEncodingType(Encoding encoding) + { + int type = -1; + if (encoding == Encoding.UTF8) + { + type = 1; + } + else if (encoding == Encoding.UTF7) + { + type = 2; + } + else if (encoding == Encoding.UTF32) + { + type = 3; + } + else if (encoding == Encoding.Unicode) + { + type = 4; + } + else if (encoding == Encoding.BigEndianUnicode) + { + type = 5; + } + else if (encoding == Encoding.ASCII) + { + type = 6; + } + else if (encoding == Encoding.Default) + { + type = 7; + } + return type; + } + /// /// 1:MainApp 2:UpdateApp /// diff --git a/src/c#/GeneralUpdate.Core/Domain/PO/Assembler/VersionAssembler.cs b/src/c#/GeneralUpdate.Core/Domain/PO/Assembler/VersionAssembler.cs index 4b7e008..57cea11 100644 --- a/src/c#/GeneralUpdate.Core/Domain/PO/Assembler/VersionAssembler.cs +++ b/src/c#/GeneralUpdate.Core/Domain/PO/Assembler/VersionAssembler.cs @@ -20,4 +20,4 @@ namespace GeneralUpdate.Core.Domain.PO.Assembler return new VersionInfo(versionDO.PubTime, versionDO.Name, versionDO.Hash, versionDO.Version, versionDO.Url); } } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Domain/PO/VersionPO.cs b/src/c#/GeneralUpdate.Core/Domain/PO/VersionPO.cs index 43f9161..bca517a 100644 --- a/src/c#/GeneralUpdate.Core/Domain/PO/VersionPO.cs +++ b/src/c#/GeneralUpdate.Core/Domain/PO/VersionPO.cs @@ -30,4 +30,4 @@ /// public string Url { get; set; } } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Domain/PO/WillMessagePO.cs b/src/c#/GeneralUpdate.Core/Domain/PO/WillMessagePO.cs index 0daf488..30dca50 100644 --- a/src/c#/GeneralUpdate.Core/Domain/PO/WillMessagePO.cs +++ b/src/c#/GeneralUpdate.Core/Domain/PO/WillMessagePO.cs @@ -9,17 +9,19 @@ namespace GeneralUpdate.Core.Domain.PO /// Processing has not yet begun. /// NotStarted, + /// /// Processing completed. /// Completed, + /// /// Processing failure. /// Failed } - public class BackupPO + public class BackupPO { public string AppPath { get; set; } @@ -39,7 +41,8 @@ namespace GeneralUpdate.Core.Domain.PO public DateTime CreateTime { get; private set; } public DateTime ChangeTime { get; private set; } - private WillMessagePO() { } + private WillMessagePO() + { } public class Builder { @@ -75,5 +78,4 @@ namespace GeneralUpdate.Core.Domain.PO } } } - -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Domain/Service/VersionService.cs b/src/c#/GeneralUpdate.Core/Domain/Service/VersionService.cs index 6aa13d7..3da4cd7 100644 --- a/src/c#/GeneralUpdate.Core/Domain/Service/VersionService.cs +++ b/src/c#/GeneralUpdate.Core/Domain/Service/VersionService.cs @@ -1,7 +1,12 @@ using GeneralUpdate.Core.Domain.DTO; using GeneralUpdate.Core.Domain.Enum; -using GeneralUpdate.Core.Utils; +using Newtonsoft.Json; using System; +using System.IO; +using System.Net; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; +using System.Text; using System.Threading.Tasks; namespace GeneralUpdate.Core.Domain.Service @@ -18,11 +23,49 @@ namespace GeneralUpdate.Core.Domain.Service public async Task ValidationVersion(string url) { - var updateResp = await HttpUtil.GetTaskAsync(url); + var updateResp = await GetTaskAsync(url); if (updateResp == null || updateResp.Body == null) throw new ArgumentNullException($"The verification request is abnormal, please check the network or parameter configuration!"); if (updateResp.Code != HttpStatus.OK) throw new Exception($"Request failed , Code :{updateResp.Code}, Message:{updateResp.Message} !"); if (updateResp.Code == HttpStatus.OK) return updateResp; return null; } + + public static async Task GetTaskAsync(string http_url, string header_key = null, string header_value = null) + { + HttpWebResponse response = null; + try + { + ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); + string httpUri = http_url; + var encoding = Encoding.GetEncoding("utf-8"); + var request = (HttpWebRequest)WebRequest.Create(httpUri); + request.Method = "GET"; + request.Accept = "text/html, application/xhtml+xml, */*"; + request.ContentType = "application/x-www-form-urlencoded"; + request.Timeout = 15000; + if (!string.IsNullOrEmpty(header_key) && !string.IsNullOrEmpty(header_value)) + { + request.Headers[header_key] = header_value; + } + response = (HttpWebResponse)await request.GetResponseAsync(); + if (response.StatusCode != HttpStatusCode.OK) return default(T); + using (var reader = new StreamReader(response.GetResponseStream(), encoding)) + { + var tempStr = reader.ReadToEnd(); + var respContent = JsonConvert.DeserializeObject(tempStr); + return respContent; + } + } + catch + { + return default(T); + } + finally + { + if (response != null) response.Close(); + } + } + + private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true; } } \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Driver/BackupDriverCommand.cs b/src/c#/GeneralUpdate.Core/Driver/BackupDriverCommand.cs index 7c89795..a98efe9 100644 --- a/src/c#/GeneralUpdate.Core/Driver/BackupDriverCommand.cs +++ b/src/c#/GeneralUpdate.Core/Driver/BackupDriverCommand.cs @@ -10,7 +10,7 @@ namespace GeneralUpdate.Core.Driver { private DriverInformation _information; - public BackupDriverCommand(DriverInformation information)=> _information = information; + public BackupDriverCommand(DriverInformation information) => _information = information; public void Execute() { @@ -31,7 +31,7 @@ namespace GeneralUpdate.Core.Driver * If no test driver files are available, you can run the following command to export all installed driver files. * (1) dism /online /export-driver /destination:"D:\packet\cache\" * (2) pnputil /export-driver * D:\packet\cache - * + * * The following code example exports the specified driver to the specified directory. * pnputil /export-driver oem14.inf D:\packet\cache */ diff --git a/src/c#/GeneralUpdate.Core/Driver/CommandExecutor.cs b/src/c#/GeneralUpdate.Core/Driver/CommandExecutor.cs index 55faa1d..aa4fb11 100644 --- a/src/c#/GeneralUpdate.Core/Driver/CommandExecutor.cs +++ b/src/c#/GeneralUpdate.Core/Driver/CommandExecutor.cs @@ -22,7 +22,7 @@ Hardware problems: If the hardware device fails or the hardware configuration ch Before doing anything, create a system restore point so that it can be restored to its previous state if something goes wrong. Update the driver regularly to ensure that the driver is compatible with the current operating system version. If possible, use pre-tested drivers that are proven to work. - * + * */ var processStartInfo = new ProcessStartInfo { diff --git a/src/c#/GeneralUpdate.Core/Driver/DeleteDriverCommand.cs b/src/c#/GeneralUpdate.Core/Driver/DeleteDriverCommand.cs index 6fb4e1d..0d21452 100644 --- a/src/c#/GeneralUpdate.Core/Driver/DeleteDriverCommand.cs +++ b/src/c#/GeneralUpdate.Core/Driver/DeleteDriverCommand.cs @@ -11,7 +11,7 @@ namespace GeneralUpdate.Core.Driver public void Execute() { //Before installing the driver, delete the driver that has been installed on the local system. Otherwise, an exception may occur. - foreach (var driver in _information.Drivers) + foreach (var driver in _information.Drivers) { var command = new StringBuilder("/c pnputil /delete-driver ") .Append(driver) @@ -20,4 +20,4 @@ namespace GeneralUpdate.Core.Driver } } } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Driver/DriverInformation.cs b/src/c#/GeneralUpdate.Core/Driver/DriverInformation.cs index bf442b9..3e1e1da 100644 --- a/src/c#/GeneralUpdate.Core/Driver/DriverInformation.cs +++ b/src/c#/GeneralUpdate.Core/Driver/DriverInformation.cs @@ -1,5 +1,4 @@ using GeneralUpdate.Core.Exceptions; -using System; using System.Collections.Generic; using System.Linq; @@ -25,12 +24,13 @@ namespace GeneralUpdate.Core.Driver /// public List Drivers { get; private set; } - private DriverInformation(){} + private DriverInformation() + { } public class Builder { private DriverInformation _information = new DriverInformation(); - + public Builder SetInstallDirectory(string installDirectory) { _information.InstallDirectory = installDirectory; @@ -56,8 +56,8 @@ namespace GeneralUpdate.Core.Driver public DriverInformation Build() { - if (string.IsNullOrWhiteSpace(_information.InstallDirectory) || - string.IsNullOrWhiteSpace(_information.OutPutDirectory) || + if (string.IsNullOrWhiteSpace(_information.InstallDirectory) || + string.IsNullOrWhiteSpace(_information.OutPutDirectory) || !_information.Drivers.Any()) { ThrowExceptionUtility.ThrowIfNull("Cannot create DriverInformation, not all fields are set."); diff --git a/src/c#/GeneralUpdate.Core/Driver/InstallDriverCommand.cs b/src/c#/GeneralUpdate.Core/Driver/InstallDriverCommand.cs index 74e7a05..17953cd 100644 --- a/src/c#/GeneralUpdate.Core/Driver/InstallDriverCommand.cs +++ b/src/c#/GeneralUpdate.Core/Driver/InstallDriverCommand.cs @@ -12,7 +12,7 @@ namespace GeneralUpdate.Core.Driver { private DriverInformation _information; - public InstallDriverCommand(DriverInformation information)=> _information = information; + public InstallDriverCommand(DriverInformation information) => _information = information; public void Execute() { @@ -22,7 +22,7 @@ namespace GeneralUpdate.Core.Driver { /* * 1.It is best to ensure that the installed file is OEM INF, otherwise PnPUtil may indicate that non-OEM INF cannot perform the current operation. - * + * * 2.Before installation, you need to delete the previously installed driver, otherwise PnPUtil will prompt 259 to exit the code. * (On Windows, an ExitCode value of 259 (STILL_ACTIVE) means that the process is still running) * If you do not remove the previous installation 259 prompt will give you a misleading impression of what is running. diff --git a/src/c#/GeneralUpdate.Core/Driver/RestoreDriverCommand.cs b/src/c#/GeneralUpdate.Core/Driver/RestoreDriverCommand.cs index f36486c..f05c167 100644 --- a/src/c#/GeneralUpdate.Core/Driver/RestoreDriverCommand.cs +++ b/src/c#/GeneralUpdate.Core/Driver/RestoreDriverCommand.cs @@ -1,7 +1,7 @@ -using System.IO; +using GeneralUpdate.Core.Exceptions; using System; +using System.IO; using System.Text; -using GeneralUpdate.Core.Exceptions; namespace GeneralUpdate.Core.Driver { @@ -9,7 +9,7 @@ namespace GeneralUpdate.Core.Driver { private DriverInformation _information; - public RestoreDriverCommand(DriverInformation information)=> _information = information; + public RestoreDriverCommand(DriverInformation information) => _information = information; public void Execute() { diff --git a/src/c#/GeneralUpdate.Core/Events/CommonArgs/ExceptionEventArgs.cs b/src/c#/GeneralUpdate.Core/Events/CommonArgs/ExceptionEventArgs.cs index eb84518..2b54d23 100644 --- a/src/c#/GeneralUpdate.Core/Events/CommonArgs/ExceptionEventArgs.cs +++ b/src/c#/GeneralUpdate.Core/Events/CommonArgs/ExceptionEventArgs.cs @@ -11,7 +11,7 @@ namespace GeneralUpdate.Core.Events.CommonArgs _exception = exception; } - public ExceptionEventArgs(string mesage)=> _exception = new Exception(mesage); + public ExceptionEventArgs(string mesage) => _exception = new Exception(mesage); public Exception Exception => _exception; } diff --git a/src/c#/GeneralUpdate.Core/Events/OSSArgs/OSSDownloadArgs.cs b/src/c#/GeneralUpdate.Core/Events/OSSArgs/OSSDownloadArgs.cs index 25dca53..44cb326 100644 --- a/src/c#/GeneralUpdate.Core/Events/OSSArgs/OSSDownloadArgs.cs +++ b/src/c#/GeneralUpdate.Core/Events/OSSArgs/OSSDownloadArgs.cs @@ -20,4 +20,4 @@ namespace GeneralUpdate.Core.Events.OSSArgs TotalLength = totalLength; } } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Exceptions/CustomException/GeneralUpdateException.cs b/src/c#/GeneralUpdate.Core/Exceptions/CustomException/GeneralUpdateException.cs index 258fc84..7e2d605 100644 --- a/src/c#/GeneralUpdate.Core/Exceptions/CustomException/GeneralUpdateException.cs +++ b/src/c#/GeneralUpdate.Core/Exceptions/CustomException/GeneralUpdateException.cs @@ -15,7 +15,7 @@ namespace GeneralUpdate.Core.Exceptions.CustomException private const String c_args = "Args"; private readonly TExceptionArgs m_args; - public TExceptionArgs Args=> m_args; + public TExceptionArgs Args => m_args; public GeneralUpdateException(String message = null, Exception innerException = null) : this(null, message, innerException) { diff --git a/src/c#/GeneralUpdate.Core/Exceptions/ThrowExceptionUtility.cs b/src/c#/GeneralUpdate.Core/Exceptions/ThrowExceptionUtility.cs index a8bbea5..25c310d 100644 --- a/src/c#/GeneralUpdate.Core/Exceptions/ThrowExceptionUtility.cs +++ b/src/c#/GeneralUpdate.Core/Exceptions/ThrowExceptionUtility.cs @@ -6,14 +6,14 @@ namespace GeneralUpdate.Core.Exceptions { internal sealed class ThrowExceptionUtility { - public static void ThrowGeneralUpdateException(ExceptionArgs args) + public static void ThrowGeneralUpdateException(ExceptionArgs args) => Throw(args.ToString(), args); #region Common public static void ThrowFileNotFound(string file) => Throw($"File cannot be accessed {file}!"); - public static void ThrowIfNull(string errorMessage = null) + public static void ThrowIfNull(string errorMessage = null) { errorMessage = errorMessage ?? "Parameter cannot be null"; Throw(errorMessage); @@ -52,6 +52,6 @@ namespace GeneralUpdate.Core.Exceptions public static void Throw(string message, params object[] args) where T : Exception, new() => throw (T)Activator.CreateInstance(typeof(T), message, args); - #endregion + #endregion Common } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/GeneralUpdateBootstrap.cs b/src/c#/GeneralUpdate.Core/GeneralUpdateBootstrap.cs index 4cc5761..8b4965b 100644 --- a/src/c#/GeneralUpdate.Core/GeneralUpdateBootstrap.cs +++ b/src/c#/GeneralUpdate.Core/GeneralUpdateBootstrap.cs @@ -1,8 +1,8 @@ using GeneralUpdate.Core.Bootstrap; +using GeneralUpdate.Core.ContentProvider; using GeneralUpdate.Core.Domain.Entity; using GeneralUpdate.Core.Domain.Entity.Assembler; using GeneralUpdate.Core.Domain.Enum; -using GeneralUpdate.Core.Exceptions; using GeneralUpdate.Core.Strategys; using GeneralUpdate.Core.Utils; using System; @@ -13,7 +13,7 @@ namespace GeneralUpdate.Core { public class GeneralUpdateBootstrap : AbstractBootstrap { - public GeneralUpdateBootstrap() : base()=> Remote(); + public GeneralUpdateBootstrap() : base() => Remote(); /// /// Gets values from system environment variables (ClientParameter object to base64 string). @@ -26,7 +26,7 @@ namespace GeneralUpdate.Core var processInfo = SerializeUtil.Deserialize(base64); Packet = ProcessAssembler.ToPacket(processInfo); Packet.AppType = AppType.UpgradeApp; - Packet.TempPath = $"{FileUtil.GetTempDirectory(processInfo.LastVersion)}{Path.DirectorySeparatorChar}"; + Packet.TempPath = $"{FileProvider.GetTempDirectory(processInfo.LastVersion)}{Path.DirectorySeparatorChar}"; } catch (Exception ex) { diff --git a/src/c#/GeneralUpdate.Core/GeneralUpdateOSS.cs b/src/c#/GeneralUpdate.Core/GeneralUpdateOSS.cs index 1a21bd6..d6525c4 100644 --- a/src/c#/GeneralUpdate.Core/GeneralUpdateOSS.cs +++ b/src/c#/GeneralUpdate.Core/GeneralUpdateOSS.cs @@ -17,7 +17,7 @@ namespace GeneralUpdate.Core private GeneralUpdateOSS() { } - #endregion + #endregion Constructors #region Public Methods @@ -27,7 +27,7 @@ namespace GeneralUpdate.Core /// /// /// - public static async Task Start(ParamsOSS parameter,Encoding encoding) where TStrategy : AbstractStrategy, new() + public static async Task Start(ParamsOSS parameter, Encoding encoding) where TStrategy : AbstractStrategy, new() { await BaseStart(parameter, encoding); } @@ -67,7 +67,7 @@ namespace GeneralUpdate.Core AddListener(callbackAction); } - #endregion + #endregion Public Methods #region Private Methods @@ -82,7 +82,7 @@ namespace GeneralUpdate.Core /// The class that needs to be injected with the corresponding platform update policy or inherits the abstract update policy. /// List of parameter. /// - private static async Task BaseStart(TParams parameter,Encoding encoding) where TStrategy : AbstractStrategy, new() where TParams : class + private static async Task BaseStart(TParams parameter, Encoding encoding) where TStrategy : AbstractStrategy, new() where TParams : class { //Initializes and executes the policy. var strategyFunc = new Func(() => new TStrategy()); @@ -92,6 +92,6 @@ namespace GeneralUpdate.Core await strategy.ExecuteTaskAsync(); } - #endregion + #endregion Private Methods } } \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/HashAlgorithms/Md5HashAlgorithm.cs b/src/c#/GeneralUpdate.Core/HashAlgorithms/Md5HashAlgorithm.cs index d7bbd0b..6502034 100644 --- a/src/c#/GeneralUpdate.Core/HashAlgorithms/Md5HashAlgorithm.cs +++ b/src/c#/GeneralUpdate.Core/HashAlgorithms/Md5HashAlgorithm.cs @@ -4,6 +4,6 @@ namespace GeneralUpdate.Core.HashAlgorithms { public class Md5HashAlgorithm : HashAlgorithmBase { - protected override HashAlgorithm GetHashAlgorithm()=> MD5.Create(); + protected override HashAlgorithm GetHashAlgorithm() => MD5.Create(); } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/HashAlgorithms/Sha1HashAlgorithm.cs b/src/c#/GeneralUpdate.Core/HashAlgorithms/Sha1HashAlgorithm.cs index 1013e2f..cec89ba 100644 --- a/src/c#/GeneralUpdate.Core/HashAlgorithms/Sha1HashAlgorithm.cs +++ b/src/c#/GeneralUpdate.Core/HashAlgorithms/Sha1HashAlgorithm.cs @@ -4,6 +4,6 @@ namespace GeneralUpdate.Core.HashAlgorithms { public class Sha1HashAlgorithm : HashAlgorithmBase { - protected override HashAlgorithm GetHashAlgorithm()=> new SHA1Managed(); + protected override HashAlgorithm GetHashAlgorithm() => new SHA1Managed(); } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/HashAlgorithms/Sha256HashAlgorithm.cs b/src/c#/GeneralUpdate.Core/HashAlgorithms/Sha256HashAlgorithm.cs index e88290a..d6135ea 100644 --- a/src/c#/GeneralUpdate.Core/HashAlgorithms/Sha256HashAlgorithm.cs +++ b/src/c#/GeneralUpdate.Core/HashAlgorithms/Sha256HashAlgorithm.cs @@ -4,6 +4,6 @@ namespace GeneralUpdate.Core.HashAlgorithms { public class Sha256HashAlgorithm : HashAlgorithmBase { - protected override HashAlgorithm GetHashAlgorithm()=> SHA256.Create(); + protected override HashAlgorithm GetHashAlgorithm() => SHA256.Create(); } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Pipelines/Context/BaseContext.cs b/src/c#/GeneralUpdate.Core/Pipelines/Context/BaseContext.cs index 63f2558..f00c56c 100644 --- a/src/c#/GeneralUpdate.Core/Pipelines/Context/BaseContext.cs +++ b/src/c#/GeneralUpdate.Core/Pipelines/Context/BaseContext.cs @@ -21,7 +21,8 @@ namespace GeneralUpdate.Core.Pipelines.Context public List BlackFiles { get; private set; } public List BlackFileFormats { get; private set; } - private BaseContext() { } + private BaseContext() + { } public class Builder { diff --git a/src/c#/GeneralUpdate.Core/Pipelines/Middleware/DriveMiddleware.cs b/src/c#/GeneralUpdate.Core/Pipelines/Middleware/DriveMiddleware.cs index 4532b2c..46f5ff3 100644 --- a/src/c#/GeneralUpdate.Core/Pipelines/Middleware/DriveMiddleware.cs +++ b/src/c#/GeneralUpdate.Core/Pipelines/Middleware/DriveMiddleware.cs @@ -1,10 +1,10 @@ -using System; +using GeneralUpdate.Core.Driver; +using GeneralUpdate.Core.Pipelines.Context; +using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading.Tasks; -using GeneralUpdate.Core.Driver; -using GeneralUpdate.Core.Pipelines.Context; namespace GeneralUpdate.Core.Pipelines.Middleware { @@ -17,8 +17,8 @@ namespace GeneralUpdate.Core.Pipelines.Middleware { var drivers = GetAllDriverDirectories(context.TargetPath); var information = new DriverInformation.Builder() - .SetInstallDirectory(Path.Combine(context.SourcePath,context.Version.ToString())) - .SetOutPutDirectory(Path.Combine(context.TargetPath,context.Version.ToString())) + .SetInstallDirectory(Path.Combine(context.SourcePath, context.Version.ToString())) + .SetOutPutDirectory(Path.Combine(context.TargetPath, context.Version.ToString())) .SetDriverNames(drivers) .Build(); @@ -70,7 +70,7 @@ namespace GeneralUpdate.Core.Pipelines.Middleware /// /// /// - private bool IsDriverFile(string filePath)=> + private bool IsDriverFile(string filePath) => string.Equals(Path.GetExtension(filePath), ".inf", StringComparison.OrdinalIgnoreCase); } } \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Pipelines/Middleware/HashMiddleware.cs b/src/c#/GeneralUpdate.Core/Pipelines/Middleware/HashMiddleware.cs index 3db8ae9..f4ba5cd 100644 --- a/src/c#/GeneralUpdate.Core/Pipelines/Middleware/HashMiddleware.cs +++ b/src/c#/GeneralUpdate.Core/Pipelines/Middleware/HashMiddleware.cs @@ -1,6 +1,5 @@ using GeneralUpdate.Core.Domain.Enum; using GeneralUpdate.Core.Events; -using GeneralUpdate.Core.Events.CommonArgs; using GeneralUpdate.Core.Events.MultiEventArgs; using GeneralUpdate.Core.HashAlgorithms; using GeneralUpdate.Core.Pipelines.Context; diff --git a/src/c#/GeneralUpdate.Core/Pipelines/Middleware/MiddlewareExtensions.cs b/src/c#/GeneralUpdate.Core/Pipelines/Middleware/MiddlewareExtensions.cs index 0fd5687..a636351 100644 --- a/src/c#/GeneralUpdate.Core/Pipelines/Middleware/MiddlewareExtensions.cs +++ b/src/c#/GeneralUpdate.Core/Pipelines/Middleware/MiddlewareExtensions.cs @@ -15,15 +15,15 @@ namespace GeneralUpdate.Core.Pipelines.Middleware private const DynamicallyAccessedMemberTypes MiddlewareAccessibility = DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods; - public static IPipelineBuilder UseMiddleware<[DynamicallyAccessedMembers(MiddlewareAccessibility)] TMiddleware>(this IPipelineBuilder pipeline) => pipeline.UseMiddleware(typeof(TMiddleware),true); + public static IPipelineBuilder UseMiddleware<[DynamicallyAccessedMembers(MiddlewareAccessibility)] TMiddleware>(this IPipelineBuilder pipeline) => pipeline.UseMiddleware(typeof(TMiddleware), true); - public static IPipelineBuilder UseMiddlewareIf<[DynamicallyAccessedMembers(MiddlewareAccessibility)] TMiddleware>(this IPipelineBuilder pipeline,bool condition = false) => pipeline.UseMiddleware(typeof(TMiddleware), condition); + public static IPipelineBuilder UseMiddlewareIf<[DynamicallyAccessedMembers(MiddlewareAccessibility)] TMiddleware>(this IPipelineBuilder pipeline, bool condition = false) => pipeline.UseMiddleware(typeof(TMiddleware), condition); public static IPipelineBuilder UseMiddleware( this IPipelineBuilder pipeline, [DynamicallyAccessedMembers(MiddlewareAccessibility)] Type middleware, bool condition) { - if(!condition) return pipeline; + if (!condition) return pipeline; if (!typeof(IMiddleware).IsAssignableFrom(middleware)) throw new ArgumentException($"The middleware type must implement \"{typeof(IMiddleware)}\"."); diff --git a/src/c#/GeneralUpdate.Core/Pipelines/Middleware/WillMessageMiddleware.cs b/src/c#/GeneralUpdate.Core/Pipelines/Middleware/WillMessageMiddleware.cs index f1125c7..b7b38d1 100644 --- a/src/c#/GeneralUpdate.Core/Pipelines/Middleware/WillMessageMiddleware.cs +++ b/src/c#/GeneralUpdate.Core/Pipelines/Middleware/WillMessageMiddleware.cs @@ -8,9 +8,9 @@ namespace GeneralUpdate.Core.Pipelines.Middleware { public async Task InvokeAsync(BaseContext context, MiddlewareStack stack) { - WillMessageManager.Instance.Backup(context.SourcePath, context.TargetPath, context.Version.ToString(), context.Version.Hash ,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); } } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Strategys/AbstractStrategy.cs b/src/c#/GeneralUpdate.Core/Strategys/AbstractStrategy.cs index 6ba1277..5b7384e 100644 --- a/src/c#/GeneralUpdate.Core/Strategys/AbstractStrategy.cs +++ b/src/c#/GeneralUpdate.Core/Strategys/AbstractStrategy.cs @@ -18,6 +18,6 @@ namespace GeneralUpdate.Core.Strategys public virtual void Create(T parameter) where T : class => throw new NotImplementedException(); - public virtual void Create(T parameter,Encoding encoding) where T : class => throw new NotImplementedException(); + public virtual void Create(T parameter, Encoding encoding) where T : class => throw new NotImplementedException(); } } \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Strategys/OSSStrategy.cs b/src/c#/GeneralUpdate.Core/Strategys/OSSStrategy.cs index 6a550f3..10f482b 100644 --- a/src/c#/GeneralUpdate.Core/Strategys/OSSStrategy.cs +++ b/src/c#/GeneralUpdate.Core/Strategys/OSSStrategy.cs @@ -1,4 +1,5 @@ -using GeneralUpdate.Core.Domain.Entity; +using GeneralUpdate.Core.ContentProvider; +using GeneralUpdate.Core.Domain.Entity; using GeneralUpdate.Core.Domain.Enum; using GeneralUpdate.Core.Domain.PO; using GeneralUpdate.Core.Domain.PO.Assembler; @@ -6,7 +7,6 @@ using GeneralUpdate.Core.Download; using GeneralUpdate.Core.Events; using GeneralUpdate.Core.Events.CommonArgs; using GeneralUpdate.Core.Events.MultiEventArgs; -using GeneralUpdate.Core.Utils; using GeneralUpdate.Zip; using GeneralUpdate.Zip.Factory; using System; @@ -28,7 +28,7 @@ namespace GeneralUpdate.Core.Strategys private ParamsOSS _parameter; private Encoding _encoding; - #endregion + #endregion Private Members #region Public Methods @@ -49,7 +49,7 @@ namespace GeneralUpdate.Core.Strategys if (!File.Exists(jsonPath)) throw new FileNotFoundException(jsonPath); //2.Parse the JSON version configuration file content. - var versions = FileUtil.GetJson>(jsonPath); + var versions = FileProvider.GetJson>(jsonPath); if (versions == null) throw new NullReferenceException(nameof(versions)); //3.Download version by version according to the version of the configuration file. @@ -70,7 +70,7 @@ namespace GeneralUpdate.Core.Strategys }); } - #endregion + #endregion Public Methods #region Private Methods @@ -106,16 +106,16 @@ namespace GeneralUpdate.Core.Strategys try { bool isCompleted = true; - foreach (VersionInfo version in versions) + foreach (VersionInfo version in versions) { - var zipFilePath = Path.Combine(_appPath,$"{version.Name}.zip"); + var zipFilePath = Path.Combine(_appPath, $"{version.Name}.zip"); var zipFactory = new GeneralZipFactory(); zipFactory.UnZipProgress += (sender, e) => EventManager.Instance.Dispatch>(this, new MultiDownloadProgressChangedEventArgs(version, ProgressType.Updatefile, "Updating file...")); - zipFactory.Completed += (sender, e) => + zipFactory.Completed += (sender, e) => { isCompleted = e.IsCompleted; - if(File.Exists(zipFilePath)) File.Delete(zipFilePath); + if (File.Exists(zipFilePath)) File.Delete(zipFilePath); }; zipFactory.CreateOperate(OperationType.GZip, version.Name, zipFilePath, _appPath, false, _encoding); zipFactory.UnZip(); @@ -129,6 +129,6 @@ namespace GeneralUpdate.Core.Strategys } } - #endregion + #endregion Private Methods } } \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Strategys/PlatformWindows/WindowsStrategy.cs b/src/c#/GeneralUpdate.Core/Strategys/PlatformWindows/WindowsStrategy.cs index 7d46afe..d4eeaf6 100644 --- a/src/c#/GeneralUpdate.Core/Strategys/PlatformWindows/WindowsStrategy.cs +++ b/src/c#/GeneralUpdate.Core/Strategys/PlatformWindows/WindowsStrategy.cs @@ -1,11 +1,11 @@ -using GeneralUpdate.Core.Domain.Entity; +using GeneralUpdate.Core.ContentProvider; +using GeneralUpdate.Core.Domain.Entity; using GeneralUpdate.Core.Domain.Enum; using GeneralUpdate.Core.Events; using GeneralUpdate.Core.Events.CommonArgs; using GeneralUpdate.Core.Pipelines; using GeneralUpdate.Core.Pipelines.Context; using GeneralUpdate.Core.Pipelines.Middleware; -using GeneralUpdate.Core.Utils; using GeneralUpdate.Core.WillMessage; using System; using System.Diagnostics; @@ -42,7 +42,7 @@ namespace GeneralUpdate.Core.Strategys.PlatformWindows { foreach (var version in updateVersions) { - var patchPath = FileUtil.GetTempDirectory(PATCHS); + var patchPath = FileProvider.GetTempDirectory(PATCHS); var zipFilePath = Path.Combine(Packet.TempPath, $"{version.Name}{Packet.Format}"); var context = new BaseContext.Builder() diff --git a/src/c#/GeneralUpdate.Core/Utils/ConvertUtil.cs b/src/c#/GeneralUpdate.Core/Utils/ConvertUtil.cs deleted file mode 100644 index 6e19739..0000000 --- a/src/c#/GeneralUpdate.Core/Utils/ConvertUtil.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Text; - -namespace GeneralUpdate.Core.Utils -{ - public class ConvertUtil - { - public static Encoding ToEncoding(int type) - { - Encoding encoding = Encoding.Default; - switch (type) - { - case 1: - encoding = Encoding.UTF8; - break; - - case 2: - encoding = Encoding.UTF7; - break; - - case 3: - encoding = Encoding.UTF32; - break; - - case 4: - encoding = Encoding.Unicode; - break; - - case 5: - encoding = Encoding.BigEndianUnicode; - break; - - case 6: - encoding = Encoding.ASCII; - break; - - case 7: - encoding = Encoding.Default; - break; - } - return encoding; - } - - public static int ToEncodingType(Encoding encoding) - { - int type = -1; - if (encoding == Encoding.UTF8) - { - type = 1; - } - else if (encoding == Encoding.UTF7) - { - type = 2; - } - else if (encoding == Encoding.UTF32) - { - type = 3; - } - else if (encoding == Encoding.Unicode) - { - type = 4; - } - else if (encoding == Encoding.BigEndianUnicode) - { - type = 5; - } - else if (encoding == Encoding.ASCII) - { - type = 6; - } - else if (encoding == Encoding.Default) - { - type = 7; - } - return type; - } - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Utils/FileUtil.cs b/src/c#/GeneralUpdate.Core/Utils/FileUtil.cs deleted file mode 100644 index c11d676..0000000 --- a/src/c#/GeneralUpdate.Core/Utils/FileUtil.cs +++ /dev/null @@ -1,71 +0,0 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.IO; - -namespace GeneralUpdate.Core.Utils -{ - public static class FileUtil - { - public static string GetTempDirectory(string name) - { - var path2 = $"generalupdate_{DateTime.Now.ToString("yyyy-MM-dd")}_{name}"; - var tempDir = Path.Combine(Path.GetTempPath(), path2); - if (!Directory.Exists(tempDir)) - { - Directory.CreateDirectory(tempDir); - } - return tempDir; - } - - public static FileInfo[] GetAllFiles(string path) - { - try - { - var files = new List(); - files.AddRange(new DirectoryInfo(path).GetFiles()); - var tmpDir = new DirectoryInfo(path).GetDirectories(); - foreach (var dic in tmpDir) - { - files.AddRange(GetAllFiles(dic.FullName)); - } - return files.ToArray(); - } - catch (Exception) - { - return null; - } - } - - public static void CreateJson(string targetPath,T obj) - { - if (!Directory.Exists(targetPath)) Directory.CreateDirectory(targetPath); - if (File.Exists(targetPath)) File.Delete(targetPath); - var jsonString = JsonConvert.SerializeObject(obj); - File.WriteAllText(targetPath, jsonString); - } - - public static T GetJson(string path) - { - if (File.Exists(path)) - { - var json = File.ReadAllText(path); - if (json != null) - { - return JsonConvert.DeserializeObject(json); - } - } - return default(T); - } - - /// - /// Delete the backup file directory and recursively delete all backup content. - /// - public static void DeleteDir(string path) - { - if (string.IsNullOrWhiteSpace(path)) return; - if (Directory.Exists(path)) - Directory.Delete(path, true); - } - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/Utils/HttpUtil.cs b/src/c#/GeneralUpdate.Core/Utils/HttpUtil.cs deleted file mode 100644 index 7989442..0000000 --- a/src/c#/GeneralUpdate.Core/Utils/HttpUtil.cs +++ /dev/null @@ -1,87 +0,0 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Net.Http; -using System.Net.Security; -using System.Security.Cryptography.X509Certificates; -using System.Text; -using System.Threading.Tasks; - -namespace GeneralUpdate.Core.Utils -{ - public sealed class HttpUtil - { - public static async Task GetTaskAsync(string http_url, string header_key = null, string header_value = null) - { - HttpWebResponse response = null; - try - { - ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); - string httpUri = http_url; - var encoding = Encoding.GetEncoding("utf-8"); - var request = (HttpWebRequest)WebRequest.Create(httpUri); - request.Method = "GET"; - request.Accept = "text/html, application/xhtml+xml, */*"; - request.ContentType = "application/x-www-form-urlencoded"; - request.Timeout = 15000; - if (!string.IsNullOrEmpty(header_key) && !string.IsNullOrEmpty(header_value)) - { - request.Headers[header_key] = header_value; - } - response = (HttpWebResponse)await request.GetResponseAsync(); - if (response.StatusCode != HttpStatusCode.OK) return default(T); - using (var reader = new StreamReader(response.GetResponseStream(), encoding)) - { - var tempStr = reader.ReadToEnd(); - var respContent = JsonConvert.DeserializeObject(tempStr); - return respContent; - } - } - catch - { - return default(T); - } - finally - { - if (response != null) response.Close(); - } - } - - public static async Task PostFileTaskAsync(string httpUrl, Dictionary parameters, string filePath) - { - try - { - Uri uri = new Uri(httpUrl); - using (var client = new HttpClient()) - using (var content = new MultipartFormDataContent()) - { - foreach (var parameter in parameters) - { - var stringContent = new StringContent(parameter.Value); - content.Add(stringContent, parameter.Key); - } - - if (string.IsNullOrWhiteSpace(filePath) && File.Exists(filePath)) - { - var fileStream = File.OpenRead(filePath); - var fileInfo = new FileInfo(filePath); - var fileContent = new StreamContent(fileStream); - content.Add(fileContent, "file", Path.GetFileName(filePath)); - } - - var result = await client.PostAsync(uri, content); - var reseponseJson = await result.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject(reseponseJson); - } - } - catch - { - return default(T); - } - } - - private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true; - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs b/src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs index 43bc50b..947914d 100644 --- a/src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs +++ b/src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs @@ -1,5 +1,5 @@ -using GeneralUpdate.Core.Domain.PO; -using GeneralUpdate.Core.Utils; +using GeneralUpdate.Core.ContentProvider; +using GeneralUpdate.Core.Domain.PO; using System; using System.Collections.Generic; using System.IO; @@ -10,11 +10,12 @@ namespace GeneralUpdate.Core.WillMessage public class WillMessageManager { #region Private Members + private string TempPath = Path.GetTempPath(); public const string DEFULT_WILL_MESSAGE_DIR = "generalupdate_willmessages"; public const string BACKUP_DIR = "generalupdate_backup"; public const string DEFULT_WILL_MESSAGE_FILE = "will_message.json"; - + private string _packetPath; private string _appPath; private string _backupPath; @@ -25,15 +26,16 @@ namespace GeneralUpdate.Core.WillMessage private bool _isFirstTime = true; private static WillMessageManager _instance; - private readonly static object _instanceLock = new object(); + private static readonly object _instanceLock = new object(); - #endregion + #endregion Private Members #region Constructors - private WillMessageManager() { } + private WillMessageManager() + { } - #endregion + #endregion Constructors #region Public Properties @@ -55,14 +57,14 @@ namespace GeneralUpdate.Core.WillMessage } } - #endregion + #endregion Public Properties #region Public Methods public WillMessagePO GetWillMessage(string path = null) { _willMessageFile = string.IsNullOrWhiteSpace(path) ? GetWillMessagePath() : path; - return _willMessage = FileUtil.GetJson(_willMessageFile); + return _willMessage = FileProvider.GetJson(_willMessageFile); } public void Clear() @@ -73,11 +75,11 @@ namespace GeneralUpdate.Core.WillMessage _willMessage = null; _willMessageFile = null; _backupStack.Clear(); - FileUtil.DeleteDir(DEFULT_WILL_MESSAGE_DIR); - FileUtil.DeleteDir(GetBackupPath()); + FileProvider.DeleteDir(DEFULT_WILL_MESSAGE_DIR); + FileProvider.DeleteDir(GetBackupPath()); } - public void Backup(string appPath, string packetPath, string version,string hash,int appType) + public void Backup(string appPath, string packetPath, string version, string hash, int appType) { if (!Directory.Exists(GetBackupPath())) Directory.CreateDirectory(GetBackupPath()); @@ -90,7 +92,7 @@ namespace GeneralUpdate.Core.WillMessage _packetPath = packetPath; _backupPath = versionDir; ProcessDirectory(_packetPath, _appPath, _backupPath); - _backupStack.Push(new BackupPO { Version = version, AppType = appType, AppPath = _appPath, BackupPath = _backupPath , Hash = hash }); + _backupStack.Push(new BackupPO { Version = version, AppType = appType, AppPath = _appPath, BackupPath = _backupPath, Hash = hash }); } public void Restore() @@ -105,7 +107,7 @@ namespace GeneralUpdate.Core.WillMessage } } - public void Builder() + public void Builder() { if (!_backupStack.Any()) return; @@ -115,7 +117,7 @@ namespace GeneralUpdate.Core.WillMessage .SetCreateTime(DateTime.Now) .SetChangeTime(DateTime.Now) .Build(); - FileUtil.CreateJson(GetWillMessagePath(), _willMessage); + FileProvider.CreateJson(GetWillMessagePath(), _willMessage); } public void Check() @@ -133,16 +135,18 @@ namespace GeneralUpdate.Core.WillMessage { case WillMessageStatus.NotStarted: return; + case WillMessageStatus.Failed: Restore(); break; + case WillMessageStatus.Completed: Clear(); break; } } - #endregion + #endregion Public Methods #region Private Methods @@ -196,6 +200,6 @@ namespace GeneralUpdate.Core.WillMessage return relativePath.Replace('/', Path.DirectorySeparatorChar); } - #endregion + #endregion Private Methods } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Differential/Common/DirectoryComparer.cs b/src/c#/GeneralUpdate.Differential/Common/DirectoryComparer.cs index e08bbc4..4926bcd 100644 --- a/src/c#/GeneralUpdate.Differential/Common/DirectoryComparer.cs +++ b/src/c#/GeneralUpdate.Differential/Common/DirectoryComparer.cs @@ -68,4 +68,4 @@ namespace GeneralUpdate.Differential.Common } } } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Differential/Config/ConfigFactory.cs b/src/c#/GeneralUpdate.Differential/Config/ConfigFactory.cs index dd840c9..bf33fc8 100644 --- a/src/c#/GeneralUpdate.Differential/Config/ConfigFactory.cs +++ b/src/c#/GeneralUpdate.Differential/Config/ConfigFactory.cs @@ -1,5 +1,4 @@ using GeneralUpdate.Core.HashAlgorithms; -using GeneralUpdate.Core.Utils; using GeneralUpdate.Differential.Common; using GeneralUpdate.Differential.Config.Cache; using GeneralUpdate.Differential.Config.Handles; diff --git a/src/c#/GeneralUpdate.Differential/Config/Handles/IniHandle.cs b/src/c#/GeneralUpdate.Differential/Config/Handles/IniHandle.cs index 8520412..2ea2cb0 100644 --- a/src/c#/GeneralUpdate.Differential/Config/Handles/IniHandle.cs +++ b/src/c#/GeneralUpdate.Differential/Config/Handles/IniHandle.cs @@ -32,7 +32,7 @@ namespace GeneralUpdate.Differential.Config.Handles throw new NotImplementedException(); } - Dictionary> ParseIniFile(string filePath) + private Dictionary> ParseIniFile(string filePath) { Dictionary> iniData = new Dictionary>(); string currentSection = ""; @@ -58,7 +58,7 @@ namespace GeneralUpdate.Differential.Config.Handles return iniData; } - static Dictionary> GetIniFileDiff( + private static Dictionary> GetIniFileDiff( Dictionary> originalIni, Dictionary> targetIni) { @@ -88,7 +88,7 @@ namespace GeneralUpdate.Differential.Config.Handles return diffIni; } - void MergeIniFiles( + private void MergeIniFiles( Dictionary> targetIni, Dictionary> diffIni) { @@ -109,7 +109,7 @@ namespace GeneralUpdate.Differential.Config.Handles } } - void SaveIniFile(string filePath, Dictionary> iniData) + private void SaveIniFile(string filePath, Dictionary> iniData) { using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8)) { diff --git a/src/c#/GeneralUpdate.Differential/Config/Handles/JsonHandle.cs b/src/c#/GeneralUpdate.Differential/Config/Handles/JsonHandle.cs index 14b41e8..2c5a9cb 100644 --- a/src/c#/GeneralUpdate.Differential/Config/Handles/JsonHandle.cs +++ b/src/c#/GeneralUpdate.Differential/Config/Handles/JsonHandle.cs @@ -126,7 +126,8 @@ namespace GeneralUpdate.Differential.Config.Handles return result; } - private void Read(string originalJson,string diffJson) { + private void Read(string originalJson, string diffJson) + { JObject originalObject = JObject.Parse(originalJson); JObject diffObject = JObject.Parse(diffJson); } diff --git a/src/c#/GeneralUpdate.Differential/DifferentialCore.cs b/src/c#/GeneralUpdate.Differential/DifferentialCore.cs index 7e47993..1e237a4 100644 --- a/src/c#/GeneralUpdate.Differential/DifferentialCore.cs +++ b/src/c#/GeneralUpdate.Differential/DifferentialCore.cs @@ -1,6 +1,5 @@ using GeneralUpdate.Core.ContentProvider; using GeneralUpdate.Core.HashAlgorithms; -using GeneralUpdate.Core.Utils; using GeneralUpdate.Differential.Binary; using GeneralUpdate.Differential.Common; using System; @@ -45,7 +44,7 @@ namespace GeneralUpdate.Differential { lock (_lockObj) { - if (_instance == null) + if (_instance == null) { _instance = new DifferentialCore(); } @@ -79,7 +78,7 @@ namespace GeneralUpdate.Differential //Take the left tree as the center to match the files that are not in the right tree . var fileProvider = new FileProvider(); var nodes = await fileProvider.Compare(sourcePath, targetPath); - + //Binary differencing of like terms . foreach (var file in nodes.Item3) { @@ -115,8 +114,8 @@ namespace GeneralUpdate.Differential //If a file is found that needs to be deleted, a list of files is written to the update package. var exceptFiles = await fileProvider.Except(sourcePath, targetPath); - if(exceptFiles != null && exceptFiles.Count() > 0) - FileUtil.CreateJson(Path.Combine(patchPath, DELETE_FILES_NAME), exceptFiles); + if (exceptFiles != null && exceptFiles.Count() > 0) + FileProvider.CreateJson(Path.Combine(patchPath, DELETE_FILES_NAME), exceptFiles); } catch (Exception ex) { @@ -136,14 +135,14 @@ namespace GeneralUpdate.Differential if (!Directory.Exists(appPath) || !Directory.Exists(patchPath)) return; try { - var patchFiles = FileUtil.GetAllFiles(patchPath); - var oldFiles = FileUtil.GetAllFiles(appPath); + var patchFiles = FileProvider.GetAllFiles(patchPath); + var oldFiles = FileProvider.GetAllFiles(appPath); //If a JSON file for the deletion list is found in the update package, it will be deleted based on its contents. - var deleteListJson = patchFiles.FirstOrDefault(i=>i.Name.Equals(DELETE_FILES_NAME)); - if (deleteListJson != null) + var deleteListJson = patchFiles.FirstOrDefault(i => i.Name.Equals(DELETE_FILES_NAME)); + if (deleteListJson != null) { - var deleteFiles = FileUtil.GetJson>(deleteListJson.FullName); + var deleteFiles = FileProvider.GetJson>(deleteListJson.FullName); var hashAlgorithm = new Sha256HashAlgorithm(); foreach (var file in deleteFiles) { diff --git a/src/c#/GeneralUpdate.Differential/GeneralUpdate.Differential.csproj b/src/c#/GeneralUpdate.Differential/GeneralUpdate.Differential.csproj index aa6072f..f6fdd38 100644 --- a/src/c#/GeneralUpdate.Differential/GeneralUpdate.Differential.csproj +++ b/src/c#/GeneralUpdate.Differential/GeneralUpdate.Differential.csproj @@ -28,6 +28,7 @@ + @@ -47,7 +48,6 @@ - diff --git a/src/c#/GeneralUpdate.Maui.OSS/GeneralUpdate.Maui.OSS.csproj b/src/c#/GeneralUpdate.Maui.OSS/GeneralUpdate.Maui.OSS.csproj index f150deb..3cfd08b 100644 --- a/src/c#/GeneralUpdate.Maui.OSS/GeneralUpdate.Maui.OSS.csproj +++ b/src/c#/GeneralUpdate.Maui.OSS/GeneralUpdate.Maui.OSS.csproj @@ -43,13 +43,18 @@ + - + + + + + @@ -66,7 +71,7 @@ - + @@ -74,7 +79,6 @@ - diff --git a/src/c#/GeneralUpdate.Maui.OSS/GeneralUpdateOSS.cs b/src/c#/GeneralUpdate.Maui.OSS/GeneralUpdateOSS.cs index 795eead..5523a4f 100644 --- a/src/c#/GeneralUpdate.Maui.OSS/GeneralUpdateOSS.cs +++ b/src/c#/GeneralUpdate.Maui.OSS/GeneralUpdateOSS.cs @@ -16,7 +16,7 @@ namespace GeneralUpdate.Maui.OSS private GeneralUpdateOSS() { } - #endregion + #endregion Constructors #region Public Methods @@ -53,7 +53,7 @@ namespace GeneralUpdate.Maui.OSS AddListener(callbackAction); } - #endregion + #endregion Public Methods #region Private Methods @@ -78,6 +78,6 @@ namespace GeneralUpdate.Maui.OSS if (callbackAction != null) EventManager.Instance.AddListener(callbackAction); } - #endregion + #endregion Private Methods } } \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Maui.OSS/Platforms/Android/AndroidManifest.xml b/src/c#/GeneralUpdate.Maui.OSS/Platforms/Android/AndroidManifest.xml index f9b832e..b0f2e2a 100644 --- a/src/c#/GeneralUpdate.Maui.OSS/Platforms/Android/AndroidManifest.xml +++ b/src/c#/GeneralUpdate.Maui.OSS/Platforms/Android/AndroidManifest.xml @@ -1,5 +1,5 @@  - + - + \ No newline at end of file diff --git a/src/c#/GeneralUpdate.OSSClient/AppShell.xaml b/src/c#/GeneralUpdate.OSSClient/AppShell.xaml index c766f29..05b5b05 100644 --- a/src/c#/GeneralUpdate.OSSClient/AppShell.xaml +++ b/src/c#/GeneralUpdate.OSSClient/AppShell.xaml @@ -10,5 +10,4 @@ Title="Home" ContentTemplate="{DataTemplate local:MainPage}" Route="MainPage" /> - - + \ No newline at end of file diff --git a/src/c#/GeneralUpdate.OSSClient/MainPage.xaml b/src/c#/GeneralUpdate.OSSClient/MainPage.xaml index a5fd5af..636a0e8 100644 --- a/src/c#/GeneralUpdate.OSSClient/MainPage.xaml +++ b/src/c#/GeneralUpdate.OSSClient/MainPage.xaml @@ -34,8 +34,6 @@ SemanticProperties.Hint="Counts the number of times you click" Clicked="OnCounterClicked" HorizontalOptions="Center" /> - - - + \ No newline at end of file diff --git a/src/c#/GeneralUpdate.OSSClient/MauiProgram.cs b/src/c#/GeneralUpdate.OSSClient/MauiProgram.cs index 87aa782..49737cd 100644 --- a/src/c#/GeneralUpdate.OSSClient/MauiProgram.cs +++ b/src/c#/GeneralUpdate.OSSClient/MauiProgram.cs @@ -16,7 +16,7 @@ namespace GeneralUpdate.OSSClient }); #if DEBUG - builder.Logging.AddDebug(); + builder.Logging.AddDebug(); #endif return builder.Build(); diff --git a/src/c#/GeneralUpdate.OSSClient/Platforms/Android/MainActivity.cs b/src/c#/GeneralUpdate.OSSClient/Platforms/Android/MainActivity.cs index 9e45c1c..00f343b 100644 --- a/src/c#/GeneralUpdate.OSSClient/Platforms/Android/MainActivity.cs +++ b/src/c#/GeneralUpdate.OSSClient/Platforms/Android/MainActivity.cs @@ -1,6 +1,5 @@ using Android.App; using Android.Content.PM; -using Android.OS; namespace GeneralUpdate.OSSClient { diff --git a/src/c#/GeneralUpdate.OSSClient/Resources/Styles/Colors.xaml b/src/c#/GeneralUpdate.OSSClient/Resources/Styles/Colors.xaml index 245758b..3f82da2 100644 --- a/src/c#/GeneralUpdate.OSSClient/Resources/Styles/Colors.xaml +++ b/src/c#/GeneralUpdate.OSSClient/Resources/Styles/Colors.xaml @@ -1,6 +1,6 @@  - @@ -17,19 +17,19 @@ #404040 #212121 #141414 - - - - - - - - - - - - - + + + + + + + + + + + + + #F7B548 #FFD590 @@ -40,5 +40,4 @@ #3E8EED #72ACF1 #A7CBF6 - \ No newline at end of file diff --git a/src/c#/GeneralUpdate.OSSClient/Resources/Styles/Styles.xaml b/src/c#/GeneralUpdate.OSSClient/Resources/Styles/Styles.xaml index dc4a034..152a2fe 100644 --- a/src/c#/GeneralUpdate.OSSClient/Resources/Styles/Styles.xaml +++ b/src/c#/GeneralUpdate.OSSClient/Resources/Styles/Styles.xaml @@ -1,6 +1,6 @@  - @@ -9,14 +9,14 @@ @@ -401,5 +401,4 @@ - - + \ No newline at end of file diff --git a/src/c#/GeneralUpdate.SystemService/GeneralUpdate.SystemService.csproj b/src/c#/GeneralUpdate.SystemService/GeneralUpdate.SystemService.csproj index 3bd060b..a13f703 100644 --- a/src/c#/GeneralUpdate.SystemService/GeneralUpdate.SystemService.csproj +++ b/src/c#/GeneralUpdate.SystemService/GeneralUpdate.SystemService.csproj @@ -8,18 +8,57 @@ + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + diff --git a/src/c#/GeneralUpdate.SystemService/Properties/launchSettings.json b/src/c#/GeneralUpdate.SystemService/Properties/launchSettings.json index ab9db06..fe8baaf 100644 --- a/src/c#/GeneralUpdate.SystemService/Properties/launchSettings.json +++ b/src/c#/GeneralUpdate.SystemService/Properties/launchSettings.json @@ -9,4 +9,4 @@ } } } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.SystemService/Services/WillMessageService.cs b/src/c#/GeneralUpdate.SystemService/Services/WillMessageService.cs index cc9c554..3aed374 100644 --- a/src/c#/GeneralUpdate.SystemService/Services/WillMessageService.cs +++ b/src/c#/GeneralUpdate.SystemService/Services/WillMessageService.cs @@ -1,5 +1,6 @@ using GeneralUpdate.Core.WillMessage; using System.Diagnostics; + #if WINDOWS using System.Runtime.InteropServices; #endif @@ -21,17 +22,17 @@ namespace GeneralUpdate.SystemService.Services private FileSystemWatcher _fileWatcher; private ILogger _logger; -#endregion + #endregion Private Members #region Constructors - public WillMessageService(IConfiguration configuration, ILogger logger) + public WillMessageService(IConfiguration configuration, ILogger logger) { _path = configuration.GetValue("WatcherPath"); _logger = logger; } - #endregion + #endregion Constructors #region Public Methods @@ -56,7 +57,7 @@ namespace GeneralUpdate.SystemService.Services _logger.LogInformation("File watcher executed."); stoppingToken.Register(() => OnStopping()); _fileWatcher = new FileSystemWatcher(_path); - // Watch for changes in LastAccess and LastWrite times, and the renaming of files or directories. + // Watch for changes in LastAccess and LastWrite times, and the renaming of files or directories. _fileWatcher.NotifyFilter = NotifyFilters.LastWrite; // Only watch text files. _fileWatcher.Filter = "*.*"; @@ -84,11 +85,11 @@ namespace GeneralUpdate.SystemService.Services return base.StopAsync(cancellationToken); } - #endregion + #endregion Public Methods #region Private Methods - private void OnChanged(object sender, FileSystemEventArgs e) + private void OnChanged(object sender, FileSystemEventArgs e) { try { @@ -116,7 +117,7 @@ namespace GeneralUpdate.SystemService.Services } } - private void Diagnosis(string processName) + private void Diagnosis(string processName) { try { @@ -140,6 +141,6 @@ namespace GeneralUpdate.SystemService.Services } } -#endregion + #endregion Private Methods } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.SystemService/appsettings.Development.json b/src/c#/GeneralUpdate.SystemService/appsettings.Development.json index b2dcdb6..07c8e4c 100644 --- a/src/c#/GeneralUpdate.SystemService/appsettings.Development.json +++ b/src/c#/GeneralUpdate.SystemService/appsettings.Development.json @@ -5,4 +5,4 @@ "Microsoft.Hosting.Lifetime": "Information" } } -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.SystemService/appsettings.json b/src/c#/GeneralUpdate.SystemService/appsettings.json index 1ac231f..2702323 100644 --- a/src/c#/GeneralUpdate.SystemService/appsettings.json +++ b/src/c#/GeneralUpdate.SystemService/appsettings.json @@ -6,4 +6,4 @@ } }, "WatcherPath": "C:\\generalupdate_willmessage" -} +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Upgrad/Program.cs b/src/c#/GeneralUpdate.Upgrad/Program.cs index 0a9e88a..ac3952d 100644 --- a/src/c#/GeneralUpdate.Upgrad/Program.cs +++ b/src/c#/GeneralUpdate.Upgrad/Program.cs @@ -1,10 +1,8 @@ using GeneralUpdate.Core; using GeneralUpdate.Core.Bootstrap; -using GeneralUpdate.Core.Domain.Entity; using GeneralUpdate.Core.Domain.Enum; using GeneralUpdate.Core.Events.CommonArgs; using GeneralUpdate.Core.Events.MultiEventArgs; -using GeneralUpdate.Core.Strategys; using GeneralUpdate.Core.Strategys.PlatformWindows; using System.Text; -- Gitee From 4b35a667a10bac8da6e3039a0b6c63c4a1c5057e Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Fri, 19 Jan 2024 22:34:12 +0800 Subject: [PATCH 08/11] add gitkeep --- .../WillMessage/.gitkeep | 0 .../FileProvider-Serialization.cs | 29 +++++++++++++++++++ .../ContentProvider/.gitkeep | 0 .../ContentProvider/.gitkeep | 0 .../Domain/DTO/Assembler/.gitkeep | 0 .../Domain/Entity/Assembler/.gitkeep | 0 .../Exceptions/CustomArgs/.gitkeep | 0 .../Exceptions/CustomException/.gitkeep | 0 .../HashAlgorithms/.gitkeep | 0 .../Utrils/.gitkeep | 0 10 files changed, 29 insertions(+) create mode 100644 src/c#/GeneralUpdate.ClientCore/WillMessage/.gitkeep create mode 100644 src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Serialization.cs create mode 100644 src/c#/GeneralUpdate.Maui.OSS/ContentProvider/.gitkeep create mode 100644 src/c#/GeneralUpdate.SystemService/ContentProvider/.gitkeep create mode 100644 src/c#/GeneralUpdate.SystemService/Domain/DTO/Assembler/.gitkeep create mode 100644 src/c#/GeneralUpdate.SystemService/Domain/Entity/Assembler/.gitkeep create mode 100644 src/c#/GeneralUpdate.SystemService/Exceptions/CustomArgs/.gitkeep create mode 100644 src/c#/GeneralUpdate.SystemService/Exceptions/CustomException/.gitkeep create mode 100644 src/c#/GeneralUpdate.SystemService/HashAlgorithms/.gitkeep create mode 100644 src/c#/GeneralUpdate.SystemService/Utrils/.gitkeep diff --git a/src/c#/GeneralUpdate.ClientCore/WillMessage/.gitkeep b/src/c#/GeneralUpdate.ClientCore/WillMessage/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Serialization.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Serialization.cs new file mode 100644 index 0000000..4a03e46 --- /dev/null +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Serialization.cs @@ -0,0 +1,29 @@ +using Newtonsoft.Json; +using System.IO; + +namespace GeneralUpdate.Core.ContentProvider +{ + public partial class FileProvider + { + public static void CreateJson(string targetPath, T obj) + { + if (!Directory.Exists(targetPath)) Directory.CreateDirectory(targetPath); + if (File.Exists(targetPath)) File.Delete(targetPath); + var jsonString = JsonConvert.SerializeObject(obj); + File.WriteAllText(targetPath, jsonString); + } + + public static T GetJson(string path) + { + if (File.Exists(path)) + { + var json = File.ReadAllText(path); + if (json != null) + { + return JsonConvert.DeserializeObject(json); + } + } + return default(T); + } + } +} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Maui.OSS/ContentProvider/.gitkeep b/src/c#/GeneralUpdate.Maui.OSS/ContentProvider/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/c#/GeneralUpdate.SystemService/ContentProvider/.gitkeep b/src/c#/GeneralUpdate.SystemService/ContentProvider/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/c#/GeneralUpdate.SystemService/Domain/DTO/Assembler/.gitkeep b/src/c#/GeneralUpdate.SystemService/Domain/DTO/Assembler/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/c#/GeneralUpdate.SystemService/Domain/Entity/Assembler/.gitkeep b/src/c#/GeneralUpdate.SystemService/Domain/Entity/Assembler/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/c#/GeneralUpdate.SystemService/Exceptions/CustomArgs/.gitkeep b/src/c#/GeneralUpdate.SystemService/Exceptions/CustomArgs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/c#/GeneralUpdate.SystemService/Exceptions/CustomException/.gitkeep b/src/c#/GeneralUpdate.SystemService/Exceptions/CustomException/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/c#/GeneralUpdate.SystemService/HashAlgorithms/.gitkeep b/src/c#/GeneralUpdate.SystemService/HashAlgorithms/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/c#/GeneralUpdate.SystemService/Utrils/.gitkeep b/src/c#/GeneralUpdate.SystemService/Utrils/.gitkeep new file mode 100644 index 0000000..e69de29 -- Gitee From 1f53ecc9e1b3769464dbd19ae0f2de60121d7b1f Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Sat, 20 Jan 2024 21:51:08 +0800 Subject: [PATCH 09/11] refactor: Reconstructs file lookup rules --- .../ContentProvider/FileProvider-Manage.cs | 141 ++++-------------- 1 file changed, 31 insertions(+), 110 deletions(-) diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs index df65f26..f073acc 100644 --- a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs @@ -1,4 +1,5 @@ -using GeneralUpdate.Core.HashAlgorithms; +using GeneralUpdate.Core.Exceptions; +using GeneralUpdate.Core.HashAlgorithms; using System; using System.Collections.Generic; using System.IO; @@ -24,126 +25,46 @@ namespace GeneralUpdate.Core.ContentProvider public partial class FileProvider { - /// - /// 根据参数内容筛选出sourceDir、targetDir两个文件路径中符合要求的文件信息 - /// - /// 源目录 - /// 目标目录 - /// 筛选结果保存目录 - /// 筛选条件,可以是文件名,可以是文件后缀名 - /// 文件可执行的操作:增、删、查、改、拷贝 - /// 集合运算:交集、并集、差集 - /// 整个方法里的操作是否递归执行 - /// 是否保持目录结构的完整性 - /// - public List Handle(string sourceDir, string targetDir, string resultDir, List condition, FileOperations fileOption, SetOperations setOperations, bool recursion, bool integrality) + public List ExecuteOperation(string sourceDir, string targetDir, List extensionsCondition, List filenamesCondition) { - IEnumerable sourceFiles = Directory.EnumerateFiles(sourceDir, "*.*", recursion ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) - .Select(path => new FileInfo(path)) - .Select(fileInfo => new FileNode - { - Id = fileInfo.GetHashCode(), - Name = fileInfo.Name, - FullName = fileInfo.FullName, - Path = fileInfo.DirectoryName, - Hash = CalculateFileHash(fileInfo) - }); - IEnumerable targetFiles = Directory.EnumerateFiles(targetDir, "*.*", recursion ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) - .Select(path => new FileInfo(path)) - .Select(fileInfo => new FileNode - { - Id = fileInfo.GetHashCode(), - Name = fileInfo.Name, - FullName = fileInfo.FullName, - Path = fileInfo.DirectoryName, - Hash = CalculateFileHash(fileInfo) - }); - - // 然后根据条件筛选满足要求的文件 - IEnumerable filteredSourceFiles = sourceFiles.Where(file => condition.Any(c => file.Name.Contains(c) || file.Name.EndsWith(c))); - IEnumerable filteredTargetFiles = targetFiles.Where(file => condition.Any(c => file.Name.Contains(c) || file.Name.EndsWith(c))); - - IEnumerable resultFiles; - switch (setOperations) - { - case SetOperations.Intersection: - resultFiles = filteredSourceFiles.Intersect(filteredTargetFiles); - break; + if (string.IsNullOrWhiteSpace(sourceDir) || string.IsNullOrWhiteSpace(targetDir) || extensionsCondition == null || filenamesCondition == null) + ThrowExceptionUtility.ThrowIfNull(); - case SetOperations.Union: - resultFiles = filteredSourceFiles.Union(filteredTargetFiles); - break; - - case SetOperations.Difference: - resultFiles = filteredSourceFiles.Except(filteredTargetFiles); - break; - - default: - throw new ArgumentException("Invalid operation.", nameof(setOperations)); - } - - foreach (var file in resultFiles) - { - ExecuteFileOperation(file, fileOption, resultDir, integrality); - } + var filesInDirA = GetFilesWithSHA256(sourceDir, extensionsCondition, filenamesCondition); + var filesInDirB = GetFilesWithSHA256(targetDir, extensionsCondition, filenamesCondition); - return resultFiles.ToList(); + var inBNotInA = InFirstNotInSecond(filesInDirA, filesInDirB); + var inANotInB = InFirstNotInSecond(filesInDirA, filesInDirB); + return new List(); } - private string CalculateFileHash(FileInfo file) + bool ShouldSkipFile(string filePath, IList extensionsToSkip, IList filenamesToSkip) { - var hashAlgorithm = new Sha256HashAlgorithm(); - return hashAlgorithm.ComputeHash(file.FullName); + var fileInfo = new FileInfo(filePath); + return extensionsToSkip.Contains(fileInfo.Extension) || filenamesToSkip.Contains(fileInfo.Name); } - /// - /// 执行文件操作. - /// - /// 文件对象. - /// 要执行的操作. - /// 结果目录. - /// 是否保留结构. - private void ExecuteFileOperation(FileNode file, FileOperations operation, string resultDir, bool retainStructure) + Dictionary GetFilesWithSHA256(string path, IList extensionsToSkip, IList filenamesToSkip) { - string destinationPath = Path.Combine(resultDir, retainStructure ? file.RelativePath : file.Name); - - switch (operation) + var result = new Dictionary(); + foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) { - case FileOperations.Add: - // 如果文件已存在,此操作将覆盖现有文件 - File.Copy(file.Path, destinationPath, true); - break; - - case FileOperations.Delete: - if (File.Exists(destinationPath)) - { - File.Delete(destinationPath); - } - break; - - case FileOperations.Update: - // 在这里,我们假定更新操作意味着复制源文件到目标位置,覆盖现有文件 - File.Copy(file.Path, destinationPath, true); - break; - - case FileOperations.Copy: - // 确保目标目录存在 - string directoryName = Path.GetDirectoryName(destinationPath); - if (!Directory.Exists(directoryName)) - { - Directory.CreateDirectory(directoryName); - } - // 拷贝文件到新的位置 - File.Copy(file.Path, destinationPath, true); - break; - - case FileOperations.Query: - // 对于“查询”操作,我们不执行任何文件操作,只在控制台中打印出相关信息 - Console.WriteLine($"Found file: {file.FullName}"); - break; + if (!ShouldSkipFile(file, extensionsToSkip, filenamesToSkip)) + { + var hashAlgorithm = new Sha256HashAlgorithm(); + result[file] = hashAlgorithm.ComputeHash(file); + } + } + return result; + } - default: - throw new ArgumentException("Invalid operation", nameof(operation)); + IEnumerable InFirstNotInSecond(Dictionary first, Dictionary second) + { + foreach (var pair in first) + { + string value; + if (!second.TryGetValue(pair.Key, out value) || !value.Equals(pair.Value)) + yield return pair.Key; } } -- Gitee From 84cacbc7aefa49a78697f1493a816a78722ba371 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Sun, 21 Jan 2024 19:21:42 +0800 Subject: [PATCH 10/11] Refactoring FileProvider --- src/c#/GeneralUpdate.Client/MySample.cs | 18 +++-- .../Differential/Common/.gitkeep | 0 .../GeneralUpdate.ClientCore.csproj | 10 +-- .../ContentProvider/FileProvider-Comparer.cs} | 20 +++--- .../ContentProvider/FileProvider-Filter.cs} | 13 ++-- .../ContentProvider/FileProvider-Manage.cs | 70 ++----------------- .../ContentProvider/FileProvider.cs | 3 +- .../Config/ConfigFactory.cs | 6 +- .../DifferentialCore.cs | 15 ++-- .../GeneralUpdate.Differential.csproj | 2 + .../GeneralUpdate.Maui.OSS.csproj | 3 +- .../GeneralUpdate.SystemService.csproj | 3 +- 12 files changed, 52 insertions(+), 111 deletions(-) delete mode 100644 src/c#/GeneralUpdate.ClientCore/Differential/Common/.gitkeep rename src/c#/{GeneralUpdate.Differential/Common/DirectoryComparer.cs => GeneralUpdate.Core/ContentProvider/FileProvider-Comparer.cs} (77%) rename src/c#/{GeneralUpdate.Differential/Common/Filefilter.cs => GeneralUpdate.Core/ContentProvider/FileProvider-Filter.cs} (83%) diff --git a/src/c#/GeneralUpdate.Client/MySample.cs b/src/c#/GeneralUpdate.Client/MySample.cs index d125ce7..72e631d 100644 --- a/src/c#/GeneralUpdate.Client/MySample.cs +++ b/src/c#/GeneralUpdate.Client/MySample.cs @@ -325,10 +325,20 @@ namespace GeneralUpdate.Client var targetPath = "D:\\packet\\target"; var resultPath = "D:\\packet\\patchs"; - FileProvider fileProvider = new FileProvider(); - var list = fileProvider.Handle(sourcePath, targetPath, resultPath, null, FileOperations.Query, SetOperations.Intersection, true, true); - foreach (var item in list) - Console.WriteLine(item.Name); + //FileProvider fileProvider = new FileProvider(); + //var list = fileProvider.ExecuteOperation(sourcePath, targetPath,new List(), new List()); + //foreach (var item in list) { + // Console.WriteLine(item); + //} + //Console.WriteLine("total" + list.Count()); + //Console.WriteLine("--------------------------------------"); + //FileProvider fileProvider1 = new FileProvider(); + //var list1 = fileProvider1.ExecuteOperation(targetPath, sourcePath, new List(), new List()); + //foreach (var item in list1) + //{ + // Console.WriteLine(item); + //} + //Console.WriteLine("total" + list1.Count()); } #endregion 文件管理测试 diff --git a/src/c#/GeneralUpdate.ClientCore/Differential/Common/.gitkeep b/src/c#/GeneralUpdate.ClientCore/Differential/Common/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj b/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj index f2f1d0e..de6d08b 100644 --- a/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj +++ b/src/c#/GeneralUpdate.ClientCore/GeneralUpdate.ClientCore.csproj @@ -32,7 +32,6 @@ - @@ -76,6 +75,8 @@ + + @@ -160,8 +161,6 @@ - - @@ -201,19 +200,14 @@ - - - - - diff --git a/src/c#/GeneralUpdate.Differential/Common/DirectoryComparer.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Comparer.cs similarity index 77% rename from src/c#/GeneralUpdate.Differential/Common/DirectoryComparer.cs rename to src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Comparer.cs index 4926bcd..ae8cfcd 100644 --- a/src/c#/GeneralUpdate.Differential/Common/DirectoryComparer.cs +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Comparer.cs @@ -3,21 +3,17 @@ using System.Collections.Generic; using System.IO; using System.Linq; -namespace GeneralUpdate.Differential.Common +namespace GeneralUpdate.Core.ContentProvider { - internal class DirectoryComparer + public partial class FileProvider { - private readonly string _directoryA; - private readonly string _directoryB; + private string _directoryA; + private string _directoryB; - public DirectoryComparer(string directoryA, string directoryB) - { - this._directoryA = directoryA.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; - this._directoryB = directoryB.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; - } - - public List Comparer() + public List Comparer(string directoryA, string directoryB) { + _directoryA = directoryA.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + _directoryB = directoryB.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; var filesInDirectoryA = new HashSet(GetAllFiles(_directoryA).Select(file => file.Substring(_directoryA.Length)), StringComparer.InvariantCultureIgnoreCase); var missingFilesPath = GetAllFiles(_directoryB).Where(fileB => !filesInDirectoryA.Contains(fileB.Substring(_directoryB.Length))).ToList(); var missingFiles = missingFilesPath.Select(path => new FileInfo(path)).ToList(); @@ -68,4 +64,4 @@ namespace GeneralUpdate.Differential.Common } } } -} \ No newline at end of file +} diff --git a/src/c#/GeneralUpdate.Differential/Common/Filefilter.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Filter.cs similarity index 83% rename from src/c#/GeneralUpdate.Differential/Common/Filefilter.cs rename to src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Filter.cs index 919a162..ba44771 100644 --- a/src/c#/GeneralUpdate.Differential/Common/Filefilter.cs +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Filter.cs @@ -1,11 +1,10 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; +using System.Text; -namespace GeneralUpdate.Differential.Common +namespace GeneralUpdate.Core.ContentProvider { - /// - /// Used to filter out non-updatable file formats during the update process. - /// - public class Filefilter + public partial class FileProvider { private static List _blackFiles, _blackFileFormats; @@ -32,4 +31,4 @@ namespace GeneralUpdate.Differential.Common /// public static List GetBlackFileFormats() => _blackFileFormats ?? new List() { ".patch", ".7z", ".zip", ".rar", ".tar", ".json" }; } -} \ No newline at end of file +} diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs index f073acc..77fa0b8 100644 --- a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider-Manage.cs @@ -3,75 +3,15 @@ using GeneralUpdate.Core.HashAlgorithms; using System; using System.Collections.Generic; using System.IO; -using System.Linq; namespace GeneralUpdate.Core.ContentProvider { - public enum FileOperations - { - Query, - Delete, - Update, - Add, - Copy - } - - public enum SetOperations - { - Intersection, - Union, - Difference - } - public partial class FileProvider { - public List ExecuteOperation(string sourceDir, string targetDir, List extensionsCondition, List filenamesCondition) - { - if (string.IsNullOrWhiteSpace(sourceDir) || string.IsNullOrWhiteSpace(targetDir) || extensionsCondition == null || filenamesCondition == null) - ThrowExceptionUtility.ThrowIfNull(); - - var filesInDirA = GetFilesWithSHA256(sourceDir, extensionsCondition, filenamesCondition); - var filesInDirB = GetFilesWithSHA256(targetDir, extensionsCondition, filenamesCondition); - - var inBNotInA = InFirstNotInSecond(filesInDirA, filesInDirB); - var inANotInB = InFirstNotInSecond(filesInDirA, filesInDirB); - return new List(); - } - - bool ShouldSkipFile(string filePath, IList extensionsToSkip, IList filenamesToSkip) - { - var fileInfo = new FileInfo(filePath); - return extensionsToSkip.Contains(fileInfo.Extension) || filenamesToSkip.Contains(fileInfo.Name); - } - - Dictionary GetFilesWithSHA256(string path, IList extensionsToSkip, IList filenamesToSkip) - { - var result = new Dictionary(); - foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) - { - if (!ShouldSkipFile(file, extensionsToSkip, filenamesToSkip)) - { - var hashAlgorithm = new Sha256HashAlgorithm(); - result[file] = hashAlgorithm.ComputeHash(file); - } - } - return result; - } - - IEnumerable InFirstNotInSecond(Dictionary first, Dictionary second) - { - foreach (var pair in first) - { - string value; - if (!second.TryGetValue(pair.Key, out value) || !value.Equals(pair.Value)) - yield return pair.Key; - } - } - public static string GetTempDirectory(string name) { - var path2 = $"generalupdate_{DateTime.Now.ToString("yyyy-MM-dd")}_{name}"; - var tempDir = Path.Combine(Path.GetTempPath(), path2); + var path = $"generalupdate_{DateTime.Now.ToString("yyyy-MM-dd")}_{name}"; + var tempDir = Path.Combine(Path.GetTempPath(), path); if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); @@ -79,7 +19,7 @@ namespace GeneralUpdate.Core.ContentProvider return tempDir; } - public static FileInfo[] GetAllFiles(string path) + public static List GetAllfiles(string path) { try { @@ -88,9 +28,9 @@ namespace GeneralUpdate.Core.ContentProvider var tmpDir = new DirectoryInfo(path).GetDirectories(); foreach (var dic in tmpDir) { - files.AddRange(GetAllFiles(dic.FullName)); + files.AddRange(GetAllfiles(dic.FullName)); } - return files.ToArray(); + return files; } catch (Exception) { diff --git a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs index 7767c84..5a89c1d 100644 --- a/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs +++ b/src/c#/GeneralUpdate.Core/ContentProvider/FileProvider.cs @@ -1,5 +1,4 @@ using GeneralUpdate.Core.HashAlgorithms; -using GeneralUpdate.Differential.Common; using System; using System.Collections.Generic; using System.IO; @@ -102,7 +101,7 @@ namespace GeneralUpdate.Core.ContentProvider /// private bool IsMatchBlacklist(string subPath) { - var blackList = Filefilter.GetBlackFiles(); + var blackList = GetBlackFiles(); if (blackList == null) return false; foreach (var file in blackList) { diff --git a/src/c#/GeneralUpdate.Differential/Config/ConfigFactory.cs b/src/c#/GeneralUpdate.Differential/Config/ConfigFactory.cs index bf33fc8..5033c1c 100644 --- a/src/c#/GeneralUpdate.Differential/Config/ConfigFactory.cs +++ b/src/c#/GeneralUpdate.Differential/Config/ConfigFactory.cs @@ -1,5 +1,5 @@ -using GeneralUpdate.Core.HashAlgorithms; -using GeneralUpdate.Differential.Common; +using GeneralUpdate.Core.ContentProvider; +using GeneralUpdate.Core.HashAlgorithms; using GeneralUpdate.Differential.Config.Cache; using GeneralUpdate.Differential.Config.Handles; using System; @@ -158,7 +158,7 @@ namespace GeneralUpdate.Differential.Config foreach (var file in rootDirectoryInfo.GetFiles()) { var extensionName = Path.GetExtension(file.Name); - if (!Filefilter.GetBlackFileFormats().Contains(extensionName)) continue; + if (!FileProvider.GetBlackFileFormats().Contains(extensionName)) continue; var fullName = file.FullName; files.Add(fullName); } diff --git a/src/c#/GeneralUpdate.Differential/DifferentialCore.cs b/src/c#/GeneralUpdate.Differential/DifferentialCore.cs index 1e237a4..95f4438 100644 --- a/src/c#/GeneralUpdate.Differential/DifferentialCore.cs +++ b/src/c#/GeneralUpdate.Differential/DifferentialCore.cs @@ -1,7 +1,6 @@ using GeneralUpdate.Core.ContentProvider; using GeneralUpdate.Core.HashAlgorithms; using GeneralUpdate.Differential.Binary; -using GeneralUpdate.Differential.Common; using System; using System.Collections.Generic; using System.IO; @@ -101,7 +100,7 @@ namespace GeneralUpdate.Differential var oldfile = finOldFile == null ? "" : finOldFile.FullName; var newfile = file.FullName; var extensionName = Path.GetExtension(file.FullName); - if (File.Exists(oldfile) && File.Exists(newfile) && !Filefilter.GetBlackFileFormats().Contains(extensionName)) + if (File.Exists(oldfile) && File.Exists(newfile) && !FileProvider.GetBlackFileFormats().Contains(extensionName)) { //Generate the difference file to the difference directory . await new BinaryHandle().Clean(oldfile, newfile, tempPath0); @@ -135,8 +134,8 @@ namespace GeneralUpdate.Differential if (!Directory.Exists(appPath) || !Directory.Exists(patchPath)) return; try { - var patchFiles = FileProvider.GetAllFiles(patchPath); - var oldFiles = FileProvider.GetAllFiles(appPath); + var patchFiles = FileProvider.GetAllfiles(patchPath); + var oldFiles = FileProvider.GetAllfiles(appPath); //If a JSON file for the deletion list is found in the update package, it will be deleted based on its contents. var deleteListJson = patchFiles.FirstOrDefault(i => i.Name.Equals(DELETE_FILES_NAME)); @@ -181,7 +180,7 @@ namespace GeneralUpdate.Differential /// /// A collection of blacklist files that are skipped when updated. /// A collection of blacklist file name extensions that are skipped on update. - public void SetBlocklist(List blackFiles, List blackFileFormats) => Filefilter.SetBlacklist(blackFiles, blackFileFormats); + public void SetBlocklist(List blackFiles, List blackFileFormats) => FileProvider.SetBlacklist(blackFiles, blackFileFormats); #endregion Public Methods @@ -217,12 +216,12 @@ namespace GeneralUpdate.Differential { try { - var dirCompare = new DirectoryComparer(patchPath, appPath); - var listExcept = dirCompare.Comparer(); + var fileProvider = new FileProvider(); + var listExcept = fileProvider.Comparer(appPath, patchPath); foreach (var file in listExcept) { var extensionName = Path.GetExtension(file.FullName); - if (Filefilter.GetBlackFileFormats().Contains(extensionName)) continue; + if (FileProvider.GetBlackFileFormats().Contains(extensionName)) continue; var targetFileName = file.FullName.Replace(patchPath, "").TrimStart("\\".ToCharArray()); var targetPath = Path.Combine(appPath, targetFileName); var parentFolder = Directory.GetParent(targetPath); diff --git a/src/c#/GeneralUpdate.Differential/GeneralUpdate.Differential.csproj b/src/c#/GeneralUpdate.Differential/GeneralUpdate.Differential.csproj index f6fdd38..cb3eba9 100644 --- a/src/c#/GeneralUpdate.Differential/GeneralUpdate.Differential.csproj +++ b/src/c#/GeneralUpdate.Differential/GeneralUpdate.Differential.csproj @@ -27,6 +27,8 @@ + + diff --git a/src/c#/GeneralUpdate.Maui.OSS/GeneralUpdate.Maui.OSS.csproj b/src/c#/GeneralUpdate.Maui.OSS/GeneralUpdate.Maui.OSS.csproj index 3cfd08b..fde0276 100644 --- a/src/c#/GeneralUpdate.Maui.OSS/GeneralUpdate.Maui.OSS.csproj +++ b/src/c#/GeneralUpdate.Maui.OSS/GeneralUpdate.Maui.OSS.csproj @@ -51,6 +51,8 @@ + + @@ -71,7 +73,6 @@ - diff --git a/src/c#/GeneralUpdate.SystemService/GeneralUpdate.SystemService.csproj b/src/c#/GeneralUpdate.SystemService/GeneralUpdate.SystemService.csproj index a13f703..5018bde 100644 --- a/src/c#/GeneralUpdate.SystemService/GeneralUpdate.SystemService.csproj +++ b/src/c#/GeneralUpdate.SystemService/GeneralUpdate.SystemService.csproj @@ -20,6 +20,8 @@ + + @@ -49,7 +51,6 @@ - -- Gitee From 3ea989fa96cd4e486726f0fc6c3a8df526c76212 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Fri, 26 Jan 2024 22:30:39 +0800 Subject: [PATCH 11/11] remove: The GeneralUpdate.AspNetCore component is no longer maintained The core of this component is a unified common method, only SignalR push and a version verification function. Subsequent iterations of the function of design will no longer be a company for each gm for example will depend on the user authentication, access to the file server, and each company is different so the following sample code will be handed over to the GeneralLibrary/GeneralUpdate - Samples in maintenance warehouse. No longer as a standalone component. --- .../GeneralUpdate.Api.csproj | 17 --- src/c#/GeneralUpdate.Api/Program.cs | 106 ------------------ .../Properties/launchSettings.json | 30 ----- .../appsettings.Development.json | 8 -- src/c#/GeneralUpdate.Api/appsettings.json | 9 -- .../DTO/RespMessage.cs | 13 --- .../GeneralUpdate.AspNetCore.csproj | 50 --------- .../GeneralUpdate.ico | Bin 16958 -> 0 bytes .../Hubs/VersionHub.cs | 91 --------------- .../Properties/launchSettings.json | 12 -- .../Services/GeneralUpdateService.cs | 72 ------------ .../Services/IUpdateService.cs | 38 ------- .../GeneralUpdate.AspNetCore/Utils/.gitkeep | 0 src/c#/GeneralUpdate.sln | 14 --- 14 files changed, 460 deletions(-) delete mode 100644 src/c#/GeneralUpdate.Api/GeneralUpdate.Api.csproj delete mode 100644 src/c#/GeneralUpdate.Api/Program.cs delete mode 100644 src/c#/GeneralUpdate.Api/Properties/launchSettings.json delete mode 100644 src/c#/GeneralUpdate.Api/appsettings.Development.json delete mode 100644 src/c#/GeneralUpdate.Api/appsettings.json delete mode 100644 src/c#/GeneralUpdate.AspNetCore/DTO/RespMessage.cs delete mode 100644 src/c#/GeneralUpdate.AspNetCore/GeneralUpdate.AspNetCore.csproj delete mode 100644 src/c#/GeneralUpdate.AspNetCore/GeneralUpdate.ico delete mode 100644 src/c#/GeneralUpdate.AspNetCore/Hubs/VersionHub.cs delete mode 100644 src/c#/GeneralUpdate.AspNetCore/Properties/launchSettings.json delete mode 100644 src/c#/GeneralUpdate.AspNetCore/Services/GeneralUpdateService.cs delete mode 100644 src/c#/GeneralUpdate.AspNetCore/Services/IUpdateService.cs delete mode 100644 src/c#/GeneralUpdate.AspNetCore/Utils/.gitkeep diff --git a/src/c#/GeneralUpdate.Api/GeneralUpdate.Api.csproj b/src/c#/GeneralUpdate.Api/GeneralUpdate.Api.csproj deleted file mode 100644 index fd8c7c4..0000000 --- a/src/c#/GeneralUpdate.Api/GeneralUpdate.Api.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - - - - - - diff --git a/src/c#/GeneralUpdate.Api/Program.cs b/src/c#/GeneralUpdate.Api/Program.cs deleted file mode 100644 index 8babcdf..0000000 --- a/src/c#/GeneralUpdate.Api/Program.cs +++ /dev/null @@ -1,106 +0,0 @@ -using GeneralUpdate.AspNetCore.DTO; -using GeneralUpdate.AspNetCore.Services; -using GeneralUpdate.Core.Domain.DTO; -using GeneralUpdate.Core.Domain.Enum; -using Newtonsoft.Json; - -var builder = WebApplication.CreateBuilder(args); -builder.Services.AddSingleton(); -builder.Services.AddSignalR(); -var app = builder.Build(); - -/** - * Push the latest version information in real time. - */ -//app.MapHub("/versionhub"); - -//app.MapPost("/push", async Task (HttpContext context) => -//{ -// try -// { -// var hubContext = context.RequestServices.GetRequiredService>(); -// await hubContext.SendMessage("TESTNAME", "123"); -// } -// catch (Exception ex) -// { -// return ex.Message; -// } -// return "OK"; -//}); - -/** - * Check if an update is required. - */ -app.MapGet("/versions/{clientType}/{clientVersion}/{clientAppKey}", (int clientType, string clientVersion, string clientAppKey, IUpdateService updateService) => -{ - var versions = new List(); - var hash = "28d10f1fc2a23dd1afe0af40d132b25c72ea56005963f653c27889f03d381c8d";//ɺõĸ°ļMD5룬Ϊظͻ˵ʱҪ֤ͬǷ - var pubTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(); - string version = null; - if (clientType == AppType.ClientApp) - { - //client - //version = "0.0.0.0"; - version = "9.9.9.9";//Ϊ9óΪҪ - } - else if (clientType == AppType.UpgradeApp) - { - //upgrad - version = "0.0.0.0"; - //version = "9.9.9.9"; //Ϊ9óΪҪ - } - var url = $"http://192.168.1.7/WpfClient_1_24.1.5.1218.zip";//°صַ - var name = "update"; - versions.Add(new VersionDTO(hash, pubTime, version, url, name)); - return updateService.Update(clientType, clientVersion, version, clientAppKey, GetAppSecretKey(), false, versions); -}); - -/** - * Upload update package. - */ -app.MapPost("/upload", async Task (HttpContext context, HttpRequest request) => -{ - var uploadReapDTO = new UploadReapDTO(); - try - { - var contextReq = context.Request; - int.TryParse(contextReq.Form["clientType"], out int clientType); - var version = contextReq.Form["clientType"].ToString(); - var clientAppKey = contextReq.Form["clientAppKey"].ToString(); - var hash = contextReq.Form["hash"].ToString(); - - if (!request.HasFormContentType) throw new Exception("ContentType was not included in the request !"); - var form = await request.ReadFormAsync(); - - var formFile = form.Files["file"]; - if (formFile is null || formFile.Length == 0) throw new ArgumentNullException("Uploaded update package file not found !"); - await using var stream = formFile.OpenReadStream(); - byte[] buffer = new byte[stream.Length]; - stream.Read(buffer, 0, buffer.Length); - //TODO:save to file server. - string localPath = $"E:\\{formFile.FileName}"; - await using var fileStream = new FileStream(localPath, FileMode.CreateNew, FileAccess.Write); - fileStream.Write(buffer, 0, buffer.Length); - - //TODO: data persistence.To mysql , sqlserver.... - - uploadReapDTO.Code = HttpStatus.OK; - uploadReapDTO.Body = "Published successfully."; - uploadReapDTO.Message = RespMessage.RequestSucceeded; - return JsonConvert.SerializeObject(uploadReapDTO); - } - catch (Exception ex) - { - uploadReapDTO.Code = HttpStatus.BAD_REQUEST; - uploadReapDTO.Body = $"Failed to publish ! Because : {ex.Message}"; - uploadReapDTO.Message = RespMessage.RequestFailed; - return JsonConvert.SerializeObject(uploadReapDTO); - } -}); - -app.Run(); - -string GetAppSecretKey() -{ - return "B8A7FADD-386C-46B0-B283-C9F963420C7C"; -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Api/Properties/launchSettings.json b/src/c#/GeneralUpdate.Api/Properties/launchSettings.json deleted file mode 100644 index 8ea702e..0000000 --- a/src/c#/GeneralUpdate.Api/Properties/launchSettings.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:43557", - "sslPort": 44365 - } - }, - "profiles": { - "GeneralUpdate.Api": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "applicationUrl": "http://127.0.0.1:5001", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Api/appsettings.Development.json b/src/c#/GeneralUpdate.Api/appsettings.Development.json deleted file mode 100644 index 1b2d3ba..0000000 --- a/src/c#/GeneralUpdate.Api/appsettings.Development.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.Api/appsettings.json b/src/c#/GeneralUpdate.Api/appsettings.json deleted file mode 100644 index ec04bc1..0000000 --- a/src/c#/GeneralUpdate.Api/appsettings.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*" -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.AspNetCore/DTO/RespMessage.cs b/src/c#/GeneralUpdate.AspNetCore/DTO/RespMessage.cs deleted file mode 100644 index fb89b3e..0000000 --- a/src/c#/GeneralUpdate.AspNetCore/DTO/RespMessage.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace GeneralUpdate.AspNetCore.DTO -{ - public class RespMessage - { - public const string RequestSucceeded = "Request succeeded."; - - public const string RequestFailed = "Request failed!"; - - public const string RequestNone = "No need to update."; - - public const string ServerException = "Server internal exception!"; - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.AspNetCore/GeneralUpdate.AspNetCore.csproj b/src/c#/GeneralUpdate.AspNetCore/GeneralUpdate.AspNetCore.csproj deleted file mode 100644 index ff68e03..0000000 --- a/src/c#/GeneralUpdate.AspNetCore/GeneralUpdate.AspNetCore.csproj +++ /dev/null @@ -1,50 +0,0 @@ - - - - netstandard2.0 - GeneralUpdate.ico - GeneralUpdate.png - False - 1.1.0.0 - 1.1.0.0 - 1.1.1 - https://github.com/WELL-E/AutoUpdater - Copyright © 2022 - Provide update information proofreading and download update package services. - juster.zhu - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/c#/GeneralUpdate.AspNetCore/GeneralUpdate.ico b/src/c#/GeneralUpdate.AspNetCore/GeneralUpdate.ico deleted file mode 100644 index 7cb4a86c1bbf84baf7b783ab21b4a7e1cf700455..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16958 zcmeI(1+*N+5(eN6?oQB<;KAK31b24{?(UwT!QI{6-GjTk2X}X`w_kHAXR_?QAz>fz zq&bt>ndzD7s`~4%zk4pVT8H|7-MZE4|8}W$?Ov;Otkr5=>s$R)tyg_>zO-(&TJKK3 zZNHtU)uILM=bwL$r=Na04msqIc=5#-`+MRKKl~8SJ@;IE_uY5>o&Rq+_~3&N;_S1} zjvaU0F{Ybtx;X#*^ZS{`_KPpRIF?&(xp?fc$NHUb_T!gdehJ%uO8erAFXGy3uZ@#W zJ~?i=<(4?*lv84!dFF{Nw%8)R{`%|q^2;yd!V52qjW^ynw%&T{IQ7(1ZJ@(jm^UXJZ*M}cr?4QzJe);9tb=O_v=%bI0S6+D~-gx7UIPt_2V~;)dh|MM!g{kZkkTjQaJ9t!?rmnJuM*=3hlbImp5h$D`O zM;>`3e*E#rV)L`lJ{!Gz_m0y}J1su{{PVxv1>$hfK?fDA@4ox)C1z`_wN`Ao<(4G} zdiLxY3opEI@ef-LJM6G{@4fd*UhvQM+ixFp%rQsV#9Mp#;fD)G_^WTsT){_kvfj*V-ty>=XY@WFB0ZMVhhtFIp0Y_meVas!Jjbk%{Si^|1GuD zQYG&Ee82$*6l}oVop;_DKmGJmQ#Z7iV@+=uz)75xxo2!g9d%T}x7Z$c+;OqaI_s1; ziQPsUZ4|4mwpz&rw$DHR{KZCgTy)VzC9Zg4mRV*g_VWYZ;YYsE4-d!}ew=ycnPbBZ zH!ObDw@a5U1zU?Pwpj5QUfFKD?c(aIuP!{h$tIf=Y~mkvNSusm@4feqk3asn@GBnX zOT2`u+G_mx=%bIuo_p>Y2OfA}TyVh!h0oai?YG~S_{!OpR$8fyLBAPioH522V~iMf z*kNO^!3K+Ah8d>phaP(9SY(k!O5WpxvBny!*gxWkBgWKIPhI*AKKS4k}&s<`OCE}A$K8Z~?-LxE! zHri;#mv6uQc3gSol`-Lj6UGQ5j8J?#)l^e8HUInXzmI$Gy|>_dnPrxVRaRN0kiCk1YOWtDKp1(n*U?yn`LC!&c|coy&E&dH3CSWAVioFULK4 z^eFzow_@cPbIv(uTyn`JaqhY2{?2~3;~n`7>+7$-etAF6!(}+gJ1)KS(o)lKKO13q zlu<@0&xh62LHsVp-n-y}3kE(<{NqebZA|+XT4%Ivl zn4tLHa~+R5>Zm1VJMFYn3^mkHtem%e)|=!#Zi1VpBDS^{{8pgUvLKle2n|#I6u%ea&AEO z8<%{MJI5b?eDvwlr})}$&%xUoyc+L0=bTe=4z}bwdvN*9H{V=vA?K!@cG{pnyc;%* z`MmSai>_U}mi`%k=Qa6w)m2v&-NILzTB^nw11*9V^m*;I*NQ)Gzy0=7$JI2LS$_HD zOKr!4so7!0IE@iU(S=$y{>I{XV4COS&Ey9h;utR(3l0?%T)-cF>-vdyRI}7e9Fz6C z*?ZXz&$NtMD(_(okEow&r8$ip@>?#rF8(l*O--cdjD?<&_u5xqeO2_UoOYk%fo=Rh z`Q(!q-l7-08|Tu}Gys3dX}oyF6<3tU^TCr(J{fo2byvIg(;DV(p2wf+JREq3_YIl!%T~~*2uXz)E(U9^3N1G?$QTg6p6K9&_rI%hRHGkV}w=Hv8 zzHMysNSIL4x_wtsGNWBIZ=9|vRTQ#g%lj~|8OtYKjp_Qslyzw@Ss7ux;ay<(#;CkncNmHL4 z;|Q45@E$&KUVnY_n)>=` z)wO1Ag%wsPI;&&Hjzzz#n{+Y`U?cmiWzcN&1?@=RuD9NL@zz^!#WT-56Xp@l(+zy3 zj+h4-hx=*96<1s_I@dM2e&dZdUePb+ZG5o94m-r?qmLd-FTHfB-^R&@=9YAd{&USW zSFF0~s^vHRPDi`Xd(=SosV{iZdK3<%QQ2aw<|)mZdQE>>yMq~8ot846y62vIN-gjX z`Wu$`(i}{#-Eqeqg=1Xz99o(E-shN3Vh4@rSp7fr&_m0()iJmeW6yJ)U74%2h53*3 zVr1S(S2#9CI7&TB*Ta)~C-3Pp6)t_-|%E-Guwaq^)MGV#42I zNkhP;bt=!qPx72^V1=eO-&SwghKJ16@Q2)ClQkB#m#)&@dFP$N&EjS~#ySZs(6wSs zf8s{#AadP$4^09a;*swatCd$?xy+f_mORsz{bGX$Qo}a$fjHq_j?r`DrE^oEGssb9Y!*16=0^cEhN(2mNu5{I*8Wo)2InbrxK}BcI4g zYfOCE-u-Ra!)K`ha}Ch*+R7pPXw8fruxsq}ihOduM_nh_;0)GrpFH!81XuViFL0iC z(k!$NPO<*c)_bet=Ly7vezuRz}T(jYI*VT7^!@>Gm+i4F6Vh#hes`)#N(Lu&GD2*S*5f<4g zhn#~6*!2$I@zfN$8ehq6W5n(3QYXaQJd|DRQ^RNr``q;9D|T9|#EI&Ld(6T3fgXYb z&(FqY94Jp=oOU#4mp8t*wl&Ym``g>6{c0}`$6cEF1x|oXbpR*yt*5uB3FI z_ST7V4(VO6z#4+3WLj0>f zN&EH7ykIB3bIcd^eCe5LW#)jq%ckbZPn>V8Ie*UUgR)ouyn`>;Ot1L1ueO`J`3^+S z@(H|(S;idJ{EA`7p2H2G7iU_*wkbRQ^s~D_`j=_Nxaue;yRO z^B#7~D|G;_tpE7dCI{e89Qc9ega6D~V`e8?*pYe7X1~SMZ}`wpT+>f!cj7`mxTX)E zx*s1{&+#0%*YJTc;XXB*mTg5dXM=lu%LnRTuBlmXJER19~-K+4(N9^zuE2njJ>$?ferR?3~k^T{_(N=tJbqt4Lqz%l=`I`@{*@+VkAXYfeUS1n7yVG{u zm$uon-sg2;D&NCOPu1|^w{%`9$*P!}=Kl#<%LcW`8 z(OI~V9xzX5zuXmj+Q{4%f3q3hGrybJ>pr%+21kzlb}r{k&f7f4Jj?s7G2}N6w)y65 z4%%w`doEwoyVe)*9xbE>(FWG&tFbkHu}?di*_`L}<0qR~v$uLp%=tlnIM0{z%{nUW zU7hP%gMzb0ljOFpy)Hr#WW7(-+RMwR(*Y;G3p_GkKoR z(bsjyo^Q=ue)$$ef6%DLW3z@z8?>7Lt+CMBw4T3-!uj^j!5}R_i@;{p2gVGu@;B|V zPhaFY$N0hgf|gV>@|rztd9K=-y34w;HA(B!*1mizrGM!ER_DKO)V6GDuKA|#GuH6o z5g&PXuHU2|GH0vyus36x=h?_lu#&lCZ-W8flGsagS)VoU7H@ysM4O6{T0|4!r&cz$ z<2`dA`k&6C|K$a3)@?yY=bd#J)Cdem21A%zHx)~CmU{bjYg)?@Uhy>2WeMhd>y-H zkKgDBH6E|xSL@BNmUBJ%C)T)6Ol;OXee1A3hof5A%&TBct=G&6tUG$Yc_-e*MaJhm z{q2}$#1Za=5w#hA$zypT=kdKckhOAo1lMBiZw_c|bGhm_9D2uf^~c(z&AeAka3K4A z?{8(3Tk2kw1FFxb3-MC*x;1!tC~mNWBVk7@<*;0_o(em-3}*OOf4YjU<>zYSTRy>g zzLU{DxxuDyrtF8qRyFI3_=XL(wwgKw^Uda-?0^liqaDRmjO?vdumzSH?XAAcIOI3o z-E4i|*l>e-j1OAb*x#qld3= zuv4AyRQsg;^1=7WRyN!ZzxZCA#Rukq&cUNiT=)lP$zgMbYO{uFYDllV%&&~yyWjzi)K~V&ZTObkzC~xW2BI`0_#Hvzy(kpV|vs-u>@t zY`}H!jfY`gtmT3nRQu#{=CI%NnfWrz`v0#S({19Wc3Mx6Q}|!J`PSd@!9X^?@jYJb z<)e4gyZ+w5ee@^n{Mm0``My88$6atI_wxS%R{M=dJ*35PK8(Y#@yc`c5-#+W|1^#3 zu!Jl5nJw}P)?vZlmf%2ojPLl6Kl!iO-+uj38(P^VulU2*Y1q^&Z1>xi hnh}rDd~~eyxPZNKny$??m{yLt{`X)1Z~wy{_!lXMf@c5# diff --git a/src/c#/GeneralUpdate.AspNetCore/Hubs/VersionHub.cs b/src/c#/GeneralUpdate.AspNetCore/Hubs/VersionHub.cs deleted file mode 100644 index 2f79b50..0000000 --- a/src/c#/GeneralUpdate.AspNetCore/Hubs/VersionHub.cs +++ /dev/null @@ -1,91 +0,0 @@ -using GeneralUpdate.Core.Utils; -using Microsoft.AspNetCore.SignalR; -using System; -using System.Threading.Tasks; - -namespace GeneralUpdate.AspNetCore.Hubs -{ - public enum HubStatus - { - Connected = 1, - Disconnected = 2 - } - - public class VersionHub : Hub - { - #region Private Members - - private const string ReceiveMessageflag = "ReceiveMessage"; - private const string SendMessageflag = "SendMessage"; - private const string Onlineflag = "Online"; - private const string GroupName = "VersionGroup"; - - public delegate void ConnectionStatus(HubStatus hubStatus, string message); - - public event ConnectionStatus OnConnectionStatus; - - #endregion Private Members - - #region Public Methods - - public override async Task OnConnectedAsync() - { - await Groups.AddToGroupAsync(Context.ConnectionId, GroupName); - await base.OnConnectedAsync(); - if (OnConnectionStatus != null) OnConnectionStatus(HubStatus.Connected, "The Version hub is connected ."); - } - - public override async Task OnDisconnectedAsync(Exception exception) - { - await Groups.RemoveFromGroupAsync(Context.ConnectionId, GroupName); - await base.OnDisconnectedAsync(exception); - if (OnConnectionStatus != null) OnConnectionStatus(HubStatus.Disconnected, "The Version hub is disconnected !"); - } - - /// - /// Kick client connection from group. - /// - /// client connectionId. - /// - public async Task Remove(string connectionId) - { - if (string.IsNullOrWhiteSpace(connectionId)) - throw new ArgumentNullException($"'VersionHub' The required parameter remove cannot be null !"); - - try - { - await Groups.RemoveFromGroupAsync(connectionId, GroupName); - } - catch (Exception ex) - { - throw new Exception($"'VersionHub' Remove error : {ex.Message} .", ex.InnerException); - } - } - - public Task ThrowException() => throw new HubException("This error will be sent to the client!"); - - #endregion Public Methods - } - - public static class HubProvider - { - private const string GroupName = "VersionGroup"; - private const string ReceiveMessageFlag = "ReceiveMessage"; - - public static async Task SendMessage(this IHubContext hub, string user, string message) - { - if (string.IsNullOrWhiteSpace(user) || string.IsNullOrWhiteSpace(message)) - throw new ArgumentNullException($"'VersionHub' The required parameter send message cannot be null !"); - - try - { - var clientParameter = SerializeUtil.Serialize(message); - await hub.Clients.Groups(GroupName).SendAsync(ReceiveMessageFlag, user, clientParameter); - } - catch (Exception ex) - { - throw new Exception($"'VersionHub' Send message error : {ex.Message} .", ex.InnerException); - } - } - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.AspNetCore/Properties/launchSettings.json b/src/c#/GeneralUpdate.AspNetCore/Properties/launchSettings.json deleted file mode 100644 index 86aa9f9..0000000 --- a/src/c#/GeneralUpdate.AspNetCore/Properties/launchSettings.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "profiles": { - "GeneralUpdate.AspNetCore": { - "commandName": "Project", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "https://localhost:65355;http://localhost:65363" - } - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.AspNetCore/Services/GeneralUpdateService.cs b/src/c#/GeneralUpdate.AspNetCore/Services/GeneralUpdateService.cs deleted file mode 100644 index 042b984..0000000 --- a/src/c#/GeneralUpdate.AspNetCore/Services/GeneralUpdateService.cs +++ /dev/null @@ -1,72 +0,0 @@ -using GeneralUpdate.AspNetCore.DTO; -using GeneralUpdate.Core.Domain.DTO; -using GeneralUpdate.Core.Domain.Enum; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; - -namespace GeneralUpdate.AspNetCore.Services -{ - public class GeneralUpdateService : IUpdateService - { - /// - /// Update validate. - /// - /// 1:ClientApp 2:UpdateApp - /// The current version number of the client. - /// The latest version number of the server. - /// Do you need to force an update. - /// Each version update (Query the latest version information in the database according to the client version number). - /// - public string Update(int clientType, string clientVersion, string serverLastVersion, string clientAppKey, string appSecretKey, - bool isForce, List versions) - { - ParameterVerification(clientType, clientVersion, serverLastVersion, clientAppKey, appSecretKey, versions); - if (!clientAppKey.Equals(appSecretKey)) throw new Exception("App key does not exist or is incorrect !"); - Version clientLastVersion; - var respDTO = new VersionRespDTO(); - try - { - if (!Version.TryParse(clientVersion, out clientLastVersion)) - { - respDTO.Message = $"{RespMessage.RequestFailed} Wrong version number."; - respDTO.Code = HttpStatus.BAD_REQUEST; - return JsonConvert.SerializeObject(respDTO); - } - var lastVersion = new Version(serverLastVersion); - if (clientLastVersion < lastVersion) - { - respDTO.Body = new VersionBodyDTO() { ClientType = clientType, Versions = versions, IsUpdate = true, IsForcibly = isForce }; - respDTO.Code = HttpStatus.OK; - respDTO.Message = RespMessage.RequestSucceeded; - } - else - { - respDTO.Body = new VersionBodyDTO() { ClientType = clientType, Versions = versions, IsUpdate = false, IsForcibly = false }; - respDTO.Code = HttpStatus.OK; - respDTO.Message = RespMessage.RequestNone; - } - } - catch - { - respDTO.Message = RespMessage.ServerException; - respDTO.Code = HttpStatus.SERVICE_UNAVAILABLE; - } - return JsonConvert.SerializeObject(respDTO); - } - - private void ParameterVerification(int clientType, string clientVersion, string serverLastVersion, string clientAppkey, string appSecretKey, List versions) - { - if (clientType <= 0) throw new Exception(@"'clientType' cannot be less than or equal to 0 !"); - if (string.IsNullOrWhiteSpace(clientVersion)) throw new ArgumentNullException(@"'clientVersion' cannot be null !"); - if (string.IsNullOrWhiteSpace(serverLastVersion)) throw new ArgumentNullException(@"'serverLastVersion' cannot be null !"); - if (versions == null) throw new ArgumentNullException(@"versions cannot be null !"); - if (string.IsNullOrEmpty(clientAppkey) || string.IsNullOrEmpty(appSecretKey)) throw new NullReferenceException("The APP key does not exist !"); - } - - public string Report(int clientType, string clientVersion, string clientAppkey, string appSecretKey, string meesage, string dumpBase64, string logBase64, Exception exception) => string.Empty; - - private void ParameterVerification(int clientType, string clientVersion, string clientAppkey, string appSecretKey, string meesage, string dumpBase64, string logBase64, Exception exception) - { } - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.AspNetCore/Services/IUpdateService.cs b/src/c#/GeneralUpdate.AspNetCore/Services/IUpdateService.cs deleted file mode 100644 index d32b541..0000000 --- a/src/c#/GeneralUpdate.AspNetCore/Services/IUpdateService.cs +++ /dev/null @@ -1,38 +0,0 @@ -using GeneralUpdate.Core.Domain.DTO; -using System; -using System.Collections.Generic; - -namespace GeneralUpdate.AspNetCore.Services -{ - public interface IUpdateService - { - /// - /// Verify whether the current version of the client needs to be updated. - /// - /// 1:ClientApp 2:UpdateApp - /// Current version of the client - /// The latest version of the server. - /// The appkey agreed by the client and server. - /// Appkey is stored in the database. - /// Whether to force all versions to be updated. - /// - /// Json object. - string Update(int clientType, string clientVersion, string serverLastVersion, string clientAppKey, string appSecretKey, bool isForce, List versions); - - /// - /// When this web api is called at the end of the automatic update, it does not mean that every call is successful. - /// Failure, rollback, and success scenarios will inform the server of the result of the update through this web api. - /// If there is an exception let the decision maker decide whether to fix the problem by pushing the latest version of the update again. - /// - /// 1:ClientApp 2:UpdateApp - /// Current version of the client. - /// The appkey agreed by the client and server. - /// Appkey is stored in the database. - /// The message from the client is used to describe the current situation to the decision maker. - /// If an exception occurs, the dump file is returned. - /// If an exception occurs, the log log is returned - /// If an exception occurs, the object is returned. - /// - string Report(int clientType, string clientVersion, string clientAppkey, string appSecretKey, string meesage, string dumpBase64, string logBase64, Exception exception); - } -} \ No newline at end of file diff --git a/src/c#/GeneralUpdate.AspNetCore/Utils/.gitkeep b/src/c#/GeneralUpdate.AspNetCore/Utils/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/c#/GeneralUpdate.sln b/src/c#/GeneralUpdate.sln index b42f9e2..0bcd9f7 100644 --- a/src/c#/GeneralUpdate.sln +++ b/src/c#/GeneralUpdate.sln @@ -11,16 +11,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GeneralUpdate.Single", "Gen EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GeneralUpdate.Zip", "GeneralUpdate.Zip\GeneralUpdate.Zip.csproj", "{D94882E1-55A7-4787-B049-265F52DC576E}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GeneralUpdate.AspNetCore", "GeneralUpdate.AspNetCore\GeneralUpdate.AspNetCore.csproj", "{7D529953-3846-485F-AC71-3EEACB9161EC}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GeneralUpdate.ClientCore", "GeneralUpdate.ClientCore\GeneralUpdate.ClientCore.csproj", "{BAEFF926-6B2C-46F1-BB73-AA2AB1355565}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GeneralUpdate.Differential", "GeneralUpdate.Differential\GeneralUpdate.Differential.csproj", "{40BDA496-7614-4213-92D0-3B1B187675D3}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{74BE0282-A10D-4A81-A0F0-FAA79A6152B7}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GeneralUpdate.Api", "GeneralUpdate.Api\GeneralUpdate.Api.csproj", "{AE3E4ADF-CE3B-4E94-B1BE-F0B9916B7F20}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GeneralUpdate.Upgrad", "GeneralUpdate.Upgrad\GeneralUpdate.Upgrad.csproj", "{E1F9FF93-CA63-4A9C-82F0-450F09ED81F9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GeneralUpdate.Maui.OSS", "GeneralUpdate.Maui.OSS\GeneralUpdate.Maui.OSS.csproj", "{C4BDA544-2A6E-442C-B7D0-32CD7A996933}" @@ -49,10 +45,6 @@ Global {D94882E1-55A7-4787-B049-265F52DC576E}.Debug|Any CPU.Build.0 = Debug|Any CPU {D94882E1-55A7-4787-B049-265F52DC576E}.Release|Any CPU.ActiveCfg = Release|Any CPU {D94882E1-55A7-4787-B049-265F52DC576E}.Release|Any CPU.Build.0 = Release|Any CPU - {7D529953-3846-485F-AC71-3EEACB9161EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7D529953-3846-485F-AC71-3EEACB9161EC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7D529953-3846-485F-AC71-3EEACB9161EC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7D529953-3846-485F-AC71-3EEACB9161EC}.Release|Any CPU.Build.0 = Release|Any CPU {BAEFF926-6B2C-46F1-BB73-AA2AB1355565}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BAEFF926-6B2C-46F1-BB73-AA2AB1355565}.Debug|Any CPU.Build.0 = Debug|Any CPU {BAEFF926-6B2C-46F1-BB73-AA2AB1355565}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -61,10 +53,6 @@ Global {40BDA496-7614-4213-92D0-3B1B187675D3}.Debug|Any CPU.Build.0 = Debug|Any CPU {40BDA496-7614-4213-92D0-3B1B187675D3}.Release|Any CPU.ActiveCfg = Release|Any CPU {40BDA496-7614-4213-92D0-3B1B187675D3}.Release|Any CPU.Build.0 = Release|Any CPU - {AE3E4ADF-CE3B-4E94-B1BE-F0B9916B7F20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AE3E4ADF-CE3B-4E94-B1BE-F0B9916B7F20}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AE3E4ADF-CE3B-4E94-B1BE-F0B9916B7F20}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AE3E4ADF-CE3B-4E94-B1BE-F0B9916B7F20}.Release|Any CPU.Build.0 = Release|Any CPU {E1F9FF93-CA63-4A9C-82F0-450F09ED81F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E1F9FF93-CA63-4A9C-82F0-450F09ED81F9}.Debug|Any CPU.Build.0 = Debug|Any CPU {E1F9FF93-CA63-4A9C-82F0-450F09ED81F9}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -95,10 +83,8 @@ Global {35BFF228-5EE4-49A6-B721-FB0122E967A0} = {91F059E6-7AD3-4FB7-9604-30A7849C6EFF} {57300FDD-58E9-489E-BF2E-C69A87938845} = {91F059E6-7AD3-4FB7-9604-30A7849C6EFF} {D94882E1-55A7-4787-B049-265F52DC576E} = {91F059E6-7AD3-4FB7-9604-30A7849C6EFF} - {7D529953-3846-485F-AC71-3EEACB9161EC} = {91F059E6-7AD3-4FB7-9604-30A7849C6EFF} {BAEFF926-6B2C-46F1-BB73-AA2AB1355565} = {91F059E6-7AD3-4FB7-9604-30A7849C6EFF} {40BDA496-7614-4213-92D0-3B1B187675D3} = {91F059E6-7AD3-4FB7-9604-30A7849C6EFF} - {AE3E4ADF-CE3B-4E94-B1BE-F0B9916B7F20} = {74BE0282-A10D-4A81-A0F0-FAA79A6152B7} {E1F9FF93-CA63-4A9C-82F0-450F09ED81F9} = {74BE0282-A10D-4A81-A0F0-FAA79A6152B7} {C4BDA544-2A6E-442C-B7D0-32CD7A996933} = {91F059E6-7AD3-4FB7-9604-30A7849C6EFF} {2877DCA1-7EA6-42E9-A1C2-399B51E24893} = {74BE0282-A10D-4A81-A0F0-FAA79A6152B7} -- Gitee