Updater.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. using Avalonia.Controls;
  2. using Avalonia.Threading;
  3. using FluentAvalonia.UI.Controls;
  4. using ICSharpCode.SharpZipLib.GZip;
  5. using ICSharpCode.SharpZipLib.Tar;
  6. using ICSharpCode.SharpZipLib.Zip;
  7. using Newtonsoft.Json.Linq;
  8. using Ryujinx.Ava;
  9. using Ryujinx.Ava.Common.Locale;
  10. using Ryujinx.Ava.UI.Helpers;
  11. using Ryujinx.Common;
  12. using Ryujinx.Common.Logging;
  13. using Ryujinx.Ui.Common.Helper;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Diagnostics;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Net;
  20. using System.Net.Http;
  21. using System.Net.NetworkInformation;
  22. using System.Runtime.CompilerServices;
  23. using System.Runtime.InteropServices;
  24. using System.Text;
  25. using System.Threading;
  26. using System.Threading.Tasks;
  27. namespace Ryujinx.Modules
  28. {
  29. internal static class Updater
  30. {
  31. private const string GitHubApiURL = "https://api.github.com";
  32. private static readonly string HomeDir = AppDomain.CurrentDomain.BaseDirectory;
  33. private static readonly string UpdateDir = Path.Combine(Path.GetTempPath(), "Ryujinx", "update");
  34. private static readonly string UpdatePublishDir = Path.Combine(UpdateDir, "publish");
  35. private static readonly int ConnectionCount = 4;
  36. private static string _buildVer;
  37. private static string _platformExt;
  38. private static string _buildUrl;
  39. private static long _buildSize;
  40. private static bool _updateSuccessful;
  41. private static bool _running;
  42. private static readonly string[] WindowsDependencyDirs = Array.Empty<string>();
  43. public static async Task BeginParse(Window mainWindow, bool showVersionUpToDate)
  44. {
  45. if (_running)
  46. {
  47. return;
  48. }
  49. _running = true;
  50. // Detect current platform
  51. if (OperatingSystem.IsMacOS())
  52. {
  53. _platformExt = "osx_x64.zip";
  54. }
  55. else if (OperatingSystem.IsWindows())
  56. {
  57. _platformExt = "win_x64.zip";
  58. }
  59. else if (OperatingSystem.IsLinux())
  60. {
  61. _platformExt = "linux_x64.tar.gz";
  62. }
  63. Version newVersion;
  64. Version currentVersion;
  65. try
  66. {
  67. currentVersion = Version.Parse(Program.Version);
  68. }
  69. catch
  70. {
  71. Logger.Error?.Print(LogClass.Application, "Failed to convert the current Ryujinx version!");
  72. Dispatcher.UIThread.Post(async () =>
  73. {
  74. await ContentDialogHelper.CreateWarningDialog(
  75. LocaleManager.Instance[LocaleKeys.DialogUpdaterConvertFailedMessage],
  76. LocaleManager.Instance[LocaleKeys.DialogUpdaterCancelUpdateMessage]);
  77. });
  78. _running = false;
  79. return;
  80. }
  81. // Get latest version number from GitHub API
  82. try
  83. {
  84. using HttpClient jsonClient = ConstructHttpClient();
  85. string buildInfoURL = $"{GitHubApiURL}/repos/{ReleaseInformation.ReleaseChannelOwner}/{ReleaseInformation.ReleaseChannelRepo}/releases/latest";
  86. string fetchedJson = await jsonClient.GetStringAsync(buildInfoURL);
  87. JObject jsonRoot = JObject.Parse(fetchedJson);
  88. JToken assets = jsonRoot["assets"];
  89. _buildVer = (string)jsonRoot["name"];
  90. foreach (JToken asset in assets)
  91. {
  92. string assetName = (string)asset["name"];
  93. string assetState = (string)asset["state"];
  94. string downloadURL = (string)asset["browser_download_url"];
  95. if (assetName.StartsWith("test-ava-ryujinx") && assetName.EndsWith(_platformExt))
  96. {
  97. _buildUrl = downloadURL;
  98. if (assetState != "uploaded")
  99. {
  100. if (showVersionUpToDate)
  101. {
  102. Dispatcher.UIThread.Post(async () =>
  103. {
  104. await ContentDialogHelper.CreateUpdaterInfoDialog(LocaleManager.Instance[LocaleKeys.DialogUpdaterAlreadyOnLatestVersionMessage], "");
  105. });
  106. }
  107. _running = false;
  108. return;
  109. }
  110. break;
  111. }
  112. }
  113. // If build not done, assume no new update are available.
  114. if (_buildUrl is null)
  115. {
  116. if (showVersionUpToDate)
  117. {
  118. Dispatcher.UIThread.Post(async () =>
  119. {
  120. await ContentDialogHelper.CreateUpdaterInfoDialog(LocaleManager.Instance[LocaleKeys.DialogUpdaterAlreadyOnLatestVersionMessage], "");
  121. });
  122. }
  123. _running = false;
  124. return;
  125. }
  126. }
  127. catch (Exception exception)
  128. {
  129. Logger.Error?.Print(LogClass.Application, exception.Message);
  130. Dispatcher.UIThread.Post(async () =>
  131. {
  132. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogUpdaterFailedToGetVersionMessage]);
  133. });
  134. _running = false;
  135. return;
  136. }
  137. try
  138. {
  139. newVersion = Version.Parse(_buildVer);
  140. }
  141. catch
  142. {
  143. Logger.Error?.Print(LogClass.Application, "Failed to convert the received Ryujinx version from Github!");
  144. Dispatcher.UIThread.Post(async () =>
  145. {
  146. await ContentDialogHelper.CreateWarningDialog(
  147. LocaleManager.Instance[LocaleKeys.DialogUpdaterConvertFailedGithubMessage],
  148. LocaleManager.Instance[LocaleKeys.DialogUpdaterCancelUpdateMessage]);
  149. });
  150. _running = false;
  151. return;
  152. }
  153. if (newVersion <= currentVersion)
  154. {
  155. if (showVersionUpToDate)
  156. {
  157. Dispatcher.UIThread.Post(async () =>
  158. {
  159. await ContentDialogHelper.CreateUpdaterInfoDialog(LocaleManager.Instance[LocaleKeys.DialogUpdaterAlreadyOnLatestVersionMessage], "");
  160. });
  161. }
  162. _running = false;
  163. return;
  164. }
  165. // Fetch build size information to learn chunk sizes.
  166. using (HttpClient buildSizeClient = ConstructHttpClient())
  167. {
  168. try
  169. {
  170. buildSizeClient.DefaultRequestHeaders.Add("Range", "bytes=0-0");
  171. HttpResponseMessage message = await buildSizeClient.GetAsync(new Uri(_buildUrl), HttpCompletionOption.ResponseHeadersRead);
  172. _buildSize = message.Content.Headers.ContentRange.Length.Value;
  173. }
  174. catch (Exception ex)
  175. {
  176. Logger.Warning?.Print(LogClass.Application, ex.Message);
  177. Logger.Warning?.Print(LogClass.Application, "Couldn't determine build size for update, using single-threaded updater");
  178. _buildSize = -1;
  179. }
  180. }
  181. Dispatcher.UIThread.Post(async () =>
  182. {
  183. // Show a message asking the user if they want to update
  184. var shouldUpdate = await ContentDialogHelper.CreateChoiceDialog(
  185. LocaleManager.Instance[LocaleKeys.RyujinxUpdater],
  186. LocaleManager.Instance[LocaleKeys.RyujinxUpdaterMessage],
  187. $"{Program.Version} -> {newVersion}");
  188. if (shouldUpdate)
  189. {
  190. UpdateRyujinx(mainWindow, _buildUrl);
  191. }
  192. else
  193. {
  194. _running = false;
  195. }
  196. });
  197. }
  198. private static HttpClient ConstructHttpClient()
  199. {
  200. HttpClient result = new();
  201. // Required by GitHub to interact with APIs.
  202. result.DefaultRequestHeaders.Add("User-Agent", "Ryujinx-Updater/1.0.0");
  203. return result;
  204. }
  205. private static async void UpdateRyujinx(Window parent, string downloadUrl)
  206. {
  207. _updateSuccessful = false;
  208. // Empty update dir, although it shouldn't ever have anything inside it
  209. if (Directory.Exists(UpdateDir))
  210. {
  211. Directory.Delete(UpdateDir, true);
  212. }
  213. Directory.CreateDirectory(UpdateDir);
  214. string updateFile = Path.Combine(UpdateDir, "update.bin");
  215. TaskDialog taskDialog = new()
  216. {
  217. Header = LocaleManager.Instance[LocaleKeys.RyujinxUpdater],
  218. SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterDownloading],
  219. IconSource = new SymbolIconSource { Symbol = Symbol.Download },
  220. Buttons = { },
  221. ShowProgressBar = true,
  222. XamlRoot = parent
  223. };
  224. taskDialog.Opened += (s, e) =>
  225. {
  226. if (_buildSize >= 0)
  227. {
  228. DoUpdateWithMultipleThreads(taskDialog, downloadUrl, updateFile);
  229. }
  230. else
  231. {
  232. DoUpdateWithSingleThread(taskDialog, downloadUrl, updateFile);
  233. }
  234. };
  235. await taskDialog.ShowAsync(true);
  236. if (_updateSuccessful)
  237. {
  238. var shouldRestart = await ContentDialogHelper.CreateChoiceDialog(LocaleManager.Instance[LocaleKeys.RyujinxUpdater],
  239. LocaleManager.Instance[LocaleKeys.DialogUpdaterCompleteMessage],
  240. LocaleManager.Instance[LocaleKeys.DialogUpdaterRestartMessage]);
  241. if (shouldRestart)
  242. {
  243. string ryuName = Path.GetFileName(Environment.ProcessPath);
  244. string ryuExe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ryuName);
  245. if (!Path.Exists(ryuExe))
  246. {
  247. ryuExe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, OperatingSystem.IsWindows() ? "Ryujinx.exe" : "Ryujinx");
  248. }
  249. Process.Start(ryuExe, CommandLineState.Arguments);
  250. Environment.Exit(0);
  251. }
  252. }
  253. }
  254. private static void DoUpdateWithMultipleThreads(TaskDialog taskDialog, string downloadUrl, string updateFile)
  255. {
  256. // Multi-Threaded Updater
  257. long chunkSize = _buildSize / ConnectionCount;
  258. long remainderChunk = _buildSize % ConnectionCount;
  259. int completedRequests = 0;
  260. int totalProgressPercentage = 0;
  261. int[] progressPercentage = new int[ConnectionCount];
  262. List<byte[]> list = new(ConnectionCount);
  263. List<WebClient> webClients = new(ConnectionCount);
  264. for (int i = 0; i < ConnectionCount; i++)
  265. {
  266. list.Add(Array.Empty<byte>());
  267. }
  268. for (int i = 0; i < ConnectionCount; i++)
  269. {
  270. #pragma warning disable SYSLIB0014
  271. // TODO: WebClient is obsolete and need to be replaced with a more complex logic using HttpClient.
  272. using WebClient client = new();
  273. #pragma warning restore SYSLIB0014
  274. webClients.Add(client);
  275. if (i == ConnectionCount - 1)
  276. {
  277. client.Headers.Add("Range", $"bytes={chunkSize * i}-{(chunkSize * (i + 1) - 1) + remainderChunk}");
  278. }
  279. else
  280. {
  281. client.Headers.Add("Range", $"bytes={chunkSize * i}-{chunkSize * (i + 1) - 1}");
  282. }
  283. client.DownloadProgressChanged += (_, args) =>
  284. {
  285. int index = (int)args.UserState;
  286. Interlocked.Add(ref totalProgressPercentage, -1 * progressPercentage[index]);
  287. Interlocked.Exchange(ref progressPercentage[index], args.ProgressPercentage);
  288. Interlocked.Add(ref totalProgressPercentage, args.ProgressPercentage);
  289. taskDialog.SetProgressBarState(totalProgressPercentage / ConnectionCount, TaskDialogProgressState.Normal);
  290. };
  291. client.DownloadDataCompleted += (_, args) =>
  292. {
  293. int index = (int)args.UserState;
  294. if (args.Cancelled)
  295. {
  296. webClients[index].Dispose();
  297. taskDialog.Hide();
  298. return;
  299. }
  300. list[index] = args.Result;
  301. Interlocked.Increment(ref completedRequests);
  302. if (Equals(completedRequests, ConnectionCount))
  303. {
  304. byte[] mergedFileBytes = new byte[_buildSize];
  305. for (int connectionIndex = 0, destinationOffset = 0; connectionIndex < ConnectionCount; connectionIndex++)
  306. {
  307. Array.Copy(list[connectionIndex], 0, mergedFileBytes, destinationOffset, list[connectionIndex].Length);
  308. destinationOffset += list[connectionIndex].Length;
  309. }
  310. File.WriteAllBytes(updateFile, mergedFileBytes);
  311. try
  312. {
  313. InstallUpdate(taskDialog, updateFile);
  314. }
  315. catch (Exception e)
  316. {
  317. Logger.Warning?.Print(LogClass.Application, e.Message);
  318. Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater.");
  319. DoUpdateWithSingleThread(taskDialog, downloadUrl, updateFile);
  320. return;
  321. }
  322. }
  323. };
  324. try
  325. {
  326. client.DownloadDataAsync(new Uri(downloadUrl), i);
  327. }
  328. catch (WebException ex)
  329. {
  330. Logger.Warning?.Print(LogClass.Application, ex.Message);
  331. Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater.");
  332. foreach (WebClient webClient in webClients)
  333. {
  334. webClient.CancelAsync();
  335. }
  336. DoUpdateWithSingleThread(taskDialog, downloadUrl, updateFile);
  337. return;
  338. }
  339. }
  340. }
  341. private static void DoUpdateWithSingleThreadWorker(TaskDialog taskDialog, string downloadUrl, string updateFile)
  342. {
  343. using HttpClient client = new();
  344. // We do not want to timeout while downloading
  345. client.Timeout = TimeSpan.FromDays(1);
  346. using (HttpResponseMessage response = client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead).Result)
  347. using (Stream remoteFileStream = response.Content.ReadAsStreamAsync().Result)
  348. {
  349. using Stream updateFileStream = File.Open(updateFile, FileMode.Create);
  350. long totalBytes = response.Content.Headers.ContentLength.Value;
  351. long byteWritten = 0;
  352. byte[] buffer = new byte[32 * 1024];
  353. while (true)
  354. {
  355. int readSize = remoteFileStream.Read(buffer);
  356. if (readSize == 0)
  357. {
  358. break;
  359. }
  360. byteWritten += readSize;
  361. taskDialog.SetProgressBarState(GetPercentage(byteWritten, totalBytes), TaskDialogProgressState.Normal);
  362. updateFileStream.Write(buffer, 0, readSize);
  363. }
  364. }
  365. InstallUpdate(taskDialog, updateFile);
  366. }
  367. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  368. private static double GetPercentage(double value, double max)
  369. {
  370. return max == 0 ? 0 : value / max * 100;
  371. }
  372. private static void DoUpdateWithSingleThread(TaskDialog taskDialog, string downloadUrl, string updateFile)
  373. {
  374. Thread worker = new(() => DoUpdateWithSingleThreadWorker(taskDialog, downloadUrl, updateFile))
  375. {
  376. Name = "Updater.SingleThreadWorker"
  377. };
  378. worker.Start();
  379. }
  380. private static async void InstallUpdate(TaskDialog taskDialog, string updateFile)
  381. {
  382. // Extract Update
  383. taskDialog.SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterExtracting];
  384. taskDialog.SetProgressBarState(0, TaskDialogProgressState.Normal);
  385. if (OperatingSystem.IsLinux())
  386. {
  387. using Stream inStream = File.OpenRead(updateFile);
  388. using GZipInputStream gzipStream = new(inStream);
  389. using TarInputStream tarStream = new(gzipStream, Encoding.ASCII);
  390. await Task.Run(() =>
  391. {
  392. TarEntry tarEntry;
  393. if (!OperatingSystem.IsWindows())
  394. {
  395. while ((tarEntry = tarStream.GetNextEntry()) is not null)
  396. {
  397. if (tarEntry.IsDirectory) continue;
  398. string outPath = Path.Combine(UpdateDir, tarEntry.Name);
  399. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  400. using (FileStream outStream = File.OpenWrite(outPath))
  401. {
  402. tarStream.CopyEntryContents(outStream);
  403. }
  404. File.SetUnixFileMode(outPath, (UnixFileMode)tarEntry.TarHeader.Mode);
  405. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc));
  406. Dispatcher.UIThread.Post(() =>
  407. {
  408. if (tarEntry is null)
  409. {
  410. return;
  411. }
  412. taskDialog.SetProgressBarState(GetPercentage(tarEntry.Size, inStream.Length), TaskDialogProgressState.Normal);
  413. });
  414. }
  415. }
  416. });
  417. taskDialog.SetProgressBarState(100, TaskDialogProgressState.Normal);
  418. }
  419. else
  420. {
  421. using Stream inStream = File.OpenRead(updateFile);
  422. using ZipFile zipFile = new(inStream);
  423. await Task.Run(() =>
  424. {
  425. double count = 0;
  426. foreach (ZipEntry zipEntry in zipFile)
  427. {
  428. count++;
  429. if (zipEntry.IsDirectory) continue;
  430. string outPath = Path.Combine(UpdateDir, zipEntry.Name);
  431. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  432. using (Stream zipStream = zipFile.GetInputStream(zipEntry))
  433. using (FileStream outStream = File.OpenWrite(outPath))
  434. {
  435. zipStream.CopyTo(outStream);
  436. }
  437. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(zipEntry.DateTime, DateTimeKind.Utc));
  438. Dispatcher.UIThread.Post(() =>
  439. {
  440. taskDialog.SetProgressBarState(GetPercentage(count, zipFile.Count), TaskDialogProgressState.Normal);
  441. });
  442. }
  443. });
  444. }
  445. // Delete downloaded zip
  446. File.Delete(updateFile);
  447. List<string> allFiles = EnumerateFilesToDelete().ToList();
  448. taskDialog.SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterRenaming];
  449. taskDialog.SetProgressBarState(0, TaskDialogProgressState.Normal);
  450. // Replace old files
  451. await Task.Run(() =>
  452. {
  453. double count = 0;
  454. foreach (string file in allFiles)
  455. {
  456. count++;
  457. try
  458. {
  459. File.Move(file, file + ".ryuold");
  460. Dispatcher.UIThread.Post(() =>
  461. {
  462. taskDialog.SetProgressBarState(GetPercentage(count, allFiles.Count), TaskDialogProgressState.Normal);
  463. });
  464. }
  465. catch
  466. {
  467. Logger.Warning?.Print(LogClass.Application, LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.UpdaterRenameFailed, file));
  468. }
  469. }
  470. Dispatcher.UIThread.Post(() =>
  471. {
  472. taskDialog.SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterAddingFiles];
  473. taskDialog.SetProgressBarState(0, TaskDialogProgressState.Normal);
  474. });
  475. MoveAllFilesOver(UpdatePublishDir, HomeDir, taskDialog);
  476. });
  477. Directory.Delete(UpdateDir, true);
  478. _updateSuccessful = true;
  479. taskDialog.Hide();
  480. }
  481. public static bool CanUpdate(bool showWarnings)
  482. {
  483. #if !DISABLE_UPDATER
  484. if (RuntimeInformation.OSArchitecture != Architecture.X64)
  485. {
  486. if (showWarnings)
  487. {
  488. Dispatcher.UIThread.Post(async () =>
  489. {
  490. await ContentDialogHelper.CreateWarningDialog(
  491. LocaleManager.Instance[LocaleKeys.DialogUpdaterArchNotSupportedMessage],
  492. LocaleManager.Instance[LocaleKeys.DialogUpdaterArchNotSupportedSubMessage]);
  493. });
  494. }
  495. return false;
  496. }
  497. if (!NetworkInterface.GetIsNetworkAvailable())
  498. {
  499. if (showWarnings)
  500. {
  501. Dispatcher.UIThread.Post(async () =>
  502. {
  503. await ContentDialogHelper.CreateWarningDialog(
  504. LocaleManager.Instance[LocaleKeys.DialogUpdaterNoInternetMessage],
  505. LocaleManager.Instance[LocaleKeys.DialogUpdaterNoInternetSubMessage]);
  506. });
  507. }
  508. return false;
  509. }
  510. if (Program.Version.Contains("dirty") || !ReleaseInformation.IsValid())
  511. {
  512. if (showWarnings)
  513. {
  514. Dispatcher.UIThread.Post(async () =>
  515. {
  516. await ContentDialogHelper.CreateWarningDialog(
  517. LocaleManager.Instance[LocaleKeys.DialogUpdaterDirtyBuildMessage],
  518. LocaleManager.Instance[LocaleKeys.DialogUpdaterDirtyBuildSubMessage]);
  519. });
  520. }
  521. return false;
  522. }
  523. return true;
  524. #else
  525. if (showWarnings)
  526. {
  527. if (ReleaseInformation.IsFlatHubBuild())
  528. {
  529. Dispatcher.UIThread.Post(async () =>
  530. {
  531. await ContentDialogHelper.CreateWarningDialog(
  532. LocaleManager.Instance[LocaleKeys.UpdaterDisabledWarningTitle],
  533. LocaleManager.Instance[LocaleKeys.DialogUpdaterFlatpakNotSupportedMessage]);
  534. });
  535. }
  536. else
  537. {
  538. Dispatcher.UIThread.Post(async () =>
  539. {
  540. await ContentDialogHelper.CreateWarningDialog(
  541. LocaleManager.Instance[LocaleKeys.UpdaterDisabledWarningTitle],
  542. LocaleManager.Instance[LocaleKeys.DialogUpdaterDirtyBuildSubMessage]);
  543. });
  544. }
  545. }
  546. return false;
  547. #endif
  548. }
  549. // NOTE: This method should always reflect the latest build layout.s
  550. private static IEnumerable<string> EnumerateFilesToDelete()
  551. {
  552. var files = Directory.EnumerateFiles(HomeDir); // All files directly in base dir.
  553. if (OperatingSystem.IsWindows())
  554. {
  555. foreach (string dir in WindowsDependencyDirs)
  556. {
  557. string dirPath = Path.Combine(HomeDir, dir);
  558. if (Directory.Exists(dirPath))
  559. {
  560. files = files.Concat(Directory.EnumerateFiles(dirPath, "*", SearchOption.AllDirectories));
  561. }
  562. }
  563. }
  564. return files;
  565. }
  566. private static void MoveAllFilesOver(string root, string dest, TaskDialog taskDialog)
  567. {
  568. int total = Directory.GetFiles(root, "*", SearchOption.AllDirectories).Length;
  569. foreach (string directory in Directory.GetDirectories(root))
  570. {
  571. string dirName = Path.GetFileName(directory);
  572. if (!Directory.Exists(Path.Combine(dest, dirName)))
  573. {
  574. Directory.CreateDirectory(Path.Combine(dest, dirName));
  575. }
  576. MoveAllFilesOver(directory, Path.Combine(dest, dirName), taskDialog);
  577. }
  578. double count = 0;
  579. foreach (string file in Directory.GetFiles(root))
  580. {
  581. count++;
  582. File.Move(file, Path.Combine(dest, Path.GetFileName(file)), true);
  583. Dispatcher.UIThread.InvokeAsync(() =>
  584. {
  585. taskDialog.SetProgressBarState(GetPercentage(count, total), TaskDialogProgressState.Normal);
  586. });
  587. }
  588. }
  589. public static void CleanupUpdate()
  590. {
  591. foreach (string file in Directory.GetFiles(HomeDir, "*.ryuold", SearchOption.AllDirectories))
  592. {
  593. File.Delete(file);
  594. }
  595. }
  596. }
  597. }