123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315 |
- 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;
- /// <summary>
- /// The event of Upload Progress Changing.
- /// </summary>
- public event EventHandler<int> UploadProgressChanged;
- /// <summary>
- /// 服务器IP
- /// </summary>
- public string ServerIP { get; set; }
- /// <summary>
- /// 服务器端口
- /// </summary>
- public int ServerPort { get; set; }
- /// <summary>
- /// 用户名
- /// </summary>
- public string Account { get; set; }
- /// <summary>
- /// 密码
- /// </summary>
- public string Password { get; set; }
- /// <summary>
- /// 构造函数,初始化
- /// </summary>
- public vCloudService()
- {
- UploadHelper.GetAuthorization = GetUpgradeAuthorization;
- UploadHelper.GetCopyAuthorization = GetUpgradeCopyAuthorization;
- //Initial clientTags
- ClientTagsInitializer.Initialize();
- }
- /// <summary>
- /// Connect Server Async
- /// </summary>
- /// <returns></returns>
- public async Task<LoginStatus> ConnectServerAsync()
- {
- if (_leaf == null || !_leaf.Online)
- {
- await Task.Run(() => { RefreshLeaf(ServerIP, ServerPort); });
- }
- using (var clientLoginRequest2 = MessagePool.GetMessage<ClientLoginRequest2>())
- {
- 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;
- }
- /// <summary>
- /// DisConnect Server Async
- /// </summary>
- /// <returns></returns>
- public async Task<LogoffStatus> DisconnectServerAsync()
- {
- if (_leaf == null || !_leaf.Online)
- {
- return LogoffStatus.Success;
- }
- try
- {
- var clientLogoffRequest = MessagePool.GetMessage<ClientLogoffRequest>();
- 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.");
- }
- }
- /// <summary>
- /// Upload Package Async
- /// </summary>
- /// <param name="filePath">Pakage Path</param>
- /// <param name="version">Package Version</param>
- /// <param name="fileName">Package Name</param>
- /// <param name="description">Description</param>
- /// <returns></returns>
- public async Task<GeneralPackInfo> 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>())
- {
- 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);
- }
- /// <summary>
- /// Get Latest Package Info Async
- /// </summary>
- /// <returns></returns>
- public async Task<GeneralPackInfo> GetLatestPackageAsync(string uniquedCode)
- {
- using (var queryLatestPackageRequest = MessagePool.GetMessage<QueryLatestPackageRequest>())
- {
- 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<GetUpgradeStorageInfoRequest>())
- {
- 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<KeyValuePair<string, string>> headers)
- {
- var authorization = string.Empty;
- var getUpgradeCopyAuthorizationRequest = new GetUpgradeCopyAuthorizationRequest();
- getUpgradeCopyAuthorizationRequest.FileName = fileName;
- var list = new List<KeyValuePairHeaderItem>();
- 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;
- }
- }
- }
|