/* ==============================================================================
* 功能描述:Untility
* 创 建 者:Garrett
* 创建日期:2019/1/29 11:19:14
* ==============================================================================*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using SAGA.DotNetUtils.Encrypt;
using ICSharpCode.SharpZipLib.Zip;
using SAGA.DotNetUtils.Extend;
using SAGA.DotNetUtils.FileOperate;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Newtonsoft.Json.Linq;
using SAGA.DotNetUtils.Http;
using Update.Core.Entities;
using WPFTestUpdate.Compress;
namespace WPFTestUpdate
{
///
/// Untility
///
public class Untility
{
///
/// 压缩文件夹
///
///
///
public static void CompressDir(string destZipName, string[] dirs, Action compressChangeAction)
{
//using (ZipFile zip = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(destZipName))
//{
// zip.BeginUpdate();
// long totalLen = 0;
// foreach (string dir in dirs)
// {
// totalLen += GetDirectoryLength(dir);
// }
// CompressArgs compressArgs = new CompressArgs(0, 0, totalLen, compressChangeAction);
// foreach (var dir in dirs)
// {
// FileInfo fileInfo = new FileInfo(dir);
// string basePath = fileInfo.Directory?.FullName ?? "";
// //ZipEntry e = new ZipEntry(Path.GetFileName(file));
// ZipAddFile(zip, dir, basePath, compressArgs);
// //break;
// //zip.Add(file, Path.GetFileName(file));
// }
// compressChangeAction?.Invoke("Compressing ...");
// zip.CommitUpdate();
//}
long totalLen = 0;
foreach (string dir in dirs)
{
totalLen += GetDirectoryLength(dir);
}
CompressArgs compressArgs = new CompressArgs(0, 0, totalLen, compressChangeAction);
using (ZipOutputStream s = new ZipOutputStream(File.Create(destZipName)))
{
s.SetLevel(6);
foreach (var dir in dirs)
{
FileInfo fileInfo = new FileInfo(dir);
string basePath = fileInfo.Directory?.FullName ?? "";
CompressT.Compress(basePath, dir, s, compressArgs);
}
s.Finish();
s.Close();
}
}
///
/// 使用递归压缩文件夹和文件
///
///
///
///
private static void ZipAddFile(ZipFile zip, string path, string basePath, CompressArgs args)
{
string fileName = path.Replace(basePath, "");
DirectoryInfo dirInfo = new DirectoryInfo(path);
if (dirInfo.Exists)
{
zip.AddDirectory(fileName);
foreach (FileSystemInfo info in dirInfo.GetFileSystemInfos())
{
ZipAddFile(zip, info.FullName, basePath, args);
}
}
else
{
args.IncrementTransferred = (new FileInfo(path)).Length;
zip.Add(path, fileName);
}
}
///
/// 获取指定路径的大小
///
/// 路径
///
public static long GetDirectoryLength(string dirPath)
{
long len = 0;
//判断该路径是否存在(是否为文件夹)
if (!Directory.Exists(dirPath))
{
//查询文件的大小
len = FileSize(dirPath);
}
else
{
//定义一个DirectoryInfo对象
DirectoryInfo di = new DirectoryInfo(dirPath);
//通过GetFiles方法,获取di目录中的所有文件的大小
foreach (FileInfo fi in di.GetFiles())
{
len += fi.Length;
}
//获取di中所有的文件夹,并存到一个新的对象数组中,以进行递归
DirectoryInfo[] dis = di.GetDirectories();
if (dis.Length > 0)
{
for (int i = 0; i < dis.Length; i++)
{
len += GetDirectoryLength(dis[i].FullName);
}
}
}
return len;
}
//所给路径中所对应的文件大小
public static long FileSize(string filePath)
{
//定义一个FileInfo对象,是指与filePath所指向的文件相关联,以获取其大小
FileInfo fileInfo = new FileInfo(filePath);
return fileInfo.Length;
}
///
/// 获取可执行文件的版本值
///
///
///
public static Version GetFileVersion(string exePath)
{
Version version = null;
try
{
version = Assembly.ReflectionOnlyLoadFrom(exePath).GetName().Version;
}
catch (Exception e)
{
version = new Version("0,0,0,0");
}
return version;
//return new Version(FileVersionInfo.GetVersionInfo(exePath).FileVersion);
}
private static Action m_UploadAction;
///
/// 上传压缩包
///
///
///
public static bool UploadCompress(string compressPath, Action action)
{
bool result = true;
string fileName = Path.GetFileName(compressPath);
string key = $"{Const.OSSKeyPath}{fileName}";
m_UploadAction = action;
OssClient client = new OssClient(Const.Endpoint, Const.AccessKeyId, Const.AccessKeySecret);
try
{
using (var fs = new MemoryStream(FileStreamOperate.ReadFile(compressPath)))
{
string bucketName = Const.BucketName;
var putObjectRequest = new PutObjectRequest(bucketName, key, fs);
putObjectRequest.StreamTransferProgress += UploadProgressCallback;
client.PutObject(putObjectRequest);
}
Console.WriteLine("Put object:{0} succeeded", key);
}
catch (OssException ex)
{
Console.WriteLine(@"Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
result = false;
}
catch (Exception ex)
{
Console.WriteLine($@"Failed with error info: { ex.Message}");
result = false;
}
return result;
}
///
/// 下载进度条
///
///
///
private static void UploadProgressCallback(object sender, StreamTransferProgressArgs args)
{
var currentData = Math.Round(args.TransferredBytes * 100d / args.TotalBytes, 3);
m_UploadAction?.Invoke(string.Format("UploadCallback - TotalBytes:{0}M, TransferredBytes:{1}M,UploadPrecent:{2}%",
args.TotalBytes / 1024 / 1024, args.TransferredBytes / 1024 / 1024, currentData));
}
///
/// 保存md5值
///
///
///
public static string SaveVision(string key, string value)
{
string url = $"{Const.URL}/image-service/common/file_upload?systemId={Const.RevitServiceId}&secret={Const.RevitServiceSecret}&key={key}&overwrite=true";
RestClient client = new RestClient(url, HttpVerb.POST, value);
string request = client.PostRequest();
return request;
}
///
/// 删除旧压缩包
///
public static void DeleteCompress()
{
string compressName = $"{ReadVision()}_{Const.Key}.zip";
string url = $"{Const.URL}/image-service/common/files_delete?systemId={Const.RevitServiceId}&secret={Const.RevitServiceSecret}";
JArray jArray = new JArray();
jArray.Add(compressName);
JObject jObject = new JObject
{
{ "keys", jArray }
};
RestClient client = new RestClient(url, HttpVerb.POST, jObject.ToString());
string request = client.PostRequest();
}
///
/// 读取版本信息
///
///
///
///
public static Version ReadVision()
{
string url = $"{Const.URL}/image-service/common/file_get/{Const.Key}?systemId={Const.RevitServiceId}";
Packages packages = null;
try
{
RestClient client = new RestClient(url, HttpVerb.GET);
string request = client.PostRequest();
packages = new Packages(request);
}
catch (Exception e)
{
packages = new Packages("0,0,0,0");
}
return packages?.FullPackages.Max()?.To;
}
///
/// CanUpload
///
///
///
public static bool CheckVision(string exePath, out string version)
{
Version serviceVersion = ReadVision();
Version localVersion = GetFileVersion(exePath);
version = $"ServiceVersion:{serviceVersion};LocalVersion:{localVersion}";
return (serviceVersion == null || localVersion > serviceVersion);
}
}
}