123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735 |
- using SkiaSharp;
- using System;
- using System.IO;
- using System.Linq;
- using System.Threading;
- using Vinno.IUS.Common.Log;
- using Vinno.vCloud.Common.FIS.Helper;
- using Vinno.vCloud.Common.Vid2;
- using Vinno.vCloud.FIS.CrossPlatform.Common.Helper;
- using Vinno.vCloud.Protocol.Infrastructures;
- using WingInterfaceLibrary.DTO.Comment;
- using WingInterfaceLibrary.DTO.Measure;
- using WingInterfaceLibrary.DTO.Record;
- using WingInterfaceLibrary.Enum;
- using WingInterfaceLibrary.Interface;
- using WingInterfaceLibrary.Request.Examine;
- using WingInterfaceLibrary.Request.Storage;
- using WingInterfaceLibrary.Result.Examine;
- namespace Vinno.vCloud.Common.FIS.Remedicals
- {
- internal class vCloudScanDataV2 : IvCloudScanData, IDisposable
- {
- private UploadStatus _status;
- private readonly IRemedicalService _remedicalService;
- private readonly IStorageService _storageService;
- private readonly string _token;
- private bool _disposed;
- private const string BreastImageLocation = "BreastImageLocation";
- private const string LiverImageLocation = "LiverImageLocation";
- private const string ThyroidImageLocation = "ThyroidImageLocation";
- /// <inheritdoc />
- /// <summary>
- /// Gets the id of this scan data.
- /// </summary>
- public string Id { get; }
- /// <inheritdoc />
- /// <summary>
- /// Gets the examId of this scan data.
- /// </summary>
- public string ExamId { get; }
- /// <inheritdoc />
- /// <summary>
- /// Gets or sets the ExamRecordId for this scan data.
- /// </summary>
- public string ExamRecordId { get; set; }
- /// <inheritdoc />
- /// <summary>
- /// Gets the workorder Id.
- /// </summary>
- public string WorkOrderId { get; }
- /// <summary>
- /// Raised when the status changed.
- /// </summary>
- public event EventHandler StatusChanged;
- /// <inheritdoc />
- /// <summary>
- /// Gets the status of this Scan data.
- /// </summary>
- public UploadStatus Status
- {
- get => _status;
- internal set
- {
- if (_status != value)
- {
- var old = _status;
- _status = value;
- if (_status == UploadStatus.Uploaded || _status == UploadStatus.Deleted)
- {
- Delete(old);
- }
- else
- {
- Move(old, _status);
- }
- OnStatusChanged();
- }
- }
- }
- /// <inheritdoc />
- /// <summary>
- /// Gets the vid file path.
- /// </summary>
- public string VidFilePath { get; private set; }
- /// <summary>
- /// Gets the sd file path.
- /// </summary>
- public string ScanDataFilePath { get; private set; }
- /// <inheritdoc />
- /// <summary>
- /// Gets the description of this scan data.
- /// </summary>
- public string Description { get; }
- /// <inheritdoc />
- /// <summary>
- /// Gets the application of this scan data.
- /// </summary>
- public string Application { get; }
- /// <summary>
- /// Gets the Application Category of this scan data
- /// </summary>
- public string ApplicationCategory { get; }
- /// <inheritdoc />
- /// <summary>
- /// Gets the data type of this scan data.
- /// </summary>
- public VidType DataType { get; }
- /// <inheritdoc />
- /// <summary>
- /// Gets the patient info for this scan data.
- /// </summary>
- public PatientScanInfo PatientInfo { get; }
- /// <summary>
- /// Get the Measure Results
- /// </summary>
- public MeasuredResultsDTO MeasuredResults { get; }
- /// <summary>
- /// Get the comment Results
- /// </summary>
- public ScanImageDTO CommentResults { get; }
- public vCloudScanDataV2(IvCloudExamRecord record, string id, string vidFilePath,
- VidType dataType, string description, PatientScanInfo patientInfo, UploadStatus status, IRemedicalService remedicalService, IStorageService storageService, string token, MeasuredResultsDTO measuredResults = null, ScanImageDTO commentResults = null)
- {
- _status = status;
- _token = token;
- _remedicalService = remedicalService;
- _storageService = storageService;
- ExamRecordId = record.Id;
- ExamId = record.ExamId;
- WorkOrderId = record.WorkOrderId;
- Id = id;
- DataType = dataType;
- Description = description;
- PatientInfo = patientInfo;
- MeasuredResults = measuredResults;
- CommentResults = commentResults;
- //Generate files.
- VidFilePath = GetVidFilePath(_status);
- if (string.Compare(VidFilePath, vidFilePath, StringComparison.OrdinalIgnoreCase) != 0)
- {
- File.Move(vidFilePath, VidFilePath);
- }
- if (description == "FromSonopost")
- {
- Application = string.Empty;
- ApplicationCategory = description;
- }
- else
- {
- using (var vinnoImage = new VinnoImageData(VidFilePath, OperationMode.Open))
- {
- ApplicationCategory = vinnoImage.Probe?.Application?.ApplicationCategoryName;
- Application = vinnoImage.Probe?.Application?.ApplicationName;
- }
- }
- //Save self.
- Save();
- }
- ~vCloudScanDataV2()
- {
- DoDispose();
- }
- private void OnStatusChanged()
- {
- StatusChanged?.Invoke(this, EventArgs.Empty);
- }
- /// <summary>
- /// Delete this scanData and its files.
- /// </summary>
- public void Delete()
- {
- Status = UploadStatus.Deleted;
- }
- /// <summary>
- /// Force update the scan data's status.
- /// </summary>
- /// <param name="status">The new status</param>
- public void ForceUpdateStaus(UploadStatus status)
- {
- Status = status;
- }
- /// <summary>
- /// Force update and save the scan data.
- /// </summary>
- public void Update()
- {
- Save();
- }
- /// <summary>
- /// Get saved scan data file path
- /// </summary>
- /// <param name="status"></param>
- /// <returns></returns>
- private string GetScanDataFilePath(UploadStatus status)
- {
- if (status == UploadStatus.Deleted)
- {
- throw new InvalidOperationException("File already deleted.");
- }
- var subFolder = string.Empty;
- if (status == UploadStatus.Idle || status == UploadStatus.Waiting || status == UploadStatus.Uploading)
- {
- subFolder = "Upload";
- }
- if (status == UploadStatus.Fail || status == UploadStatus.FailBecauseExamIsFinished)
- {
- subFolder = "Failed";
- }
- var folder = GetWorkingFolder(subFolder);
- var fileName = $"{Id}.sd";
- return Path.Combine(folder, fileName);
- }
- private string GetWorkingFolder(string subFolder)
- {
- var folder = Path.Combine(vCloudTerminalV2.WorkingFolder, "RemedicalV2", subFolder);
- DirectoryHelper.CreateDirectory(folder);
- return folder;
- }
- /// <summary>
- /// Get the vid file path.
- /// </summary>
- /// <param name="status"></param>
- /// <returns></returns>
- private string GetVidFilePath(UploadStatus status)
- {
- if (status == UploadStatus.Deleted)
- {
- throw new InvalidOperationException("File already deleted.");
- }
- var subFolder = string.Empty;
- if (status == UploadStatus.Idle || status == UploadStatus.Waiting || status == UploadStatus.Uploading)
- {
- subFolder = "Upload";
- }
- if (status == UploadStatus.Fail || status == UploadStatus.FailBecauseExamIsFinished)
- {
- subFolder = "Failed";
- }
- var folder = GetWorkingFolder(subFolder);
- var fileName = $"{Id}.vid";
- return Path.Combine(folder, fileName);
- }
- /// <summary>
- /// Delete the files
- /// </summary>
- /// <param name="status"></param>
- private void Delete(UploadStatus status)
- {
- var scanDataFilePath = GetScanDataFilePath(status);
- var vidFilePath = GetVidFilePath(status);
- FileHelper.DeleteFile(scanDataFilePath);
- FileHelper.DeleteFile(vidFilePath);
- }
- /// <summary>
- /// Save scan data and vid file to the disk by current status.
- /// </summary>
- private void Save()
- {
- ScanDataFilePath = GetScanDataFilePath(Status);
- this.Serialize(ScanDataFilePath);
- }
- /// <summary>
- /// Move scan data from one to another
- /// </summary>
- /// <param name="source"></param>
- /// <param name="dest"></param>
- private void Move(UploadStatus source, UploadStatus dest)
- {
- var sourceScanDataFilePath = GetScanDataFilePath(source);
- var sourceVidFilePath = GetVidFilePath(source);
- var destScanDataFilePath = GetScanDataFilePath(dest);
- var destVidFilePath = GetVidFilePath(dest);
- if (File.Exists(sourceScanDataFilePath) && !File.Exists(destScanDataFilePath))
- {
- File.Move(sourceScanDataFilePath, destScanDataFilePath);
- ScanDataFilePath = destScanDataFilePath;
- }
- if (File.Exists(sourceVidFilePath) && !File.Exists(destVidFilePath))
- {
- File.Move(sourceVidFilePath, destVidFilePath);
- VidFilePath = destVidFilePath;
- }
- }
- /// <summary>
- /// Upload the data to the vCloud server.
- /// </summary>
- public void Upload(CancellationTokenSource cancellationTokenSource)
- {
- string previewFileToken = string.Empty;
- string coverImageToken = string.Empty;
- ImageLocationDTO imageLocationDTO = null;
- using (var vinnoImage = new VinnoImageData(VidFilePath, OperationMode.Open))
- {
- if (vinnoImage.ImageCount <= 0)
- {
- throw new FileNotFoundException("The VinnoImageData Image Count <=0");
- }
- }
- if (vCloudServerConfig.Instance.IsUploadThumbnail)
- {
- var storageUrl = UploadFirstImage(cancellationTokenSource);
- if (string.IsNullOrWhiteSpace(storageUrl))
- {
- throw new InvalidOperationException($"Get token failed when Uploading first image");
- }
- coverImageToken = storageUrl;
- storageUrl = UploadPreviewImage(cancellationTokenSource);
- if (string.IsNullOrWhiteSpace(storageUrl))
- {
- throw new InvalidOperationException($"Get token failed when Uploading preview image");
- }
- previewFileToken = storageUrl;
- imageLocationDTO = GetImageLocation(cancellationTokenSource);
- }
- var url = UploadVidFile(cancellationTokenSource);
- if (string.IsNullOrWhiteSpace(url))
- {
- throw new InvalidOperationException("Get token failed when Uploading VID file");
- }
- var fileType = RemedicalFileDataTypeEnum.VinnoVidSingle;
- switch (DataType)
- {
- case VidType.VinnoVidMovie:
- fileType = RemedicalFileDataTypeEnum.VinnoVidMovie;
- break;
- case VidType.ThirdVidSingle:
- fileType = RemedicalFileDataTypeEnum.ThirdVidSingle;
- break;
- case VidType.ThirdVidMovie:
- fileType = RemedicalFileDataTypeEnum.ThirdVidMovie;
- break;
- }
- var fileInfo = new FileInfo(VidFilePath);
- var fileSize = fileInfo.Length;
- var uploadExamDataRequest = new UploadExamDataRequest
- {
- Token = _token,
- ExamCode = ExamRecordId,
- FileToken = url,
- FileSize = fileSize,
- Application = Application,
- ApplicationCategory = ApplicationCategory,
- FileDataType = fileType,
- PreviewFileToken = previewFileToken,
- CoverImageToken = coverImageToken,
- MeasuredResult = MeasuredResults,
- CommentResult = CommentResults,
- ImageLocation = imageLocationDTO
- };
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- var result = JsonRpcHelper.UploadExamData(_remedicalService, uploadExamDataRequest);
- if (result == null)
- {
- throw new InvalidDataException($"JsonRPCHelper UploadExamData Result is null");
- }
- else if (result.IsSuccess)
- {
- Status = UploadStatus.Uploaded;
- return;
- }
- else if (!result.IsSuccess)
- {
- if (result.ErrorCode == 4002)
- {
- Status = UploadStatus.FailBecauseExamIsFinished;
- Save();
- return;
- }
- else if (result.ErrorCode == 4015)
- {
- if (CreateExamRecord())
- {
- result = JsonRpcHelper.UploadExamData(_remedicalService, uploadExamDataRequest);
- if (result == null)
- {
- throw new InvalidDataException($"JsonRPCHelper UploadExamData Result is null");
- }
- else if (result.IsSuccess)
- {
- Status = UploadStatus.Uploaded;
- return;
- }
- else
- {
- throw new InvalidDataException($"JsonRPCHelper UploadExamData Fail,Error Code is {result.ErrorCode}");
- }
- }
- else
- {
- throw new InvalidDataException($"JsonRPCHelper UploadExamData Fail:ReCreateExamRecord Result is false");
- }
- }
- else
- {
- throw new InvalidDataException($"JsonRPCHelper UploadExamData Fail,Error Code is {result.ErrorCode}");
- }
- }
- }
- private ImageLocationDTO GetImageLocation(CancellationTokenSource cancellationTokenSource)
- {
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- using (var vinnoImage = new VinnoImageData(VidFilePath, OperationMode.Open))
- {
- var imageLocationExtenedData = VidExtendedData.FromBytes(vinnoImage.ExtendedData);
- if (imageLocationExtenedData != null && imageLocationExtenedData.Data != null)
- {
- var positionTag = imageLocationExtenedData.Data.Keys.FirstOrDefault(t => t.Element == "Position" && t.Group == BreastImageLocation);
- var quadrantTag = imageLocationExtenedData.Data.Keys.FirstOrDefault(t => t.Element == "Quadrant" && t.Group == BreastImageLocation);
- if (positionTag != null && quadrantTag != null)
- {
- if (Enum.TryParse<Position>(imageLocationExtenedData.Data[positionTag].GetValue()?.ToString(), out var positionEnum)
- && Enum.TryParse<QuadrantEnum>(imageLocationExtenedData.Data[quadrantTag].GetValue()?.ToString(), out var quadrantEnum))
- {
- return new ImageLocationDTO
- {
- Position = positionEnum.ToString(),
- Quadrant = quadrantEnum.ToString(),
- Group = positionTag.Group,
- };
- }
- }
- positionTag = imageLocationExtenedData.Data.Keys.FirstOrDefault(t => t.Element == "Position" && t.Group == LiverImageLocation);
- if (positionTag != null)
- {
- if (Enum.TryParse<LiverPosition>(imageLocationExtenedData.Data[positionTag].GetValue()?.ToString(), out var positionEnum))
- {
- return new ImageLocationDTO
- {
- Position = positionEnum.ToString(),
- Group = positionTag.Group,
- };
- }
- }
- positionTag = imageLocationExtenedData.Data.Keys.FirstOrDefault(t => t.Element == FISTissueCategory.Position && !string.IsNullOrWhiteSpace(t.Group));
- var groupName = positionTag?.Group;
- if (positionTag != null && !imageLocationExtenedData.Data.Keys.Any(x => x.Group == groupName && x.Element != FISTissueCategory.Position))
- {
- return new ImageLocationDTO
- {
- Group = groupName,
- Position = imageLocationExtenedData.Data[positionTag].GetValue()?.ToString(),
- };
- }
- }
- }
- return null;
- }
- /// <inheritdoc />
- /// <summary>
- /// Create an exam record from vCloud.
- /// </summary>
- /// <param name="examId">The local excam id.</param>
- /// <param name="workOrderId">The workerId</param>
- /// <param name="patientInfo">The patient basic info for creating the exam record.</param>
- /// <returns><see cref="T:Vinno.vCloud.Terminal.Remedicals.IvCloudExamRecord" /></returns>
- public bool CreateExamRecord()
- {
- var createExaminfoRequest = new CreateExaminfoRequest
- {
- Token = _token,
- PatientType = vCloudServerConfig.Instance.PatientType.ToString(),
- ExamRecordCode = ExamRecordId,
- PatientInfo = DTOConverter.RenderPatientInfo(PatientInfo),
- PatientScanInfoList = DTOConverter.RenderPatientScanInfo(PatientInfo),
- };
- CreateExaminfoResult result = JsonRpcHelper.CreateExamInfo(_remedicalService, createExaminfoRequest);
- if (result == null || result.ExamCode != ExamRecordId)
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- private string UploadFirstImage(CancellationTokenSource cancellationTokenSource)
- {
- try
- {
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- var firstImageName = "firstImage_" + Path.GetFileNameWithoutExtension(VidFilePath) + ".jpg";
- using (var vinnoImage = new VinnoImageData(VidFilePath, OperationMode.Open))
- {
- var image = vinnoImage.GetImage(0);
- var fileServiceRequest = new FileServiceRequest
- {
- FileName = firstImageName,
- IsRechristen = true,
- Token = _token,
- };
- var authorizationInfo = JsonRpcHelper.GetAuthorization(_storageService, fileServiceRequest);
- if (authorizationInfo == null)
- {
- throw new Exception("GetAuthorization Error,AuthorizationInfo is null ");
- }
- var uploadResult = UploadFileHelper.UploadFile(authorizationInfo.StorageUrl, image?.ImageData, authorizationInfo.ContentType, authorizationInfo.Authorization, null, cancellationTokenSource);
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- if (uploadResult)
- {
- return authorizationInfo.StorageUrl;
- }
- else
- {
- return string.Empty;
- }
- }
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"Upload First Image Error:{ex}");
- return string.Empty;
- }
- }
- private string UploadPreviewImage(CancellationTokenSource cancellationTokenSource)
- {
- try
- {
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- var previewImageName = "preview_" + Path.GetFileNameWithoutExtension(VidFilePath) + ".jpg";
- using (var vinnoImage = new VinnoImageData(VidFilePath, OperationMode.Open))
- {
- var image = vinnoImage.GetImage(0);
- var fileServiceRequest = new FileServiceRequest
- {
- FileName = previewImageName,
- IsRechristen = true,
- Token = _token,
- };
- var authorizationInfo = JsonRpcHelper.GetAuthorization(_storageService, fileServiceRequest);
- if (authorizationInfo == null)
- {
- throw new Exception("GetAuthorization Error,AuthorizationInfo is null ");
- }
- var compressedImage = Compress(image);
- var uploadResult = UploadFileHelper.UploadFile(authorizationInfo.StorageUrl, compressedImage?.ImageData, authorizationInfo.ContentType, authorizationInfo.Authorization, null, cancellationTokenSource);
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- if (uploadResult)
- {
- return authorizationInfo.StorageUrl;
- }
- else
- {
- return string.Empty;
- }
- }
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"Upload Preview Image Error:{ex}");
- return string.Empty;
- }
- }
- private string UploadVidFile(CancellationTokenSource cancellationTokenSource)
- {
- try
- {
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- var fileName = Path.GetFileName(VidFilePath);
- var fileServiceRequest = new FileServiceRequest
- {
- FileName = fileName,
- IsRechristen = true,
- Token = _token,
- };
- var authorizationInfo = JsonRpcHelper.GetAuthorization(_storageService, fileServiceRequest);
- if (authorizationInfo == null)
- {
- throw new Exception("GetAuthorization Error,AuthorizationInfo is null ");
- }
- var uploadResult = UploadFileHelper.UploadFile(authorizationInfo.StorageUrl, VidFilePath, authorizationInfo.ContentType, authorizationInfo.Authorization, null, cancellationTokenSource);
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- if (uploadResult)
- {
- return authorizationInfo.StorageUrl;
- }
- else
- {
- return string.Empty;
- }
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"Upload Vid File Error:{ex}");
- return string.Empty;
- }
- }
- private void DoDispose()
- {
- try
- {
- if (!_disposed)
- {
- //if not uploaded just save it to disk.
- if (Status != UploadStatus.Uploaded && Status != UploadStatus.Deleted)
- {
- Save();
- }
- }
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"vCloudScanData: dispose upload data error:{ex}");
- }
- finally
- {
- _disposed = true;
- }
- }
- /// <summary>
- /// Compress a VinnoImage to a 100p image with {compressLevel} quality
- /// </summary>
- /// <param name="vinnoImage"></param>
- /// <param name="compressLevel"></param>
- /// <returns></returns>
- /// <exception cref="Exception"></exception>
- private VinnoImage Compress(VinnoImage vinnoImage, long compressLevel = 80)
- {
- byte[] compressedData = vinnoImage.ImageData;
- using (var ms = new MemoryStream(compressedData))
- {
- using (var image = SKBitmap.Decode(ms))
- {
- var ratio = (double)100 / image.Height;
- if (ratio < 1)
- {
- var width = (int)(image.Width * ratio);
- var height = 100;
- SKBitmap tempImage = image;
- if (image.Width != width || image.Height != height)
- {
- tempImage = image.Resize(new SKImageInfo(width, height), SKFilterQuality.High);
- }
- try
- {
- using (var map = new SKPixmap(new SKImageInfo(tempImage.Width, tempImage.Height, tempImage.ColorType), tempImage.GetPixels()))
- {
- using (var stream = new SKDynamicMemoryWStream())
- {
- SKPixmap.Encode(stream, map, SKEncodedImageFormat.Jpeg, (int)compressLevel);
- compressedData = stream.CopyToData().ToArray();
- }
- }
- }
- catch (Exception exception)
- {
- throw new Exception($"Compress error:{exception}");
- }
- finally
- {
- tempImage.Dispose();
- }
- var compressImage = new VinnoImage(vinnoImage.Index, width, height, compressedData);
- return compressImage;
- }
- }
- }
- return vinnoImage;
- }
- public void Dispose()
- {
- DoDispose();
- GC.SuppressFinalize(this);
- }
- }
- }
|