Untility.cs 10 KB

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