FisTools.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO.Compression;
  4. namespace FisTools
  5. {
  6. public class FFmpegException : Exception
  7. {
  8. public FFmpegException(int exitCode, Exception innerException = null)
  9. : base($"Exit Code: {exitCode}.\nSee FFmpeg Log for more info.", innerException) { }
  10. }
  11. public class FFmpegService
  12. {
  13. private string _ffmpegPath = "ffmpeg";
  14. public void SetFFmpegPath(string ffmpegPath)
  15. {
  16. _ffmpegPath = ffmpegPath;
  17. }
  18. public void StartFFmpeg(out Process process, string arguments)
  19. {
  20. process = new Process
  21. {
  22. StartInfo =
  23. {
  24. FileName = _ffmpegPath,
  25. Arguments = arguments,
  26. UseShellExecute = false,
  27. Verb = "runas",
  28. CreateNoWindow = true,
  29. RedirectStandardError = true,
  30. RedirectStandardInput = true
  31. },
  32. EnableRaisingEvents = true
  33. };
  34. process.Start();
  35. process.BeginErrorReadLine();
  36. }
  37. public void ForceCloseFFmpegIfStillAlive()
  38. {
  39. var fmpegProcess = Process.GetProcessesByName("ffmpeg");
  40. foreach (var f in fmpegProcess)
  41. {
  42. f.Kill();
  43. }
  44. }
  45. }
  46. public class LoaderCenter
  47. {
  48. private string _processName=string.Empty;
  49. public void StartProcessWithFileName(string filePath, string arguments,string processName)
  50. {
  51. _processName = processName;
  52. var process = new Process
  53. {
  54. StartInfo =
  55. {
  56. FileName = filePath,
  57. Arguments = arguments,
  58. UseShellExecute = false,
  59. Verb = "runas",
  60. CreateNoWindow = true,
  61. RedirectStandardError = true,
  62. RedirectStandardInput = true
  63. },
  64. };
  65. process.Start();
  66. }
  67. public void StartProcessWithWorkingDirectory(string filePath,string workingDirectory)
  68. {
  69. var process = new Process
  70. {
  71. StartInfo =
  72. {
  73. FileName = filePath,
  74. WorkingDirectory = workingDirectory,
  75. UseShellExecute = false,
  76. CreateNoWindow = true,
  77. RedirectStandardOutput = true,
  78. Verb = "runas",
  79. },
  80. };
  81. process.Start();
  82. }
  83. /// <summary>
  84. /// 校验APP是否已存在,已存在则直接唤起
  85. /// </summary>
  86. /// <returns></returns>
  87. public bool CheckAppIsInvalid(Action<string> logger)
  88. {
  89. var id = Process.GetCurrentProcess().Id;
  90. Process[] processesByNames = Process.GetProcessesByName("fis");
  91. bool appInvalid=false;
  92. foreach (var pn in processesByNames)
  93. {
  94. //如果存在同名但不同id的进程
  95. if (pn.Id != id)
  96. {
  97. logger.Invoke("Got another fis process");
  98. var threads = pn.Threads;
  99. foreach (ProcessThread t in threads)
  100. {
  101. logger.Invoke("Exist process status is:");
  102. logger.Invoke(t.ThreadState.ToString());
  103. var appHangup = t.ThreadState == System.Diagnostics.ThreadState.Unknown
  104. || t.ThreadState == System.Diagnostics.ThreadState.Terminated
  105. || t.ThreadState == System.Diagnostics.ThreadState.Wait;
  106. if (appHangup)
  107. {
  108. logger.Invoke("Kill the existing hang up process");
  109. //如果存在挂起线程,则杀死
  110. KillProcessWithGivenName("fis", false);
  111. }
  112. if (t.ThreadState == System.Diagnostics.ThreadState.Running)
  113. {
  114. appInvalid = true;
  115. }
  116. }
  117. }
  118. }
  119. return appInvalid;
  120. }
  121. /// <summary>
  122. /// 打开守护进程
  123. /// </summary>
  124. public void OpenFlyinsonoDaemon()
  125. {
  126. var process = Process.GetProcessesByName("FlyinsonoDaemon.exe").FirstOrDefault();
  127. if (process == null)
  128. {
  129. var flyinsonoDaemonPath = "C:\\vinno\\daemon\\FlyinsonoDaemon.exe";
  130. ToolManager.Instance.LoaderCenter.StartProcessDirectly(flyinsonoDaemonPath);
  131. }
  132. }
  133. public void StartProcessDirectly(string filePath)
  134. {
  135. var process = new Process
  136. {
  137. StartInfo =
  138. {
  139. FileName = filePath,
  140. UseShellExecute = false,
  141. Verb = "runas",
  142. CreateNoWindow = true,
  143. RedirectStandardError = true,
  144. },
  145. EnableRaisingEvents = true
  146. };
  147. process.Start();
  148. }
  149. public void StartProcessWithUI(string filePath)
  150. {
  151. var process = new Process
  152. {
  153. StartInfo =
  154. {
  155. FileName = filePath,
  156. },
  157. };
  158. process.Start();
  159. }
  160. public void ForceCloseIfStillAlive()
  161. {
  162. if (!string.IsNullOrEmpty(_processName))
  163. {
  164. var fmpegProcess = Process.GetProcessesByName(_processName);
  165. foreach (var f in fmpegProcess)
  166. {
  167. f.Kill();
  168. }
  169. }
  170. }
  171. public void KillProcessWithGivenName(string processName,bool killSelf=true)
  172. {
  173. var processes = Process.GetProcessesByName(processName);
  174. foreach (Process process in processes)
  175. {
  176. if (process.ProcessName == processName)
  177. {
  178. if (killSelf)
  179. {
  180. process.Kill();
  181. process.WaitForExit();
  182. }
  183. else if(process.Id != Process.GetCurrentProcess().Id)
  184. {
  185. process.Kill();
  186. process.WaitForExit();
  187. }
  188. }
  189. }
  190. }
  191. }
  192. // public class AutoStartHelper
  193. // {
  194. // /// <summary>
  195. // /// App开机自启动 Reg key
  196. // /// </summary>
  197. // private const string AppAutoStartRegistryKey = "FisAutoStart";
  198. // /// <summary>
  199. // /// 当前用户注册表开启启动路径
  200. // /// </summary>
  201. // private const string RegPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
  202. // /// <summary>
  203. // /// 设置APP开机自启动
  204. // /// </summary>
  205. // /// <returns></returns>
  206. // public bool SetAppAutoStart()
  207. // {
  208. // ///默认选择Release下的loader.exe
  209. // var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "loader.exe");
  210. //#if DEBUG
  211. // ///Debug模式下启动fis.exe
  212. // path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fis.exe");
  213. //#endif
  214. // return SetAutoStartByPath(path, AppAutoStartRegistryKey);
  215. // }
  216. // /// <summary>
  217. // /// 取消APP开机自启动
  218. // /// </summary>
  219. // /// <returns></returns>
  220. // public bool AbortAppAutoStart()
  221. // {
  222. // return AbortAutoByRegKey(AppAutoStartRegistryKey);
  223. // }
  224. // /// <summary>
  225. // /// 根据指定的key取消开机自启动
  226. // /// </summary>
  227. // /// <param name="regkey"></param>
  228. // /// <returns></returns>
  229. // public bool AbortAutoByRegKey(string regkey)
  230. // {
  231. // try
  232. // {
  233. // var currentUserRegKey = Registry.CurrentUser;
  234. // var startUpKey = currentUserRegKey.CreateSubKey(RegPath);
  235. // startUpKey.DeleteValue(regkey, false);
  236. // startUpKey.Close();
  237. // currentUserRegKey.Close();
  238. // return true;
  239. // }
  240. // catch (Exception ex)
  241. // {
  242. // return false;
  243. // }
  244. // }
  245. // /// <summary>
  246. // /// 根据给定开机自启动文件路径和注册表的key设置开启自启动
  247. // /// </summary>
  248. // /// <param name="regkey"></param>
  249. // /// <returns></returns>
  250. // public bool SetAutoStartByPath(string path, string regKey)
  251. // {
  252. // try
  253. // {
  254. // var currentUserKey = Registry.CurrentUser;
  255. // var startUpKey = currentUserKey.CreateSubKey(RegPath);
  256. // startUpKey.SetValue(regKey, path);
  257. // startUpKey.Close();
  258. // currentUserKey.Close();
  259. // return true;
  260. // }
  261. // catch (Exception)
  262. // {
  263. // return false;
  264. // }
  265. // }
  266. // }
  267. public class UpgradeCenter
  268. {
  269. private int _totalEntrysCount;
  270. private int _finishedCount;
  271. private const int ExpirationCount = 90;
  272. private Action<double>? _onProgressChanged;
  273. public void ExecutePartUpgrade(Action<string> logger)
  274. {
  275. logger.Invoke($"Part upgrade");
  276. ToolManager.Instance.LoaderCenter.KillProcessWithGivenName("fis");
  277. var currentDir = AppDomain.CurrentDomain.BaseDirectory;
  278. var fisDir = Directory.GetParent(currentDir)!.Parent!.FullName;
  279. logger($"Fis dir is {fisDir}");
  280. var webZipPath = Path.Combine(fisDir, "App", "flyinsono");
  281. var updateCacheDir = Path.Combine(fisDir, "UpgradCache");
  282. var filesToCopy = Directory.GetFiles(updateCacheDir);
  283. foreach (var file in filesToCopy)
  284. {
  285. var ext = Path.GetExtension(file);
  286. if (ext != ".zip")
  287. {
  288. logger($"Skipped none zip file for part upgrade");
  289. continue;
  290. }
  291. var fileName = Path.GetFileName(file);
  292. var fileDest = Path.Combine(webZipPath, fileName);
  293. File.Copy(file, fileDest, true);
  294. File.Delete(file);
  295. }
  296. //var fisFileName = Path.Combine(fisDir, "fis.exe");
  297. //ToolManager.Instance.LoaderCenter.StartProcessDirectly(fisFileName);
  298. }
  299. public void ExecuteFullUpgrade(Action<string> logger, Action<double>? onProgressChanged = null)
  300. {
  301. logger.Invoke($"Full upgrade");
  302. _onProgressChanged = onProgressChanged;
  303. ToolManager.Instance.LoaderCenter.KillProcessWithGivenName("fis");
  304. var currentDir = AppDomain.CurrentDomain.BaseDirectory;
  305. var fisDir = Directory.GetParent(currentDir)!.Parent!.FullName;
  306. logger($"Fis dir is {fisDir}");
  307. var filesToCopy = Directory.GetFiles(currentDir);
  308. foreach (var file in filesToCopy)
  309. {
  310. var ext = Path.GetExtension(file);
  311. logger($"File name {file}");
  312. if (ext != ".zip")
  313. {
  314. logger($"None zip file skipped {file}");
  315. continue;
  316. }
  317. var fileName = Path.GetFileName(file);
  318. if (!fileName.Contains("fis_package"))
  319. {
  320. logger($"Zip file skipped {file}");
  321. continue;
  322. }
  323. logger($"Do extract {file} begin");
  324. var fileNameWithoutExt = Path.GetFileNameWithoutExtension(file);
  325. var filePathToSkip = $"{fileNameWithoutExt}/";
  326. logger("Begin to extract");
  327. Task.Run(() =>
  328. {
  329. var waitCount = 0;
  330. while (true)
  331. {
  332. waitCount++;
  333. Thread.Sleep(1000);
  334. if (waitCount == 90)
  335. {
  336. _onProgressChanged?.Invoke(2.0);
  337. break;
  338. }
  339. var progress = Math.Round((double)_finishedCount / (double)_totalEntrysCount, 2);
  340. _onProgressChanged?.Invoke(progress);
  341. if (progress == 1)
  342. {
  343. break;
  344. }
  345. }
  346. });
  347. using (ZipArchive archive = ZipFile.OpenRead(file))
  348. {
  349. try
  350. {
  351. var entrys = archive.Entries;
  352. _totalEntrysCount = entrys.Count;
  353. var filesEntries = entrys.Where(c => c.Name != "");
  354. foreach (ZipArchiveEntry fileEntry in filesEntries)
  355. {
  356. var entrySubPath = fileEntry.FullName.Replace(filePathToSkip, "");
  357. string entryPath = Path.Combine(fisDir, entrySubPath);
  358. if (fileEntry.Name.Contains("libHarfBuzzSharp") || fileEntry.Name.Contains("libSkiaSharp"))
  359. {
  360. _finishedCount++;
  361. continue;
  362. }
  363. try
  364. {
  365. CreateDirWithFileName(fileEntry.FullName, fisDir);
  366. fileEntry.ExtractToFile(entryPath, true);
  367. }
  368. catch (Exception ex)
  369. {
  370. logger($"Extract single file error {ex}");
  371. }
  372. logger($"{fileEntry.FullName} extract success.");
  373. _finishedCount++;
  374. }
  375. }
  376. catch (Exception ex)
  377. {
  378. logger($"Extract error {ex}");
  379. }
  380. }
  381. logger("End to extract");
  382. logger($"Do extract {file} end");
  383. logger($"Do delete {file} begin");
  384. File.Delete(file);
  385. logger($"Do delete {file} end");
  386. }
  387. logger($"Do restart begin");
  388. var fisFileName = Path.Combine(fisDir, "fis.exe");
  389. if (_onProgressChanged == null)
  390. {
  391. ToolManager.Instance.LoaderCenter.StartProcessDirectly(fisFileName);
  392. }
  393. logger($"Do restart end");
  394. }
  395. private void CreateDirWithFileName(string fullName, string fisDir)
  396. {
  397. var filePathElements = fullName.Split("/");
  398. if (filePathElements.Count() == 1)
  399. {
  400. return;
  401. }
  402. var fullpath = "";
  403. foreach (var filePath in filePathElements)
  404. {
  405. if (filePath.Contains("."))
  406. {
  407. continue;
  408. }
  409. fullpath = Path.Combine(fullpath, filePath);
  410. var path = Path.Combine(fisDir, fullpath);
  411. if (!Directory.Exists(path))
  412. {
  413. Directory.CreateDirectory(path);
  414. }
  415. }
  416. }
  417. }
  418. public class ToolManager
  419. {
  420. private ToolManager()
  421. {
  422. }
  423. private FFmpegService _ffmpegService;
  424. private LoaderCenter _loaderCenter;
  425. //private AutoStartHelper _autoStartHelper;
  426. private UpgradeCenter _upgradeCenter;
  427. static private ToolManager _instance;
  428. public static ToolManager Instance
  429. {
  430. get{
  431. if (_instance == null)
  432. {
  433. _instance = new ToolManager();
  434. }
  435. return _instance;
  436. }
  437. }
  438. public LoaderCenter LoaderCenter
  439. {
  440. get {
  441. if (_loaderCenter == null)
  442. {
  443. _loaderCenter = new LoaderCenter();
  444. }
  445. return _loaderCenter;
  446. }
  447. }
  448. public FFmpegService FFmpegService
  449. {
  450. get
  451. {
  452. if (_ffmpegService == null)
  453. {
  454. _ffmpegService = new FFmpegService();
  455. }
  456. return _ffmpegService;
  457. }
  458. }
  459. public UpgradeCenter UpgradeCenter
  460. {
  461. get
  462. {
  463. if (_upgradeCenter == null)
  464. {
  465. _upgradeCenter = new UpgradeCenter();
  466. }
  467. return _upgradeCenter;
  468. }
  469. }
  470. //public AutoStartHelper AutoStartHelper
  471. //{
  472. // get {
  473. // if (_autoStartHelper == null)
  474. // {
  475. // _autoStartHelper = new AutoStartHelper();
  476. // }
  477. // return _autoStartHelper;
  478. // }
  479. //}
  480. }
  481. }