123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583 |
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using Vinno.IUS.Common.Log;
- using Vinno.IUS.Common.Network.Transfer;
- using Vinno.vCloud.Common.Storage.ObjectStorageInfo.Interface;
- using Vinno.vCloud.Common.Storage.ObjectStorageInfo.SignatureClient.Connect;
- using Vinno.vCloud.Common.Storage.ObjectStorageInfo.SignatureClient.UFile;
- using Vinno.vCloud.Common.Storage.ObjectStorageInfo.Solid;
- using Vinno.vCloud.Protocol.Infrastructures.Storage;
- using Vinno.vCloud.Protocol.Initializers;
- using Vinno.vCloud.Protocol.Messages.Common;
- using Vinno.vCloud.Protocol.Messages.Upgrade;
- namespace vCloud.Windows.ForceUpgrade
- {
- /// <summary>
- /// MainWindow.xaml 的交互逻辑
- /// </summary>
- public partial class MainWindow : Window
- {
- private ILeafAgency _leafAgency;
- private UpgradeFilePathReader _filePathReader = new UpgradeFilePathReader();
- private string _fileListPath =Path.Combine(AppDomain.CurrentDomain.BaseDirectory , "FileList.json");
- private double _pie;
- private double _leftMargin;
- private double _currentProcess;
- private bool _isDownloadFinish = false;
- private IUFileStorageHelper _uFileStorageHelper;
- public MainWindow()
- {
- UpgradeTagsInitializer.Initialize();
- InitializeComponent();
- InitProcess();
- try
- {
- Task.Run(() =>
- {
- try
- {
- string upgradeServerUrl = string.Empty;
- var dic = CheckVersion(out upgradeServerUrl, App.GetVersion);
- if (dic.Count > 0)
- {
- KillVcloudClientProcess();
- Thread.Sleep(1000);
- KillVcloudClientProcess();
- Thread.Sleep(1000);
- RunUpgrade(dic, OnUpload);
- }
- else
- {
- OnUpload(100);
- RestartClient();
- }
- }
- catch (NetWorkException ex)
- {
- FileHelper.AppendWriteFile("UpgradeLog.txt", ex.Message + "|" + ex.StackTrace);
- Dispatcher.Invoke(() =>
- {
- MessageBox.Show(this, $"{App.GetOfflineShow}");
- Environment.Exit(0);
- });
- }
- catch (Exception ex)
- {
- FileHelper.AppendWriteFile("UpgradeLog.txt", ex.Message + "|" + ex.StackTrace);
- Dispatcher.Invoke(() =>
- {
- MessageBox.Show(this, $"{App.UpgradeError}");
- Environment.Exit(0);
- });
- }
- });
- }
- catch (Exception ex)
- {
- FileHelper.AppendWriteFile("UpgradeLog.txt", ex.Message + "|" + ex.StackTrace);
- Dispatcher.Invoke(() =>
- {
- MessageBox.Show(this, $"{App.UpgradeError}");
- Environment.Exit(0);
- });
- }
- }
- private void InitProcess()
- {
- ImageBrush backImage = new ImageBrush();
- var backImageUri = new Uri("pack://application:,,,/backImage.png");
- if (!App.IsChinese)
- {
- backImageUri = new Uri("pack://application:,,,/enBackImage.png");
- }
- backImage.ImageSource = new BitmapImage(backImageUri);
- backImage.Stretch = Stretch.Fill;
- Background = backImage;
- InstallProcess.Content = "1%";
- _pie = 551 / 100d;
- _leftMargin = 14;
- }
- /// <summary>
- /// 检查版本
- /// </summary>
- /// <param name="upgradeServerUrl"></param>
- /// <returns></returns>
- private Dictionary<string, UpgradeFileInfo> CheckVersion(out string upgradeServerUrl, string newVersion, bool forced = false)
- {
- upgradeServerUrl = string.Empty;
- string fileList = string.Empty;
- Dictionary<string, UpgradeFileInfo> srcDic = null;
- if (!File.Exists(_fileListPath) || forced == true)
- {
- srcDic = _filePathReader.StartReader(AppDomain.CurrentDomain.BaseDirectory);
- }
- else
- {
- fileList = File.ReadAllText(_fileListPath);
- srcDic = JsonConvert.DeserializeObject<Dictionary<string, UpgradeFileInfo>>(fileList);
- }
- //排除不存在的文件
- if (srcDic != null && srcDic.Count > 0)
- {
- var srcArray = srcDic.ToArray();
- foreach (var finfo in srcArray)
- {
- var filePath = finfo.Key.Replace("RootPath", $"{AppDomain.CurrentDomain.BaseDirectory}");
- if (!File.Exists(filePath))
- {
- srcDic.Remove(finfo.Key);
- }
- }
- fileList = JsonConvert.SerializeObject(srcDic);
- File.WriteAllText(_fileListPath, fileList);
- }
- if (string.IsNullOrWhiteSpace(newVersion) || newVersion == "New Version")
- {
- newVersion = GetNewPackageVersion(App.GetServerUrl)?.ToString();
- Dispatcher.Invoke(() =>
- {
- InstallVersion.Content = newVersion;
- });
- }
- string storageUrl = string.Empty;
- using (_leafAgency = new SimpleLeafAgency(App.GetServerUrl))
- {
- var request = new GetStorageUrlRequest();
- var urlMessage = _leafAgency.AgencySend(request);
- var storageUrlMessage = GetStorageUrlResult.Convert(urlMessage);
- if (storageUrlMessage != null)
- {
- storageUrl = storageUrlMessage.StorageUrl;
- }
- }
- if (!string.IsNullOrWhiteSpace(storageUrl))
- {
- _leafAgency = new SimpleLeafAgency(storageUrl);
- _uFileStorageHelper = new UFileStorageServerHelper(_leafAgency);
- var tempFileListPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ServerFileList.json");
- if (File.Exists(tempFileListPath))
- {
- File.Delete(tempFileListPath);
- }
- var isDownloadSuccess = _uFileStorageHelper.DownloadFile(
- new ObjectFileDownloadInfo
- {
- FileName = $"FileList[{newVersion}].json",
- FileLocalPath = tempFileListPath
- },
- StorageNodeType.UpgradeStorageCDN);
- if (isDownloadSuccess)
- {
- var json1 = File.ReadAllText(tempFileListPath);
- var json2 = File.ReadAllText(_fileListPath);
- var dic = _filePathReader.DiffReaderJson(json1, json2);
- using (Process ps = new Process())
- {
- ps.StartInfo.FileName = "cmd.exe";
- ps.StartInfo.UseShellExecute = false;
- ps.StartInfo.RedirectStandardOutput = true;
- ps.StartInfo.RedirectStandardInput = true;
- ps.StartInfo.CreateNoWindow = true;
- ps.StartInfo.Verb = "runas";
- ps.Start();
- ps.StandardInput.WriteLine($"taskkill /f /t /FI \"imagename eq vCloud.Windows.exe\"");
- ps.WaitForExit(1000);
- ps.StandardInput.WriteLine("exit");
- }
- return dic;
- }
- }
- return new Dictionary<string, UpgradeFileInfo>();
- }
- /// <summary>
- /// 客户端更新
- /// </summary>
- /// <param name="dic"></param>
- /// <param name="progressCallback"></param>
- private void RunUpgrade(Dictionary<string, UpgradeFileInfo> dic, Action<double> progressCallback = null)
- {
- if (dic != null && dic.Count > 0)
- {
- var fileCounts = dic.Count(f=>f.Value.Type == UpgradeOperateType.Add && f.Key.IndexOf("vCloud.Windows.ForceUpgrade.exe")==-1);
- int finishFileCount = 0;
- var totalFileProgress = 100F / (dic.Count);
- finishFileCount = AddFilesInStepUFileStorage(dic, progressCallback, finishFileCount, totalFileProgress);
- if (finishFileCount != fileCounts)
- {
- FileHelper.AppendWriteFile("UpgradeLog.txt", $"Upgrade Fail {App.PartFilesFail}");
- }
- else
- {
- File.Delete(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"vCloud.Windows.exe"));
- }
- _isDownloadFinish = true;
- var updateTemp = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UpdateTemp");
- MoveFiles(updateTemp, AppDomain.CurrentDomain.BaseDirectory);
- DelEmptyFolder(AppDomain.CurrentDomain.BaseDirectory);
- Directory.Delete(updateTemp, true);
- if (File.Exists(_fileListPath))
- {
- var oldfileList = File.ReadAllText(_fileListPath);
- var oldDic = JsonConvert.DeserializeObject<Dictionary<string, UpgradeFileInfo>>(oldfileList);
- foreach (var newfile in dic)
- {
- if (newfile.Value.Type == UpgradeOperateType.Add)
- {
- if (!oldDic.Keys.Contains(newfile.Key))
- {
- oldDic.Add(newfile.Key, newfile.Value);
- }
- else
- {
- oldDic[newfile.Key] = newfile.Value;
- }
- }
- else
- {
- if (oldDic.Keys.Contains(newfile.Key))
- {
- oldDic.Remove(newfile.Key);
- }
- }
- }
- OnUpload(100);
- var fileList = JsonConvert.SerializeObject(oldDic);
- File.WriteAllText(_fileListPath, fileList);
- }
- }
- RestartClient();
- }
-
- /// <summary>
- /// 版本更新下载文件(UFile)
- /// </summary>
- /// <param name="dic"></param>
- /// <param name="progressCallback"></param>
- /// <param name="finishFileCount"></param>
- /// <param name="totalFileProgress"></param>
- /// <param name="works"></param>
- /// <returns></returns>
- private int AddFilesInStepUFileStorage(Dictionary<string, UpgradeFileInfo> dic, Action<double> progressCallback, int finishFileCount, float totalFileProgress)
- {
- var updateTempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UpdateTemp");
- Directory.CreateDirectory(updateTempFolder);
- var downloadTempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DownloadTemp");
- Directory.CreateDirectory(downloadTempFolder);
- if (dic != null && dic.Count > 0)
- {
- var allUpgradeFiles = dic.Where(f => f.Value.Type == UpgradeOperateType.Add && f.Key.IndexOf("vCloud.Windows.ForceUpgrade.exe") == -1).ToArray();
- if (allUpgradeFiles != null && allUpgradeFiles.Length > 0)
- {
- var ufiles = allUpgradeFiles.Select(f => new RootPathFileInfo
- {
- RootPath = f.Key + ".zip",
- UFileName = f.Value.Md5Code + ".zip"
- }).ToList();
- var success = _uFileStorageHelper.DownloadFiles(downloadTempFolder, StorageNodeType.UpgradeStorageCDN, ufiles, progressCallback);
- if (success)
- {
- var zipFiles = Directory.GetFiles(downloadTempFolder, "*.zip", SearchOption.AllDirectories);
- foreach (var file in ufiles)
- {
- if (file != null && !string.IsNullOrWhiteSpace(file.RootPath))
- {
- var realFileName = Path.GetFileName(file.RootPath.Substring(0, file.RootPath.LastIndexOf('.')));
- string inPath = file.RootPath.Replace("RootPath", downloadTempFolder);
- string outPath = Path.GetDirectoryName(file.RootPath.Replace("RootPath", updateTempFolder));
- Directory.CreateDirectory(outPath);
- DeZip(inPath, outPath);
- Dispatcher.Invoke(() =>
- {
- finishFileCount++;
- });
- }
- }
- Directory.Delete(downloadTempFolder, true);
- progressCallback?.Invoke(100);
- }
- }
- }
- return finishFileCount;
- }
- /// <summary>
- /// 解压文件
- /// </summary>
- /// <param name="filePath"></param>
- /// <param name="outPath"></param>
- private void DeZip(string filePath, string outPath)
- {
- using (Process ps = new Process())
- {
- ps.StartInfo.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Commons", "7z", "7za.exe");
- ps.StartInfo.Arguments = $"x \"{filePath}\" -o\"{outPath}\" -y";
- ps.StartInfo.UseShellExecute = false;
- ps.StartInfo.RedirectStandardOutput = false;
- ps.StartInfo.RedirectStandardInput = false;
- ps.StartInfo.CreateNoWindow = true;
- ps.StartInfo.Verb = "runas";
- ps.Start();
- ps.WaitForExit(15000);
- }
- }
- /// <summary>
- /// 关闭所有客户端
- /// </summary>
- private void KillVcloudClientProcess()
- {
- var mainProcesses = Process.GetProcessesByName("vCloud.Windows");
- foreach (var process in mainProcesses)
- {
- process.Kill();
- }
- var registerProcesses = Process.GetProcessesByName("vCloud.Windows.Register");
- foreach (var process in registerProcesses)
- {
- process.Kill();
- }
- var videoManagementProcesses = Process.GetProcessesByName("vCloud.Video.Management");
- foreach (var process in videoManagementProcesses)
- {
- process.Kill();
- }
- var reportProcesses = Process.GetProcessesByName("ReportTemplateDesigner");
- foreach (var process in reportProcesses)
- {
- process.Kill();
- }
- }
- /// <summary>
- /// 重启客户端
- /// </summary>
- private void RestartClient(bool moveTempFolder = true)
- {
- if (moveTempFolder)
- {
- if (Directory.Exists($"{ AppDomain.CurrentDomain.BaseDirectory}\\UpdateTemp"))
- {
- Directory.Delete($"{ AppDomain.CurrentDomain.BaseDirectory}\\UpdateTemp", true);
- }
- //if (Directory.Exists($"{ AppDomain.CurrentDomain.BaseDirectory}\\DownloadTemp"))
- //{
- // Directory.Delete($"{ AppDomain.CurrentDomain.BaseDirectory}\\DownloadTemp", true);
- //}
- }
- var clientPath = AppDomain.CurrentDomain.BaseDirectory + "vCloud.Windows.exe";
- Process.Start(clientPath);
- Thread.Sleep(100);
- Environment.Exit(0);
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="srcFolder"></param>
- /// <param name="targetFolder"></param>
- private void MoveFiles(string srcFolder, string targetFolder)
- {
- Directory.CreateDirectory(targetFolder);
- var files = Directory.GetFiles(srcFolder);
- foreach (var file in files)
- {
- File.Copy(file, file.Replace(srcFolder, targetFolder), true);
- }
- var dirs = Directory.GetDirectories(srcFolder);
- foreach (var dir in dirs)
- {
- MoveFiles(dir, dir.Replace(srcFolder, targetFolder));
- }
- }
- private void FilterWhiteList(Dictionary<string, UpgradeFileInfo> dic)
- {
- //过滤掉删除项暂时只同步新增文件
- var fileArray = dic.Where(f => f.Value.Type == UpgradeOperateType.Remove).ToArray();
- foreach (var fileInfo in fileArray)
- {
- dic.Remove(fileInfo.Key);
- }
- var whiteDic = dic.ToArray();
- foreach (var fileInfo in whiteDic)
- {
- if (WhiteList(fileInfo.Key))
- {
- dic.Remove(fileInfo.Key);
- }
- }
- }
- /// <summary>
- /// 白名单
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- private bool WhiteList(string key)
- {
- if (Regex.IsMatch(key, "RootPath[\\\\]FileList.json"))
- {
- return true;
- }
- if (Regex.IsMatch(key, "RootPath[\\\\]UpdateTemp[\\\\/].*"))
- {
- return true;
- }
- if (Regex.IsMatch(key, ".*UserCommonSetting.conf.*"))
- {
- return true;
- }
- if (Regex.IsMatch(key, ".*vCloud.Windows.Upgrade.*"))
- {
- return true;
- }
- if (Regex.IsMatch(key, ".*Commons[\\\\/]CefSharp[\\\\/](x86|x64).*"))
- {
- return true;
- }
- if (Regex.IsMatch(key, ".*Commons[\\\\/]Emgu[\\\\/](x86|x64).*"))
- {
- return true;
- }
- if (Regex.IsMatch(key, "RootPath[\\\\]Newtonsoft.Json.*") || Regex.IsMatch(key, "RootPath[\\\\]SharpCompress.dll"))
- {
- return true;
- }
- if (Regex.IsMatch(key, "RootPath[\\\\]debug.log") || Regex.IsMatch(key, "RootPath[\\\\]InstallLog.txt") || Regex.IsMatch(key, "RootPath[\\\\]UpgradeLog.txt"))
- {
- return true;
- }
- return false;
- }
- private void OnUpload(double progress)
- {
- Dispatcher.Invoke(() => {
- InstallProcess.Content = progress + "%";
- var addProgressValue = (progress - _currentProcess) * _pie;
- if (addProgressValue > 0)
- {
- ProcessImage.Width -= (ProcessImage.Width > addProgressValue ? addProgressValue : ProcessImage.Width);
- _leftMargin -= addProgressValue;
- ProcessImage.Margin = new Thickness(14, 32, _leftMargin, 30);
- _currentProcess = progress;
- }
- if (progress == 100)
- {
- InstallContent.Content = App.GetFinishShow;
- }
- });
- Thread.Sleep(1);
- }
- private static string GetJson(Stream stream)
- {
- using (stream)
- {
- using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))
- {
- return streamReader.ReadToEnd();
- }
- }
- }
- /// <summary>
- /// 清除空文件夹
- /// </summary>
- /// <param name="folder"></param>
- /// <returns></returns>
- private static bool DelEmptyFolder(string folder)
- {
- bool allChildFolderIsDelete = true;
- var files = Directory.GetFiles(folder);
- var childFolders = Directory.GetDirectories(folder);
- if (files.Length > 0)
- {
- if (childFolders.Length > 0)
- {
- foreach (var childFolder in childFolders)
- {
- if (DelEmptyFolder(childFolder) == false)
- {
- allChildFolderIsDelete = false;
- }
- }
- }
- return false;
- }
- else if (childFolders.Length > 0)
- {
- foreach (var childFolder in childFolders)
- {
- if (DelEmptyFolder(childFolder) == false)
- {
- allChildFolderIsDelete = false;
- }
- }
- }
- else
- {
- Directory.Delete(folder, true);
- return true;
- }
- if (allChildFolderIsDelete && Directory.Exists(folder))
- {
- Directory.Delete(folder, true);
- return true;
- }
- return false;
- }
- private Version GetNewPackageVersion(string serverUrlValue)
- {
- try
- {
- using (var leafAgency = new SimpleLeafAgency(serverUrlValue))
- {
- using (var getUpgradeVersionRequest = MessagePool.GetMessage<GetUpgradeVersionRequest>())
- {
- getUpgradeVersionRequest.Platform = UpgradePlatform.PC;
- getUpgradeVersionRequest.Type = UpgradeType.Client;
- var result = leafAgency.AgencySend(getUpgradeVersionRequest);
- var versionResult = GetUpgradeVersionResult.Convert(result);
- if (versionResult != null)
- {
- return versionResult.Version;
- }
- }
- }
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"Get package info error:{ex}");
- }
- return null;
- }
- private void Label_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
- {
- if (_isDownloadFinish == false)
- {
- Environment.Exit(0);
- }
- }
- }
- }
|