vCloudScanDataV2.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. using SkiaSharp;
  2. using System;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using Vinno.IUS.Common.Log;
  7. using Vinno.vCloud.Common.FIS.Helper;
  8. using Vinno.vCloud.Common.Vid2;
  9. using Vinno.vCloud.FIS.CrossPlatform.Common.Helper;
  10. using Vinno.vCloud.Protocol.Infrastructures;
  11. using WingInterfaceLibrary.DTO.Comment;
  12. using WingInterfaceLibrary.DTO.Measure;
  13. using WingInterfaceLibrary.DTO.Record;
  14. using WingInterfaceLibrary.Enum;
  15. using WingInterfaceLibrary.Interface;
  16. using WingInterfaceLibrary.Request.Examine;
  17. using WingInterfaceLibrary.Request.Storage;
  18. using WingInterfaceLibrary.Result.Examine;
  19. namespace Vinno.vCloud.Common.FIS.Remedicals
  20. {
  21. internal class vCloudScanDataV2 : IvCloudScanData, IDisposable
  22. {
  23. private UploadStatus _status;
  24. private readonly IRemedicalService _remedicalService;
  25. private readonly IStorageService _storageService;
  26. private readonly string _token;
  27. private bool _disposed;
  28. private const string BreastImageLocation = "BreastImageLocation";
  29. private const string LiverImageLocation = "LiverImageLocation";
  30. private const string ThyroidImageLocation = "ThyroidImageLocation";
  31. /// <inheritdoc />
  32. /// <summary>
  33. /// Gets the id of this scan data.
  34. /// </summary>
  35. public string Id { get; }
  36. /// <inheritdoc />
  37. /// <summary>
  38. /// Gets the examId of this scan data.
  39. /// </summary>
  40. public string ExamId { get; }
  41. /// <inheritdoc />
  42. /// <summary>
  43. /// Gets or sets the ExamRecordId for this scan data.
  44. /// </summary>
  45. public string ExamRecordId { get; set; }
  46. /// <inheritdoc />
  47. /// <summary>
  48. /// Gets the workorder Id.
  49. /// </summary>
  50. public string WorkOrderId { get; }
  51. /// <summary>
  52. /// Raised when the status changed.
  53. /// </summary>
  54. public event EventHandler StatusChanged;
  55. /// <inheritdoc />
  56. /// <summary>
  57. /// Gets the status of this Scan data.
  58. /// </summary>
  59. public UploadStatus Status
  60. {
  61. get => _status;
  62. internal set
  63. {
  64. if (_status != value)
  65. {
  66. var old = _status;
  67. _status = value;
  68. if (_status == UploadStatus.Uploaded || _status == UploadStatus.Deleted)
  69. {
  70. Delete(old);
  71. }
  72. else
  73. {
  74. Move(old, _status);
  75. }
  76. OnStatusChanged();
  77. }
  78. }
  79. }
  80. /// <inheritdoc />
  81. /// <summary>
  82. /// Gets the vid file path.
  83. /// </summary>
  84. public string VidFilePath { get; private set; }
  85. /// <summary>
  86. /// Gets the sd file path.
  87. /// </summary>
  88. public string ScanDataFilePath { get; private set; }
  89. /// <inheritdoc />
  90. /// <summary>
  91. /// Gets the description of this scan data.
  92. /// </summary>
  93. public string Description { get; }
  94. /// <inheritdoc />
  95. /// <summary>
  96. /// Gets the application of this scan data.
  97. /// </summary>
  98. public string Application { get; }
  99. /// <summary>
  100. /// Gets the Application Category of this scan data
  101. /// </summary>
  102. public string ApplicationCategory { get; }
  103. /// <inheritdoc />
  104. /// <summary>
  105. /// Gets the data type of this scan data.
  106. /// </summary>
  107. public VidType DataType { get; }
  108. /// <inheritdoc />
  109. /// <summary>
  110. /// Gets the patient info for this scan data.
  111. /// </summary>
  112. public PatientScanInfo PatientInfo { get; }
  113. /// <summary>
  114. /// Get the Measure Results
  115. /// </summary>
  116. public MeasuredResultsDTO MeasuredResults { get; }
  117. /// <summary>
  118. /// Get the comment Results
  119. /// </summary>
  120. public ScanImageDTO CommentResults { get; }
  121. public vCloudScanDataV2(IvCloudExamRecord record, string id, string vidFilePath,
  122. VidType dataType, string description, PatientScanInfo patientInfo, UploadStatus status, IRemedicalService remedicalService, IStorageService storageService, string token, MeasuredResultsDTO measuredResults = null, ScanImageDTO commentResults = null)
  123. {
  124. _status = status;
  125. _token = token;
  126. _remedicalService = remedicalService;
  127. _storageService = storageService;
  128. ExamRecordId = record.Id;
  129. ExamId = record.ExamId;
  130. WorkOrderId = record.WorkOrderId;
  131. Id = id;
  132. DataType = dataType;
  133. Description = description;
  134. PatientInfo = patientInfo;
  135. MeasuredResults = measuredResults;
  136. CommentResults = commentResults;
  137. //Generate files.
  138. VidFilePath = GetVidFilePath(_status);
  139. if (string.Compare(VidFilePath, vidFilePath, StringComparison.OrdinalIgnoreCase) != 0)
  140. {
  141. File.Move(vidFilePath, VidFilePath);
  142. }
  143. if (description == "FromSonopost")
  144. {
  145. Application = string.Empty;
  146. ApplicationCategory = description;
  147. }
  148. else
  149. {
  150. using (var vinnoImage = new VinnoImageData(VidFilePath, OperationMode.Open))
  151. {
  152. ApplicationCategory = vinnoImage.Probe?.Application?.ApplicationCategoryName;
  153. Application = vinnoImage.Probe?.Application?.ApplicationName;
  154. }
  155. }
  156. //Save self.
  157. Save();
  158. }
  159. ~vCloudScanDataV2()
  160. {
  161. DoDispose();
  162. }
  163. private void OnStatusChanged()
  164. {
  165. StatusChanged?.Invoke(this, EventArgs.Empty);
  166. }
  167. /// <summary>
  168. /// Delete this scanData and its files.
  169. /// </summary>
  170. public void Delete()
  171. {
  172. Status = UploadStatus.Deleted;
  173. }
  174. /// <summary>
  175. /// Force update the scan data's status.
  176. /// </summary>
  177. /// <param name="status">The new status</param>
  178. public void ForceUpdateStaus(UploadStatus status)
  179. {
  180. Status = status;
  181. }
  182. /// <summary>
  183. /// Force update and save the scan data.
  184. /// </summary>
  185. public void Update()
  186. {
  187. Save();
  188. }
  189. /// <summary>
  190. /// Get saved scan data file path
  191. /// </summary>
  192. /// <param name="status"></param>
  193. /// <returns></returns>
  194. private string GetScanDataFilePath(UploadStatus status)
  195. {
  196. if (status == UploadStatus.Deleted)
  197. {
  198. throw new InvalidOperationException("File already deleted.");
  199. }
  200. var subFolder = string.Empty;
  201. if (status == UploadStatus.Idle || status == UploadStatus.Waiting || status == UploadStatus.Uploading)
  202. {
  203. subFolder = "Upload";
  204. }
  205. if (status == UploadStatus.Fail || status == UploadStatus.FailBecauseExamIsFinished)
  206. {
  207. subFolder = "Failed";
  208. }
  209. var folder = GetWorkingFolder(subFolder);
  210. var fileName = $"{Id}.sd";
  211. return Path.Combine(folder, fileName);
  212. }
  213. private string GetWorkingFolder(string subFolder)
  214. {
  215. var folder = Path.Combine(vCloudTerminalV2.WorkingFolder, "RemedicalV2", subFolder);
  216. DirectoryHelper.CreateDirectory(folder);
  217. return folder;
  218. }
  219. /// <summary>
  220. /// Get the vid file path.
  221. /// </summary>
  222. /// <param name="status"></param>
  223. /// <returns></returns>
  224. private string GetVidFilePath(UploadStatus status)
  225. {
  226. if (status == UploadStatus.Deleted)
  227. {
  228. throw new InvalidOperationException("File already deleted.");
  229. }
  230. var subFolder = string.Empty;
  231. if (status == UploadStatus.Idle || status == UploadStatus.Waiting || status == UploadStatus.Uploading)
  232. {
  233. subFolder = "Upload";
  234. }
  235. if (status == UploadStatus.Fail || status == UploadStatus.FailBecauseExamIsFinished)
  236. {
  237. subFolder = "Failed";
  238. }
  239. var folder = GetWorkingFolder(subFolder);
  240. var fileName = $"{Id}.vid";
  241. return Path.Combine(folder, fileName);
  242. }
  243. /// <summary>
  244. /// Delete the files
  245. /// </summary>
  246. /// <param name="status"></param>
  247. private void Delete(UploadStatus status)
  248. {
  249. var scanDataFilePath = GetScanDataFilePath(status);
  250. var vidFilePath = GetVidFilePath(status);
  251. FileHelper.DeleteFile(scanDataFilePath);
  252. FileHelper.DeleteFile(vidFilePath);
  253. }
  254. /// <summary>
  255. /// Save scan data and vid file to the disk by current status.
  256. /// </summary>
  257. private void Save()
  258. {
  259. ScanDataFilePath = GetScanDataFilePath(Status);
  260. this.Serialize(ScanDataFilePath);
  261. }
  262. /// <summary>
  263. /// Move scan data from one to another
  264. /// </summary>
  265. /// <param name="source"></param>
  266. /// <param name="dest"></param>
  267. private void Move(UploadStatus source, UploadStatus dest)
  268. {
  269. var sourceScanDataFilePath = GetScanDataFilePath(source);
  270. var sourceVidFilePath = GetVidFilePath(source);
  271. var destScanDataFilePath = GetScanDataFilePath(dest);
  272. var destVidFilePath = GetVidFilePath(dest);
  273. if (File.Exists(sourceScanDataFilePath) && !File.Exists(destScanDataFilePath))
  274. {
  275. File.Move(sourceScanDataFilePath, destScanDataFilePath);
  276. ScanDataFilePath = destScanDataFilePath;
  277. }
  278. if (File.Exists(sourceVidFilePath) && !File.Exists(destVidFilePath))
  279. {
  280. File.Move(sourceVidFilePath, destVidFilePath);
  281. VidFilePath = destVidFilePath;
  282. }
  283. }
  284. /// <summary>
  285. /// Upload the data to the vCloud server.
  286. /// </summary>
  287. public void Upload(CancellationTokenSource cancellationTokenSource)
  288. {
  289. string previewFileToken = string.Empty;
  290. string coverImageToken = string.Empty;
  291. ImageLocationDTO imageLocationDTO = null;
  292. using (var vinnoImage = new VinnoImageData(VidFilePath, OperationMode.Open))
  293. {
  294. if (vinnoImage.ImageCount <= 0)
  295. {
  296. throw new FileNotFoundException("The VinnoImageData Image Count <=0");
  297. }
  298. }
  299. if (vCloudServerConfig.Instance.IsUploadThumbnail)
  300. {
  301. var storageUrl = UploadFirstImage(cancellationTokenSource);
  302. if (string.IsNullOrWhiteSpace(storageUrl))
  303. {
  304. throw new InvalidOperationException($"Get token failed when Uploading first image");
  305. }
  306. coverImageToken = storageUrl;
  307. storageUrl = UploadPreviewImage(cancellationTokenSource);
  308. if (string.IsNullOrWhiteSpace(storageUrl))
  309. {
  310. throw new InvalidOperationException($"Get token failed when Uploading preview image");
  311. }
  312. previewFileToken = storageUrl;
  313. imageLocationDTO = GetImageLocation(cancellationTokenSource);
  314. }
  315. var url = UploadVidFile(cancellationTokenSource);
  316. if (string.IsNullOrWhiteSpace(url))
  317. {
  318. throw new InvalidOperationException("Get token failed when Uploading VID file");
  319. }
  320. var fileType = RemedicalFileDataTypeEnum.VinnoVidSingle;
  321. switch (DataType)
  322. {
  323. case VidType.VinnoVidMovie:
  324. fileType = RemedicalFileDataTypeEnum.VinnoVidMovie;
  325. break;
  326. case VidType.ThirdVidSingle:
  327. fileType = RemedicalFileDataTypeEnum.ThirdVidSingle;
  328. break;
  329. case VidType.ThirdVidMovie:
  330. fileType = RemedicalFileDataTypeEnum.ThirdVidMovie;
  331. break;
  332. }
  333. var fileInfo = new FileInfo(VidFilePath);
  334. var fileSize = fileInfo.Length;
  335. var uploadExamDataRequest = new UploadExamDataRequest
  336. {
  337. Token = _token,
  338. ExamCode = ExamRecordId,
  339. FileToken = url,
  340. FileSize = fileSize,
  341. Application = Application,
  342. ApplicationCategory = ApplicationCategory,
  343. FileDataType = fileType,
  344. PreviewFileToken = previewFileToken,
  345. CoverImageToken = coverImageToken,
  346. MeasuredResult = MeasuredResults,
  347. CommentResult = CommentResults,
  348. ImageLocation = imageLocationDTO
  349. };
  350. if (cancellationTokenSource.IsCancellationRequested)
  351. {
  352. throw new OperationCanceledException("Cancelled");
  353. }
  354. var result = JsonRpcHelper.UploadExamData(_remedicalService, uploadExamDataRequest);
  355. if (result == null)
  356. {
  357. throw new InvalidDataException($"JsonRPCHelper UploadExamData Result is null");
  358. }
  359. else if (result.IsSuccess)
  360. {
  361. Status = UploadStatus.Uploaded;
  362. return;
  363. }
  364. else if (!result.IsSuccess)
  365. {
  366. if (result.ErrorCode == 4002)
  367. {
  368. Status = UploadStatus.FailBecauseExamIsFinished;
  369. Save();
  370. return;
  371. }
  372. else if (result.ErrorCode == 4015)
  373. {
  374. if (CreateExamRecord())
  375. {
  376. result = JsonRpcHelper.UploadExamData(_remedicalService, uploadExamDataRequest);
  377. if (result == null)
  378. {
  379. throw new InvalidDataException($"JsonRPCHelper UploadExamData Result is null");
  380. }
  381. else if (result.IsSuccess)
  382. {
  383. Status = UploadStatus.Uploaded;
  384. return;
  385. }
  386. else
  387. {
  388. throw new InvalidDataException($"JsonRPCHelper UploadExamData Fail,Error Code is {result.ErrorCode}");
  389. }
  390. }
  391. else
  392. {
  393. throw new InvalidDataException($"JsonRPCHelper UploadExamData Fail:ReCreateExamRecord Result is false");
  394. }
  395. }
  396. else
  397. {
  398. throw new InvalidDataException($"JsonRPCHelper UploadExamData Fail,Error Code is {result.ErrorCode}");
  399. }
  400. }
  401. }
  402. private ImageLocationDTO GetImageLocation(CancellationTokenSource cancellationTokenSource)
  403. {
  404. if (cancellationTokenSource.IsCancellationRequested)
  405. {
  406. throw new OperationCanceledException("Cancelled");
  407. }
  408. using (var vinnoImage = new VinnoImageData(VidFilePath, OperationMode.Open))
  409. {
  410. var imageLocationExtenedData = VidExtendedData.FromBytes(vinnoImage.ExtendedData);
  411. if (imageLocationExtenedData != null && imageLocationExtenedData.Data != null)
  412. {
  413. var positionTag = imageLocationExtenedData.Data.Keys.FirstOrDefault(t => t.Element == "Position" && t.Group == BreastImageLocation);
  414. var quadrantTag = imageLocationExtenedData.Data.Keys.FirstOrDefault(t => t.Element == "Quadrant" && t.Group == BreastImageLocation);
  415. if (positionTag != null && quadrantTag != null)
  416. {
  417. if (Enum.TryParse<Position>(imageLocationExtenedData.Data[positionTag].GetValue()?.ToString(), out var positionEnum)
  418. && Enum.TryParse<QuadrantEnum>(imageLocationExtenedData.Data[quadrantTag].GetValue()?.ToString(), out var quadrantEnum))
  419. {
  420. return new ImageLocationDTO
  421. {
  422. Position = positionEnum.ToString(),
  423. Quadrant = quadrantEnum.ToString(),
  424. Group = positionTag.Group,
  425. };
  426. }
  427. }
  428. positionTag = imageLocationExtenedData.Data.Keys.FirstOrDefault(t => t.Element == "Position" && t.Group == LiverImageLocation);
  429. if (positionTag != null)
  430. {
  431. if (Enum.TryParse<LiverPosition>(imageLocationExtenedData.Data[positionTag].GetValue()?.ToString(), out var positionEnum))
  432. {
  433. return new ImageLocationDTO
  434. {
  435. Position = positionEnum.ToString(),
  436. Group = positionTag.Group,
  437. };
  438. }
  439. }
  440. positionTag = imageLocationExtenedData.Data.Keys.FirstOrDefault(t => t.Element == FISTissueCategory.Position && !string.IsNullOrWhiteSpace(t.Group));
  441. var groupName = positionTag?.Group;
  442. if (positionTag != null && !imageLocationExtenedData.Data.Keys.Any(x => x.Group == groupName && x.Element != FISTissueCategory.Position))
  443. {
  444. return new ImageLocationDTO
  445. {
  446. Group = groupName,
  447. Position = imageLocationExtenedData.Data[positionTag].GetValue()?.ToString(),
  448. };
  449. }
  450. }
  451. }
  452. return null;
  453. }
  454. /// <inheritdoc />
  455. /// <summary>
  456. /// Create an exam record from vCloud.
  457. /// </summary>
  458. /// <param name="examId">The local excam id.</param>
  459. /// <param name="workOrderId">The workerId</param>
  460. /// <param name="patientInfo">The patient basic info for creating the exam record.</param>
  461. /// <returns><see cref="T:Vinno.vCloud.Terminal.Remedicals.IvCloudExamRecord" /></returns>
  462. public bool CreateExamRecord()
  463. {
  464. var createExaminfoRequest = new CreateExaminfoRequest
  465. {
  466. Token = _token,
  467. PatientType = vCloudServerConfig.Instance.PatientType.ToString(),
  468. ExamRecordCode = ExamRecordId,
  469. PatientInfo = DTOConverter.RenderPatientInfo(PatientInfo),
  470. PatientScanInfoList = DTOConverter.RenderPatientScanInfo(PatientInfo),
  471. };
  472. CreateExaminfoResult result = JsonRpcHelper.CreateExamInfo(_remedicalService, createExaminfoRequest);
  473. if (result == null || result.ExamCode != ExamRecordId)
  474. {
  475. return false;
  476. }
  477. else
  478. {
  479. return true;
  480. }
  481. }
  482. private string UploadFirstImage(CancellationTokenSource cancellationTokenSource)
  483. {
  484. try
  485. {
  486. if (cancellationTokenSource.IsCancellationRequested)
  487. {
  488. throw new OperationCanceledException("Cancelled");
  489. }
  490. var firstImageName = "firstImage_" + Path.GetFileNameWithoutExtension(VidFilePath) + ".jpg";
  491. using (var vinnoImage = new VinnoImageData(VidFilePath, OperationMode.Open))
  492. {
  493. var image = vinnoImage.GetImage(0);
  494. var fileServiceRequest = new FileServiceRequest
  495. {
  496. FileName = firstImageName,
  497. IsRechristen = true,
  498. Token = _token,
  499. };
  500. var authorizationInfo = JsonRpcHelper.GetAuthorization(_storageService, fileServiceRequest);
  501. if (authorizationInfo == null)
  502. {
  503. throw new Exception("GetAuthorization Error,AuthorizationInfo is null ");
  504. }
  505. var uploadResult = UploadFileHelper.UploadFile(authorizationInfo.StorageUrl, image?.ImageData, authorizationInfo.ContentType, authorizationInfo.Authorization, null, cancellationTokenSource);
  506. if (cancellationTokenSource.IsCancellationRequested)
  507. {
  508. throw new OperationCanceledException("Cancelled");
  509. }
  510. if (uploadResult)
  511. {
  512. return authorizationInfo.StorageUrl;
  513. }
  514. else
  515. {
  516. return string.Empty;
  517. }
  518. }
  519. }
  520. catch (Exception ex)
  521. {
  522. Logger.WriteLineError($"Upload First Image Error:{ex}");
  523. return string.Empty;
  524. }
  525. }
  526. private string UploadPreviewImage(CancellationTokenSource cancellationTokenSource)
  527. {
  528. try
  529. {
  530. if (cancellationTokenSource.IsCancellationRequested)
  531. {
  532. throw new OperationCanceledException("Cancelled");
  533. }
  534. var previewImageName = "preview_" + Path.GetFileNameWithoutExtension(VidFilePath) + ".jpg";
  535. using (var vinnoImage = new VinnoImageData(VidFilePath, OperationMode.Open))
  536. {
  537. var image = vinnoImage.GetImage(0);
  538. var fileServiceRequest = new FileServiceRequest
  539. {
  540. FileName = previewImageName,
  541. IsRechristen = true,
  542. Token = _token,
  543. };
  544. var authorizationInfo = JsonRpcHelper.GetAuthorization(_storageService, fileServiceRequest);
  545. if (authorizationInfo == null)
  546. {
  547. throw new Exception("GetAuthorization Error,AuthorizationInfo is null ");
  548. }
  549. var compressedImage = Compress(image);
  550. var uploadResult = UploadFileHelper.UploadFile(authorizationInfo.StorageUrl, compressedImage?.ImageData, authorizationInfo.ContentType, authorizationInfo.Authorization, null, cancellationTokenSource);
  551. if (cancellationTokenSource.IsCancellationRequested)
  552. {
  553. throw new OperationCanceledException("Cancelled");
  554. }
  555. if (uploadResult)
  556. {
  557. return authorizationInfo.StorageUrl;
  558. }
  559. else
  560. {
  561. return string.Empty;
  562. }
  563. }
  564. }
  565. catch (Exception ex)
  566. {
  567. Logger.WriteLineError($"Upload Preview Image Error:{ex}");
  568. return string.Empty;
  569. }
  570. }
  571. private string UploadVidFile(CancellationTokenSource cancellationTokenSource)
  572. {
  573. try
  574. {
  575. if (cancellationTokenSource.IsCancellationRequested)
  576. {
  577. throw new OperationCanceledException("Cancelled");
  578. }
  579. var fileName = Path.GetFileName(VidFilePath);
  580. var fileServiceRequest = new FileServiceRequest
  581. {
  582. FileName = fileName,
  583. IsRechristen = true,
  584. Token = _token,
  585. };
  586. var authorizationInfo = JsonRpcHelper.GetAuthorization(_storageService, fileServiceRequest);
  587. if (authorizationInfo == null)
  588. {
  589. throw new Exception("GetAuthorization Error,AuthorizationInfo is null ");
  590. }
  591. var uploadResult = UploadFileHelper.UploadFile(authorizationInfo.StorageUrl, VidFilePath, authorizationInfo.ContentType, authorizationInfo.Authorization, null, cancellationTokenSource);
  592. if (cancellationTokenSource.IsCancellationRequested)
  593. {
  594. throw new OperationCanceledException("Cancelled");
  595. }
  596. if (uploadResult)
  597. {
  598. return authorizationInfo.StorageUrl;
  599. }
  600. else
  601. {
  602. return string.Empty;
  603. }
  604. }
  605. catch (Exception ex)
  606. {
  607. Logger.WriteLineError($"Upload Vid File Error:{ex}");
  608. return string.Empty;
  609. }
  610. }
  611. private void DoDispose()
  612. {
  613. try
  614. {
  615. if (!_disposed)
  616. {
  617. //if not uploaded just save it to disk.
  618. if (Status != UploadStatus.Uploaded && Status != UploadStatus.Deleted)
  619. {
  620. Save();
  621. }
  622. }
  623. }
  624. catch (Exception ex)
  625. {
  626. Logger.WriteLineError($"vCloudScanData: dispose upload data error:{ex}");
  627. }
  628. finally
  629. {
  630. _disposed = true;
  631. }
  632. }
  633. /// <summary>
  634. /// Compress a VinnoImage to a 100p image with {compressLevel} quality
  635. /// </summary>
  636. /// <param name="vinnoImage"></param>
  637. /// <param name="compressLevel"></param>
  638. /// <returns></returns>
  639. /// <exception cref="Exception"></exception>
  640. private VinnoImage Compress(VinnoImage vinnoImage, long compressLevel = 80)
  641. {
  642. byte[] compressedData = vinnoImage.ImageData;
  643. using (var ms = new MemoryStream(compressedData))
  644. {
  645. using (var image = SKBitmap.Decode(ms))
  646. {
  647. var ratio = (double)100 / image.Height;
  648. if (ratio < 1)
  649. {
  650. var width = (int)(image.Width * ratio);
  651. var height = 100;
  652. SKBitmap tempImage = image;
  653. if (image.Width != width || image.Height != height)
  654. {
  655. tempImage = image.Resize(new SKImageInfo(width, height), SKFilterQuality.High);
  656. }
  657. try
  658. {
  659. using (var map = new SKPixmap(new SKImageInfo(tempImage.Width, tempImage.Height, tempImage.ColorType), tempImage.GetPixels()))
  660. {
  661. using (var stream = new SKDynamicMemoryWStream())
  662. {
  663. SKPixmap.Encode(stream, map, SKEncodedImageFormat.Jpeg, (int)compressLevel);
  664. compressedData = stream.CopyToData().ToArray();
  665. }
  666. }
  667. }
  668. catch (Exception exception)
  669. {
  670. throw new Exception($"Compress error:{exception}");
  671. }
  672. finally
  673. {
  674. tempImage.Dispose();
  675. }
  676. var compressImage = new VinnoImage(vinnoImage.Index, width, height, compressedData);
  677. return compressImage;
  678. }
  679. }
  680. }
  681. return vinnoImage;
  682. }
  683. public void Dispose()
  684. {
  685. DoDispose();
  686. GC.SuppressFinalize(this);
  687. }
  688. }
  689. }