Untility.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /* ==============================================================================
  2. * 功能描述:Untility
  3. * 创 建 者:Garrett
  4. * 创建日期:2019/1/29 11:19:14
  5. * ==============================================================================*/
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. using SAGA.DotNetUtils.Encrypt;
  15. using ICSharpCode.SharpZipLib.Zip;
  16. using SAGA.DotNetUtils.Extend;
  17. using SAGA.DotNetUtils.FileOperate;
  18. using Aliyun.OSS;
  19. using Aliyun.OSS.Common;
  20. using Newtonsoft.Json.Linq;
  21. using SAGA.DotNetUtils.Http;
  22. using Update.Core.Entities;
  23. using WPFTestUpdate.Compress;
  24. namespace WPFTestUpdate
  25. {
  26. /// <summary>
  27. /// Untility
  28. /// </summary>
  29. public class Untility
  30. {
  31. /// <summary>
  32. /// 压缩文件夹
  33. /// </summary>
  34. /// <param name="destZipName"></param>
  35. /// <param name="dirs"></param>
  36. public static void CompressDir(string destZipName, string[] dirs, Action<string> compressChangeAction)
  37. {
  38. //using (ZipFile zip = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(destZipName))
  39. //{
  40. // zip.BeginUpdate();
  41. // long totalLen = 0;
  42. // foreach (string dir in dirs)
  43. // {
  44. // totalLen += GetDirectoryLength(dir);
  45. // }
  46. // CompressArgs compressArgs = new CompressArgs(0, 0, totalLen, compressChangeAction);
  47. // foreach (var dir in dirs)
  48. // {
  49. // FileInfo fileInfo = new FileInfo(dir);
  50. // string basePath = fileInfo.Directory?.FullName ?? "";
  51. // //ZipEntry e = new ZipEntry(Path.GetFileName(file));
  52. // ZipAddFile(zip, dir, basePath, compressArgs);
  53. // //break;
  54. // //zip.Add(file, Path.GetFileName(file));
  55. // }
  56. // compressChangeAction?.Invoke("Compressing ...");
  57. // zip.CommitUpdate();
  58. //}
  59. long totalLen = 0;
  60. foreach (string dir in dirs)
  61. {
  62. totalLen += GetDirectoryLength(dir);
  63. }
  64. CompressArgs compressArgs = new CompressArgs(0, 0, totalLen, compressChangeAction);
  65. using (ZipOutputStream s = new ZipOutputStream(File.Create(destZipName)))
  66. {
  67. s.SetLevel(6);
  68. foreach (var dir in dirs)
  69. {
  70. FileInfo fileInfo = new FileInfo(dir);
  71. string basePath = fileInfo.Directory?.FullName ?? "";
  72. CompressT.Compress(basePath, dir, s, compressArgs);
  73. }
  74. s.Finish();
  75. s.Close();
  76. }
  77. }
  78. /// <summary>
  79. /// 使用递归压缩文件夹和文件
  80. /// </summary>
  81. /// <param name="zip"></param>
  82. /// <param name="path"></param>
  83. /// <param name="basePath"></param>
  84. private static void ZipAddFile(ZipFile zip, string path, string basePath, CompressArgs args)
  85. {
  86. string fileName = path.Replace(basePath, "");
  87. DirectoryInfo dirInfo = new DirectoryInfo(path);
  88. if (dirInfo.Exists)
  89. {
  90. zip.AddDirectory(fileName);
  91. foreach (FileSystemInfo info in dirInfo.GetFileSystemInfos())
  92. {
  93. ZipAddFile(zip, info.FullName, basePath, args);
  94. }
  95. }
  96. else
  97. {
  98. args.IncrementTransferred = (new FileInfo(path)).Length;
  99. zip.Add(path, fileName);
  100. }
  101. }
  102. /// <summary>
  103. /// 获取指定路径的大小
  104. /// </summary>
  105. /// <param name="dirPath">路径</param>
  106. /// <returns></returns>
  107. public static long GetDirectoryLength(string dirPath)
  108. {
  109. long len = 0;
  110. //判断该路径是否存在(是否为文件夹)
  111. if (!Directory.Exists(dirPath))
  112. {
  113. //查询文件的大小
  114. len = FileSize(dirPath);
  115. }
  116. else
  117. {
  118. //定义一个DirectoryInfo对象
  119. DirectoryInfo di = new DirectoryInfo(dirPath);
  120. //通过GetFiles方法,获取di目录中的所有文件的大小
  121. foreach (FileInfo fi in di.GetFiles())
  122. {
  123. len += fi.Length;
  124. }
  125. //获取di中所有的文件夹,并存到一个新的对象数组中,以进行递归
  126. DirectoryInfo[] dis = di.GetDirectories();
  127. if (dis.Length > 0)
  128. {
  129. for (int i = 0; i < dis.Length; i++)
  130. {
  131. len += GetDirectoryLength(dis[i].FullName);
  132. }
  133. }
  134. }
  135. return len;
  136. }
  137. //所给路径中所对应的文件大小
  138. public static long FileSize(string filePath)
  139. {
  140. //定义一个FileInfo对象,是指与filePath所指向的文件相关联,以获取其大小
  141. FileInfo fileInfo = new FileInfo(filePath);
  142. return fileInfo.Length;
  143. }
  144. /// <summary>
  145. /// 获取可执行文件的版本值
  146. /// </summary>
  147. /// <param name="exePath"></param>
  148. /// <returns></returns>
  149. public static Version GetFileVersion(string exePath)
  150. {
  151. Version version = null;
  152. try
  153. {
  154. version = Assembly.ReflectionOnlyLoadFrom(exePath).GetName().Version;
  155. }
  156. catch (Exception e)
  157. {
  158. version = new Version("0,0,0,0");
  159. }
  160. return version;
  161. //return new Version(FileVersionInfo.GetVersionInfo(exePath).FileVersion);
  162. }
  163. private static Action<string> m_UploadAction;
  164. /// <summary>
  165. /// 上传压缩包
  166. /// </summary>
  167. /// <param name="url"></param>
  168. /// <param name="compressPath"></param>
  169. public static bool UploadCompress(string compressPath, Action<string> action)
  170. {
  171. bool result = true;
  172. string fileName = Path.GetFileName(compressPath);
  173. string key = $"{Const.OSSKeyPath}{fileName}";
  174. m_UploadAction = action;
  175. OssClient client = new OssClient(Const.Endpoint, Const.AccessKeyId, Const.AccessKeySecret);
  176. try
  177. {
  178. using (var fs = new MemoryStream(FileStreamOperate.ReadFile(compressPath)))
  179. {
  180. string bucketName = Const.BucketName;
  181. var putObjectRequest = new PutObjectRequest(bucketName, key, fs);
  182. putObjectRequest.StreamTransferProgress += UploadProgressCallback;
  183. client.PutObject(putObjectRequest);
  184. }
  185. Console.WriteLine("Put object:{0} succeeded", key);
  186. }
  187. catch (OssException ex)
  188. {
  189. Console.WriteLine(@"Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
  190. ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
  191. result = false;
  192. }
  193. catch (Exception ex)
  194. {
  195. Console.WriteLine($@"Failed with error info: { ex.Message}");
  196. result = false;
  197. }
  198. return result;
  199. }
  200. /// <summary>
  201. /// 下载进度条
  202. /// </summary>
  203. /// <param name="sender"></param>
  204. /// <param name="args"></param>
  205. private static void UploadProgressCallback(object sender, StreamTransferProgressArgs args)
  206. {
  207. var currentData = Math.Round(args.TransferredBytes * 100d / args.TotalBytes, 3);
  208. m_UploadAction?.Invoke(string.Format("UploadCallback - TotalBytes:{0}M, TransferredBytes:{1}M,UploadPrecent:{2}%",
  209. args.TotalBytes / 1024 / 1024, args.TransferredBytes / 1024 / 1024, currentData));
  210. }
  211. /// <summary>
  212. /// 保存md5值
  213. /// </summary>
  214. /// <param name="url"></param>
  215. /// <param name="md5"></param>
  216. public static string SaveVision(string key, string value)
  217. {
  218. string url = $"{Const.URL}/image-service/common/file_upload?systemId={Const.RevitServiceId}&secret={Const.RevitServiceSecret}&key={key}&overwrite=true";
  219. RestClient client = new RestClient(url, HttpVerb.POST, value);
  220. string request = client.PostRequest();
  221. return request;
  222. }
  223. /// <summary>
  224. /// 删除旧压缩包
  225. /// </summary>
  226. public static void DeleteCompress()
  227. {
  228. string compressName = $"{ReadVision()}_{Const.Key}.zip";
  229. string url = $"{Const.URL}/image-service/common/files_delete?systemId={Const.RevitServiceId}&secret={Const.RevitServiceSecret}";
  230. JArray jArray = new JArray();
  231. jArray.Add(compressName);
  232. JObject jObject = new JObject
  233. {
  234. { "keys", jArray }
  235. };
  236. RestClient client = new RestClient(url, HttpVerb.POST, jObject.ToString());
  237. string request = client.PostRequest();
  238. }
  239. /// <summary>
  240. /// 读取版本信息
  241. /// </summary>
  242. /// <param name="url"></param>
  243. /// <param name="key"></param>
  244. /// <returns></returns>
  245. public static Version ReadVision()
  246. {
  247. string url = $"{Const.URL}/image-service/common/file_get/{Const.Key}?systemId={Const.RevitServiceId}";
  248. Packages packages = null;
  249. try
  250. {
  251. RestClient client = new RestClient(url, HttpVerb.GET);
  252. string request = client.PostRequest();
  253. packages = new Packages(request);
  254. }
  255. catch (Exception e)
  256. {
  257. packages = new Packages("0,0,0,0");
  258. }
  259. return packages?.FullPackages.Max()?.To;
  260. }
  261. /// <summary>
  262. /// CanUpload
  263. /// </summary>
  264. /// <param name="exePath"></param>
  265. /// <returns></returns>
  266. public static bool CheckVision(string exePath, out string version)
  267. {
  268. Version serviceVersion = ReadVision();
  269. Version localVersion = GetFileVersion(exePath);
  270. version = $"ServiceVersion:{serviceVersion};LocalVersion:{localVersion}";
  271. return (serviceVersion == null || localVersion > serviceVersion);
  272. }
  273. }
  274. }