using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Vinno.IUS.Common.Network; using Vinno.IUS.Common.Network.Leaf; using Vinno.IUS.Common.Network.Tcp; using Vinno.IUS.Common.Network.Transfer; using Vinno.vCloud.Common.Storage; using Vinno.vCloud.Common.Storage.ObjectStorageInfo; using Vinno.vCloud.Common.Storage.Upload; using Vinno.vCloud.Protocol.Infrastructures; using Vinno.vCloud.Protocol.Initializers; using Vinno.vCloud.Protocol.Messages.Client.Login; using Vinno.vCloud.Protocol.Messages.Client.Storage; using Vinno.vCloud.Protocol.Messages.Common; using Vinno.vCloud.Protocol.Messages.Login; using Vinno.vCloud.Protocol.Messages.Upgrade; namespace UpgradePackageUploadTool.Services { public class vCloudService { private StorageInfo _storageInfo; private object _storageInfoLocker = new object(); private ClientLeaf _leaf; private string _accountId; /// /// The event of Upload Progress Changing. /// public event EventHandler UploadProgressChanged; /// /// 服务器IP /// public string ServerIP { get; set; } /// /// 服务器端口 /// public int ServerPort { get; set; } /// /// 用户名 /// public string Account { get; set; } /// /// 密码 /// public string Password { get; set; } /// /// 构造函数,初始化 /// public vCloudService() { UploadHelper.GetAuthorization = GetUpgradeAuthorization; UploadHelper.GetCopyAuthorization = GetUpgradeCopyAuthorization; //Initial clientTags ClientTagsInitializer.Initialize(); } /// /// Connect Server Async /// /// public async Task ConnectServerAsync() { if (_leaf == null || !_leaf.Online) { await Task.Run(() => { RefreshLeaf(ServerIP, ServerPort); }); } using (var clientLoginRequest2 = MessagePool.GetMessage()) { clientLoginRequest2.Name = Account; clientLoginRequest2.Password = Password; clientLoginRequest2.Source = LoginSource.PersonalComputer; clientLoginRequest2.ClientVersion = "Upgrade Package Upload Tool"; clientLoginRequest2.Force = true; try { var result = await _leaf.SendAsync(clientLoginRequest2); var loginResult = LoginResult2.Convert(result); if (loginResult != null) { _accountId = loginResult.AccountId; return loginResult.Status; } } catch (ConnectionTimeoutException) { return LoginStatus.ConnectionTmeout; } catch (NotConnectedException) { return LoginStatus.ConnectServerFailed; } catch (Exception ex) { return LoginStatus.Unknown; } } return LoginStatus.Unknown; } /// /// DisConnect Server Async /// /// public async Task DisconnectServerAsync() { if (_leaf == null || !_leaf.Online) { return LogoffStatus.Success; } try { var clientLogoffRequest = MessagePool.GetMessage(); clientLogoffRequest.Name = Account; clientLogoffRequest.Password = Password; clientLogoffRequest.Source = LoginSource.PersonalComputer; var result = await _leaf.SendAsync(clientLogoffRequest); var logoffResult = LogoffResult.Convert(result); if (logoffResult != null) { return logoffResult.Status; } } catch { return LogoffStatus.Unknown; } return LogoffStatus.Unknown; } private void LeafOnlineCheck() { if (!_leaf.Online) { RefreshLeaf(ServerIP, ServerPort); } } private void RefreshLeaf(string serverIP, int serverPort) { _leaf?.Close(); if (string.IsNullOrEmpty(serverIP) || serverPort == 0) { throw new Exception("Server IP or Server Port is wrong!"); } var tcpCreator = new TcpCreator(serverIP, serverPort); if (!tcpCreator.HasValidIpAddress) { throw new Exception($"Tcp Creator dosen't have valid Ip Address"); } _leaf = new ClientLeaf(new LeafIdContext(), LeafMode.Dual, tcpCreator); if (!_leaf.Online) { _leaf.Close(); throw new Exception("Connect Server Failed."); } } /// /// Upload Package Async /// /// Pakage Path /// Package Version /// Package Name /// Description /// public async Task UploadDataAsync(string filePath, string version, string fileName, string description, string uniqueCode) { return await Task.Run(() => { LeafOnlineCheck(); var storageInfo = GetUpgradeStorageInfo(); var fileData = File.ReadAllBytes(filePath); var fileToken = UploadHelper.UploadFile(storageInfo, filePath, fileName, _accountId, uploadProgress => { var progress = (int)(uploadProgress * 100 * 0.95); OnUploadProgressChanged(progress); }, null, false, true); if (string.IsNullOrEmpty(fileToken)) { throw new Exception("Upload Fail!File Token is null"); } if (storageInfo.StorageType == StorageType.Default && !fileToken.Contains(FileTokenInfo.TokenSplitor[0])) { fileToken = $"{(int)storageInfo.StorageType}{FileTokenInfo.TokenSplitor[0]}{fileToken}"; } using (var savePackageRequest = MessagePool.GetMessage()) { savePackageRequest.CreateUserId = _accountId; savePackageRequest.Description = description; savePackageRequest.Version = version; savePackageRequest.FileSize = (int)new FileInfo(filePath).Length; savePackageRequest.FileToken = fileToken; savePackageRequest.UniquedCode = uniqueCode; savePackageRequest.FileName = fileName; var message = _leaf.Send(savePackageRequest); if (message == null) { throw new Exception("Create Package Request Fail."); } var ok = ResultMessage.Convert(message); if (ok == null || ok.ResultCode != OKResult.Code) { throw new Exception("Create Package Request Fail."); } OnUploadProgressChanged(100); return new GeneralPackInfo(Account, description, fileName, fileToken, savePackageRequest.FileSize, PackageType.Other, DateTime.UtcNow, version, uniqueCode); } }); } private void OnUploadProgressChanged(int progress) { UploadProgressChanged?.Invoke(this, progress); } /// /// Get Latest Package Info Async /// /// public async Task GetLatestPackageAsync(string uniquedCode) { using (var queryLatestPackageRequest = MessagePool.GetMessage()) { queryLatestPackageRequest.UniquedCode = uniquedCode; var message = await _leaf.SendAsync(queryLatestPackageRequest); if (message == null) { return null; } var result = GetPackageResult.Convert(message); if (result != null) { return new GeneralPackInfo(result.CreateUserName, result.Description, result.FileName, result.FileToken, result.FileSize, result.PackageType, result.UpdateTime, result.Version, result.UniquedCode); } } return null; } private StorageInfo GetUpgradeStorageInfo() { lock (_storageInfoLocker) { using (var request = MessagePool.GetMessage()) { var result = _leaf.Send(request); var getUpgradeInfoResult = GetUpgradeStorageInfoResult.Convert(result); if (getUpgradeInfoResult != null) { var url = getUpgradeInfoResult.StorageServerUrl; var storageType = getUpgradeInfoResult.StorageType; var config = getUpgradeInfoResult.Config; _storageInfo = new StorageInfo() { Url = url, StorageType = storageType, Config = config }; NodeMapping.NodeMappingInilization(_storageInfo.StorageNodeItems); } } return _storageInfo; } } private string GetUpgradeAuthorization(string fileName) { var authorization = string.Empty; var getUpgradeAuthorizationRequest = new GetUpgradeAuthorizationRequest(); getUpgradeAuthorizationRequest.FileName = fileName; var upgradeResult = _leaf.Send(getUpgradeAuthorizationRequest); var getUpgradeAuthorizationResult = GetUpgradeAuthorizationResult.Convert(upgradeResult); if (getUpgradeAuthorizationResult != null) { authorization = getUpgradeAuthorizationResult.Authorization; } return authorization; } private string GetUpgradeCopyAuthorization(string fileName, List> headers) { var authorization = string.Empty; var getUpgradeCopyAuthorizationRequest = new GetUpgradeCopyAuthorizationRequest(); getUpgradeCopyAuthorizationRequest.FileName = fileName; var list = new List(); if (headers?.Count > 0) { foreach (var item in headers) { list.Add(new KeyValuePairHeaderItem() { HeaderKey = item.Key, HeaderValue = item.Value }); } } getUpgradeCopyAuthorizationRequest.CopyHeaders = list; var upgradeResult = _leaf.Send(getUpgradeCopyAuthorizationRequest); var getUpgradeAuthorizationResult = GetUpgradeAuthorizationResult.Convert(upgradeResult); if (getUpgradeAuthorizationResult != null) { authorization = getUpgradeAuthorizationResult.Authorization; } return authorization; } } }