vCloudService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Threading.Tasks;
  5. using Vinno.IUS.Common.Network;
  6. using Vinno.IUS.Common.Network.Leaf;
  7. using Vinno.IUS.Common.Network.Tcp;
  8. using Vinno.IUS.Common.Network.Transfer;
  9. using Vinno.vCloud.Common.Storage;
  10. using Vinno.vCloud.Common.Storage.ObjectStorageInfo;
  11. using Vinno.vCloud.Common.Storage.Upload;
  12. using Vinno.vCloud.Protocol.Infrastructures;
  13. using Vinno.vCloud.Protocol.Initializers;
  14. using Vinno.vCloud.Protocol.Messages.Client.Login;
  15. using Vinno.vCloud.Protocol.Messages.Client.Storage;
  16. using Vinno.vCloud.Protocol.Messages.Common;
  17. using Vinno.vCloud.Protocol.Messages.Login;
  18. using Vinno.vCloud.Protocol.Messages.Upgrade;
  19. namespace UpgradePackageUploadTool.Services
  20. {
  21. public class vCloudService
  22. {
  23. private StorageInfo _storageInfo;
  24. private object _storageInfoLocker = new object();
  25. private ClientLeaf _leaf;
  26. private string _accountId;
  27. /// <summary>
  28. /// The event of Upload Progress Changing.
  29. /// </summary>
  30. public event EventHandler<int> UploadProgressChanged;
  31. /// <summary>
  32. /// 服务器IP
  33. /// </summary>
  34. public string ServerIP { get; set; }
  35. /// <summary>
  36. /// 服务器端口
  37. /// </summary>
  38. public int ServerPort { get; set; }
  39. /// <summary>
  40. /// 用户名
  41. /// </summary>
  42. public string Account { get; set; }
  43. /// <summary>
  44. /// 密码
  45. /// </summary>
  46. public string Password { get; set; }
  47. /// <summary>
  48. /// 构造函数,初始化
  49. /// </summary>
  50. public vCloudService()
  51. {
  52. UploadHelper.GetAuthorization = GetUpgradeAuthorization;
  53. UploadHelper.GetCopyAuthorization = GetUpgradeCopyAuthorization;
  54. //Initial clientTags
  55. ClientTagsInitializer.Initialize();
  56. }
  57. /// <summary>
  58. /// Connect Server Async
  59. /// </summary>
  60. /// <returns></returns>
  61. public async Task<LoginStatus> ConnectServerAsync()
  62. {
  63. if (_leaf == null || !_leaf.Online)
  64. {
  65. await Task.Run(() => { RefreshLeaf(ServerIP, ServerPort); });
  66. }
  67. using (var clientLoginRequest2 = MessagePool.GetMessage<ClientLoginRequest2>())
  68. {
  69. clientLoginRequest2.Name = Account;
  70. clientLoginRequest2.Password = Password;
  71. clientLoginRequest2.Source = LoginSource.PersonalComputer;
  72. clientLoginRequest2.ClientVersion = "Upgrade Package Upload Tool";
  73. clientLoginRequest2.Force = true;
  74. try
  75. {
  76. var result = await _leaf.SendAsync(clientLoginRequest2);
  77. var loginResult = LoginResult2.Convert(result);
  78. if (loginResult != null)
  79. {
  80. _accountId = loginResult.AccountId;
  81. return loginResult.Status;
  82. }
  83. }
  84. catch (ConnectionTimeoutException)
  85. {
  86. return LoginStatus.ConnectionTmeout;
  87. }
  88. catch (NotConnectedException)
  89. {
  90. return LoginStatus.ConnectServerFailed;
  91. }
  92. catch (Exception ex)
  93. {
  94. return LoginStatus.Unknown;
  95. }
  96. }
  97. return LoginStatus.Unknown;
  98. }
  99. /// <summary>
  100. /// DisConnect Server Async
  101. /// </summary>
  102. /// <returns></returns>
  103. public async Task<LogoffStatus> DisconnectServerAsync()
  104. {
  105. if (_leaf == null || !_leaf.Online)
  106. {
  107. return LogoffStatus.Success;
  108. }
  109. try
  110. {
  111. var clientLogoffRequest = MessagePool.GetMessage<ClientLogoffRequest>();
  112. clientLogoffRequest.Name = Account;
  113. clientLogoffRequest.Password = Password;
  114. clientLogoffRequest.Source = LoginSource.PersonalComputer;
  115. var result = await _leaf.SendAsync(clientLogoffRequest);
  116. var logoffResult = LogoffResult.Convert(result);
  117. if (logoffResult != null)
  118. {
  119. return logoffResult.Status;
  120. }
  121. }
  122. catch
  123. {
  124. return LogoffStatus.Unknown;
  125. }
  126. return LogoffStatus.Unknown;
  127. }
  128. private void LeafOnlineCheck()
  129. {
  130. if (!_leaf.Online)
  131. {
  132. RefreshLeaf(ServerIP, ServerPort);
  133. }
  134. }
  135. private void RefreshLeaf(string serverIP, int serverPort)
  136. {
  137. _leaf?.Close();
  138. if (string.IsNullOrEmpty(serverIP) || serverPort == 0)
  139. {
  140. throw new Exception("Server IP or Server Port is wrong!");
  141. }
  142. var tcpCreator = new TcpCreator(serverIP, serverPort);
  143. if (!tcpCreator.HasValidIpAddress)
  144. {
  145. throw new Exception($"Tcp Creator dosen't have valid Ip Address");
  146. }
  147. _leaf = new ClientLeaf(new LeafIdContext(), LeafMode.Dual, tcpCreator);
  148. if (!_leaf.Online)
  149. {
  150. _leaf.Close();
  151. throw new Exception("Connect Server Failed.");
  152. }
  153. }
  154. /// <summary>
  155. /// Upload Package Async
  156. /// </summary>
  157. /// <param name="filePath">Pakage Path</param>
  158. /// <param name="version">Package Version</param>
  159. /// <param name="fileName">Package Name</param>
  160. /// <param name="description">Description</param>
  161. /// <returns></returns>
  162. public async Task<GeneralPackInfo> UploadDataAsync(string filePath, string version, string fileName, string description, string uniqueCode)
  163. {
  164. return await Task.Run(() =>
  165. {
  166. LeafOnlineCheck();
  167. var storageInfo = GetUpgradeStorageInfo();
  168. var fileData = File.ReadAllBytes(filePath);
  169. var fileToken = UploadHelper.UploadFile(storageInfo, filePath, fileName, _accountId, uploadProgress =>
  170. {
  171. var progress = (int)(uploadProgress * 100 * 0.95);
  172. OnUploadProgressChanged(progress);
  173. }, null, false, true);
  174. if (string.IsNullOrEmpty(fileToken))
  175. {
  176. throw new Exception("Upload Fail!File Token is null");
  177. }
  178. if (storageInfo.StorageType == StorageType.Default && !fileToken.Contains(FileTokenInfo.TokenSplitor[0]))
  179. {
  180. fileToken = $"{(int)storageInfo.StorageType}{FileTokenInfo.TokenSplitor[0]}{fileToken}";
  181. }
  182. using (var savePackageRequest = MessagePool.GetMessage<SavePackageRequest>())
  183. {
  184. savePackageRequest.CreateUserId = _accountId;
  185. savePackageRequest.Description = description;
  186. savePackageRequest.Version = version;
  187. savePackageRequest.FileSize = (int)new FileInfo(filePath).Length;
  188. savePackageRequest.FileToken = fileToken;
  189. savePackageRequest.UniquedCode = uniqueCode;
  190. savePackageRequest.FileName = fileName;
  191. var message = _leaf.Send(savePackageRequest);
  192. if (message == null)
  193. {
  194. throw new Exception("Create Package Request Fail.");
  195. }
  196. var ok = ResultMessage.Convert(message);
  197. if (ok == null || ok.ResultCode != OKResult.Code)
  198. {
  199. throw new Exception("Create Package Request Fail.");
  200. }
  201. OnUploadProgressChanged(100);
  202. return new GeneralPackInfo(Account, description, fileName, fileToken, savePackageRequest.FileSize, PackageType.Other, DateTime.UtcNow, version, uniqueCode);
  203. }
  204. });
  205. }
  206. private void OnUploadProgressChanged(int progress)
  207. {
  208. UploadProgressChanged?.Invoke(this, progress);
  209. }
  210. /// <summary>
  211. /// Get Latest Package Info Async
  212. /// </summary>
  213. /// <returns></returns>
  214. public async Task<GeneralPackInfo> GetLatestPackageAsync(string uniquedCode)
  215. {
  216. using (var queryLatestPackageRequest = MessagePool.GetMessage<QueryLatestPackageRequest>())
  217. {
  218. queryLatestPackageRequest.UniquedCode = uniquedCode;
  219. var message = await _leaf.SendAsync(queryLatestPackageRequest);
  220. if (message == null)
  221. {
  222. return null;
  223. }
  224. var result = GetPackageResult.Convert(message);
  225. if (result != null)
  226. {
  227. return new GeneralPackInfo(result.CreateUserName, result.Description, result.FileName, result.FileToken, result.FileSize, result.PackageType, result.UpdateTime, result.Version, result.UniquedCode);
  228. }
  229. }
  230. return null;
  231. }
  232. private StorageInfo GetUpgradeStorageInfo()
  233. {
  234. lock (_storageInfoLocker)
  235. {
  236. using (var request = MessagePool.GetMessage<GetUpgradeStorageInfoRequest>())
  237. {
  238. var result = _leaf.Send(request);
  239. var getUpgradeInfoResult = GetUpgradeStorageInfoResult.Convert(result);
  240. if (getUpgradeInfoResult != null)
  241. {
  242. var url = getUpgradeInfoResult.StorageServerUrl;
  243. var storageType = getUpgradeInfoResult.StorageType;
  244. var config = getUpgradeInfoResult.Config;
  245. _storageInfo = new StorageInfo()
  246. {
  247. Url = url,
  248. StorageType = storageType,
  249. Config = config
  250. };
  251. NodeMapping.NodeMappingInilization(_storageInfo.StorageNodeItems);
  252. }
  253. }
  254. return _storageInfo;
  255. }
  256. }
  257. private string GetUpgradeAuthorization(string fileName)
  258. {
  259. var authorization = string.Empty;
  260. var getUpgradeAuthorizationRequest = new GetUpgradeAuthorizationRequest();
  261. getUpgradeAuthorizationRequest.FileName = fileName;
  262. var upgradeResult = _leaf.Send(getUpgradeAuthorizationRequest);
  263. var getUpgradeAuthorizationResult = GetUpgradeAuthorizationResult.Convert(upgradeResult);
  264. if (getUpgradeAuthorizationResult != null)
  265. {
  266. authorization = getUpgradeAuthorizationResult.Authorization;
  267. }
  268. return authorization;
  269. }
  270. private string GetUpgradeCopyAuthorization(string fileName, List<KeyValuePair<string, string>> headers)
  271. {
  272. var authorization = string.Empty;
  273. var getUpgradeCopyAuthorizationRequest = new GetUpgradeCopyAuthorizationRequest();
  274. getUpgradeCopyAuthorizationRequest.FileName = fileName;
  275. var list = new List<KeyValuePairHeaderItem>();
  276. if (headers?.Count > 0)
  277. {
  278. foreach (var item in headers)
  279. {
  280. list.Add(new KeyValuePairHeaderItem()
  281. {
  282. HeaderKey = item.Key,
  283. HeaderValue = item.Value
  284. });
  285. }
  286. }
  287. getUpgradeCopyAuthorizationRequest.CopyHeaders = list;
  288. var upgradeResult = _leaf.Send(getUpgradeCopyAuthorizationRequest);
  289. var getUpgradeAuthorizationResult = GetUpgradeAuthorizationResult.Convert(upgradeResult);
  290. if (getUpgradeAuthorizationResult != null)
  291. {
  292. authorization = getUpgradeAuthorizationResult.Authorization;
  293. }
  294. return authorization;
  295. }
  296. }
  297. }