Updater.cs 27 KB

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