using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Vinno.IUS.Common.Log;
using Vinno.IUS.Common.Network.Leaf;
using Vinno.IUS.Common.Network.Tcp;
using Vinno.IUS.Common.Network.Transfer;
using Vinno.IUS.Common.Utilities;
using Vinno.vCloud.Common.Storage.Download;
using Vinno.vCloud.FIS.CrossPlatform.Common;
using Vinno.vCloud.Protocol.Infrastructures;
using Vinno.vCloud.Protocol.Messages.Terminal.Remedical.TerminialLog;
using Vinno.vCloud.Protocol.Messages.Upgrade;
namespace Vinno.vCloud.Common.FIS.Upgraders
{
internal class Upgraders : IUpgraders
{
private const string _tokenSplitor = "1!U$";
private const string _tokenSplitor2 = "0!U$";
private readonly ClientLeaf _leaf;
private bool _disposed;
///
/// Raise the event when force upgrade.
///
public event EventHandler ForceUpgraded;
///
/// The constructor of the AfterSales
///
/// The
public Upgraders(ClientLeaf leaf)
{
_leaf = leaf;
_leaf.MessageArrived += OnMessageArrived;
}
~Upgraders()
{
Dispose();
}
///
/// Get upgrade version.
///
/// Package info
public PackageInfo GetUpgradeVersion(UpgradePlatform platform, UpgradeType upgradeType)
{
using (var request = MessagePool.GetMessage())
{
request.Platform = platform;
request.Type = upgradeType;
var result = _leaf.Send(request);
var versionResult = GetUpgradeVersionResult.Convert(result);
if (versionResult != null)
{
var upgradeServerUrl = versionResult.UpgradeUrl;
var version = versionResult.Version;
var fileMd5 = versionResult.FileMD5.GetBytes();
return new PackageInfo(version, upgradeServerUrl, fileMd5);
}
}
return null;
}
///
/// Download client package.
///
public void DownloadPackage(string url, string packagePath, UpgradePlatform platform, UpgradeType upgradeType)
{
var tcpCreator = new TcpCreator(url);
using (var request = MessagePool.GetMessage())
{
request.Platform = platform;
request.Type = upgradeType;
var tempPath = packagePath + ".tmp";
using (var stream = File.Create(tempPath))
{
var downloadLeaf = new ClientLeaf(new LeafIdContext(), LeafMode.None, tcpCreator);
try
{
downloadLeaf.Send(request, sendResult =>
{
var dataResult = GetUpgradeFileDataResult.Convert(sendResult.Result);
if (dataResult != null)
{
var data = dataResult.FileData.GetBytes();
stream.Write(data, 0, data.Length);
}
});
}
finally
{
downloadLeaf.Close();
}
}
File.Move(tempPath, packagePath);
}
}
///
/// Download client package support the Resume breakpoint.
///
public void ResumeDownloadPackage(string url, string packagePath, UpgradePlatform platform, UpgradeType upgradeType)
{
}
///
/// Get Ultrasound Machine Latest Package Info
///
///
/// Ultrasound Machine Package Info
public UpgradePackageInfo GetUltrasoundMachineLatestPackageInfo(string uniqueCode)
{
using (var queryLatestPackageRequest = MessagePool.GetMessage())
{
queryLatestPackageRequest.UniquedCode = uniqueCode;
var message = _leaf.Send(queryLatestPackageRequest);
if (message == null)
{
return null;
}
var result = GetPackageResult.Convert(message);
if (result != null)
{
var createUserName = result.CreateUserName;
var description = result.Description;
var fileName = result.FileName;
var fileSize = result.FileSize;
var fileToken = result.FileToken;
var updateTime = result.UpdateTime;
var version = result.Version;
return new UpgradePackageInfo
{
PackageName = fileName,
Version = version,
UniqueCode = uniqueCode,
Description = description,
PackageToken = fileToken,
PackageSize = fileSize,
UploadUserName = createUserName,
UpdateTime = updateTime,
};
}
}
return null;
}
///
/// Download the Latest Package of Ultrasound Machine from Storage Server Async.
///
/// File Token
/// The Path to place the package
/// Download Progress
/// Cancel Token Source
public void DownloadPackage(string url, string packagePath, Action progress = null, CancellationTokenSource cancelTokenSource = null)
{
var fileToken = url;
if (!fileToken.StartsWith(_tokenSplitor) && !fileToken.StartsWith(_tokenSplitor2))
{
fileToken = _tokenSplitor + fileToken;
}
DownloadHelper.GetFile(fileToken, packagePath, progress, cancelTokenSource, true);
}
///
/// Download the Latest Package of Ultrasound Machine from Storage Server Async.
///
/// File Token
/// The Path to place the package
/// Download Progress
/// Cancel Token Source
///
public async Task DownloadPackageAsync(string url, string packagePath, Action progress = null, CancellationTokenSource cancelTokenSource = null)
{
var fileToken = url;
if (!fileToken.StartsWith(_tokenSplitor) && !fileToken.StartsWith(_tokenSplitor2))
{
fileToken = _tokenSplitor + fileToken;
}
await DownloadHelper.GetFileAsync(fileToken, packagePath, progress, cancelTokenSource);
}
///
/// Get Latest FIS Patch
///
/// Device Patch Type
/// Client OS Type
/// Latest FIS Patch Info
public UpgradePatchInfo GetLatestFISPatch(DevicePatchType patchType, ClientOSType osType)
{
using (var request = MessagePool.GetMessage())
{
request.PatchType = patchType;
request.FitPlatform = osType;
request.IsSonopost = CommonParameter.Instance.IsSonopost;
var message = _leaf.Send(request);
var result = GetPatchFISResult.Convert(message);
if (result != null)
{
var returnPatchType = result.PatchType;
var version = result.Version;
var url = result.FileUrl;
var description = result.Description;
return new UpgradePatchInfo(returnPatchType, version, url, description);
}
}
return null;
}
private void DoDispose()
{
if (!_disposed)
{
_leaf.MessageArrived -= OnMessageArrived;
_disposed = true;
}
}
private void OnMessageArrived(object sender, Message e)
{
var modifyFISNotification = ModifyFISNotification.Convert(e);
if (modifyFISNotification != null)
{
HandleModifyFISNotification(modifyFISNotification);
}
}
private void HandleModifyFISNotification(ModifyFISNotification modifyFISNotification)
{
ForceUpgraded?.Invoke(null, new UpgradePatchInfo(modifyFISNotification.PatchType, modifyFISNotification.Version, modifyFISNotification.FileUrl, modifyFISNotification.Description));
}
///
/// Is Has New Package
///
///
///
///
///
public UpgradeInfo IsHasNewPackage(UpgradePlatform platform, UpgradeType upgradeType, string version)
{
try
{
using (var request = new GetUpgradeInfoRequest())
{
request.Platform = platform;
request.Type = upgradeType;
request.CurrentVersion = version;
var currentVersion = new Version("1.0.0.0");
Version.TryParse(version, out currentVersion);
var result = _leaf.Send(request);
var upgradeInfoResult = GetUpgradeInfoResult.Convert(result);
if (upgradeInfoResult != null)
{
var latestVersion = new Version("1.0.0.0");
Version.TryParse(upgradeInfoResult.NewVersion, out latestVersion);
Logger.WriteLineInfo($"The latest version is {latestVersion} in server");
if (upgradeInfoResult.UpgadeType != UpgradeTypeEnum.NoUpgrade && latestVersion > currentVersion)
{
return new UpgradeInfo
{
UpgradeUrl = upgradeInfoResult.UpgradeUrl,
StorageType = upgradeInfoResult.StorageType,
UpgradeType = upgradeType,
UpgradePlatform = platform,
};
}
}
}
}
catch (Exception ex)
{
Logger.WriteLineError($"DownloadUFilePackage Error:{ex}");
}
return new UpgradeInfo
{
UpgradeUrl = "",
UpgradeType = upgradeType,
UpgradePlatform = platform,
};
}
///
///
/// Download Package
///
///
///
///
public void DownloadPackage(string packagePath, UpgradeInfo upgradeInfo, Action progress = null, CancellationTokenSource cancelTokenSource = null)
{
try
{
if (upgradeInfo.StorageType == StorageType.ObjectStorage)
{
DownloadHelper.GetFile(upgradeInfo.UpgradeUrl, packagePath, progress, cancelTokenSource, true); //下载升级包
}
else
{
var tcpCreatorDownLoad = new TcpCreator(upgradeInfo.UpgradeUrl);
var downLoadLeaf = new ClientLeaf(new LeafIdContext(), LeafMode.Single, tcpCreatorDownLoad);
var packageFileExtension = Path.GetExtension(packagePath);
var cacheFilePath = Path.ChangeExtension(packagePath, "tmp");
FileHelper.DeleteFile(packagePath);
FileHelper.DeleteFile(cacheFilePath);
var finished = false;
using (var stream = File.Open(cacheFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) //打开文件
{
while (!finished)
{
if (cancelTokenSource != null && cancelTokenSource.IsCancellationRequested)
{
FileHelper.DeleteFile(cacheFilePath);
return;
}
var position = (int)stream.Length;
using (var requestDownLoad = MessagePool.GetMessage())
{
requestDownLoad.Platform = upgradeInfo.UpgradePlatform;
requestDownLoad.Type = upgradeInfo.UpgradeType;
requestDownLoad.FilePosition = position;
var token = downLoadLeaf.ApplyToken();
var downLoadResult = downLoadLeaf.Send(token, requestDownLoad);
var downLoadFileResult = BreakpointDownloadUpgradeFileDataResult.Convert(downLoadResult);
if (downLoadResult != null)
{
downLoadFileResult.FileData.Save(stream);
if (stream.Length >= downLoadFileResult.FileSize)
{
progress?.Invoke(1.0);
finished = true;
}
else
{
progress?.Invoke((double)stream.Length / downLoadFileResult.FileSize);
}
}
}
}
}
File.Move(cacheFilePath, packagePath);
}
}
catch (Exception ex)
{
Logger.WriteLineError($"DownloadUFilePackage Error:{ex}");
}
}
public void Dispose()
{
DoDispose();
GC.SuppressFinalize(this);
}
}
}