Updater.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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 availaible.
  114. if (_buildUrl == 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 interract with APIs.
  202. result.DefaultRequestHeaders.Add("User-Agent", "Ryujinx-Updater/1.0.0");
  203. return result;
  204. }
  205. public 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. SetFileExecutable(ryuExe);
  250. Process.Start(ryuExe, CommandLineState.Arguments);
  251. Environment.Exit(0);
  252. }
  253. }
  254. }
  255. private static void DoUpdateWithMultipleThreads(TaskDialog taskDialog, string downloadUrl, string updateFile)
  256. {
  257. // Multi-Threaded Updater
  258. long chunkSize = _buildSize / ConnectionCount;
  259. long remainderChunk = _buildSize % ConnectionCount;
  260. int completedRequests = 0;
  261. int totalProgressPercentage = 0;
  262. int[] progressPercentage = new int[ConnectionCount];
  263. List<byte[]> list = new(ConnectionCount);
  264. List<WebClient> webClients = new(ConnectionCount);
  265. for (int i = 0; i < ConnectionCount; i++)
  266. {
  267. list.Add(Array.Empty<byte>());
  268. }
  269. for (int i = 0; i < ConnectionCount; i++)
  270. {
  271. #pragma warning disable SYSLIB0014
  272. // TODO: WebClient is obsolete and need to be replaced with a more complex logic using HttpClient.
  273. using WebClient client = new();
  274. #pragma warning restore SYSLIB0014
  275. webClients.Add(client);
  276. if (i == ConnectionCount - 1)
  277. {
  278. client.Headers.Add("Range", $"bytes={chunkSize * i}-{(chunkSize * (i + 1) - 1) + remainderChunk}");
  279. }
  280. else
  281. {
  282. client.Headers.Add("Range", $"bytes={chunkSize * i}-{chunkSize * (i + 1) - 1}");
  283. }
  284. client.DownloadProgressChanged += (_, args) =>
  285. {
  286. int index = (int)args.UserState;
  287. Interlocked.Add(ref totalProgressPercentage, -1 * progressPercentage[index]);
  288. Interlocked.Exchange(ref progressPercentage[index], args.ProgressPercentage);
  289. Interlocked.Add(ref totalProgressPercentage, args.ProgressPercentage);
  290. taskDialog.SetProgressBarState(totalProgressPercentage / ConnectionCount, TaskDialogProgressState.Normal);
  291. };
  292. client.DownloadDataCompleted += (_, args) =>
  293. {
  294. int index = (int)args.UserState;
  295. if (args.Cancelled)
  296. {
  297. webClients[index].Dispose();
  298. taskDialog.Hide();
  299. return;
  300. }
  301. list[index] = args.Result;
  302. Interlocked.Increment(ref completedRequests);
  303. if (Equals(completedRequests, ConnectionCount))
  304. {
  305. byte[] mergedFileBytes = new byte[_buildSize];
  306. for (int connectionIndex = 0, destinationOffset = 0; connectionIndex < ConnectionCount; connectionIndex++)
  307. {
  308. Array.Copy(list[connectionIndex], 0, mergedFileBytes, destinationOffset, list[connectionIndex].Length);
  309. destinationOffset += list[connectionIndex].Length;
  310. }
  311. File.WriteAllBytes(updateFile, mergedFileBytes);
  312. try
  313. {
  314. InstallUpdate(taskDialog, updateFile);
  315. }
  316. catch (Exception e)
  317. {
  318. Logger.Warning?.Print(LogClass.Application, e.Message);
  319. Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater.");
  320. DoUpdateWithSingleThread(taskDialog, downloadUrl, updateFile);
  321. return;
  322. }
  323. }
  324. };
  325. try
  326. {
  327. client.DownloadDataAsync(new Uri(downloadUrl), i);
  328. }
  329. catch (WebException ex)
  330. {
  331. Logger.Warning?.Print(LogClass.Application, ex.Message);
  332. Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater.");
  333. for (int j = 0; j < webClients.Count; j++)
  334. {
  335. webClients[j].CancelAsync();
  336. }
  337. DoUpdateWithSingleThread(taskDialog, downloadUrl, updateFile);
  338. return;
  339. }
  340. }
  341. }
  342. private static void DoUpdateWithSingleThreadWorker(TaskDialog taskDialog, string downloadUrl, string updateFile)
  343. {
  344. using HttpClient client = new();
  345. // We do not want to timeout while downloading
  346. client.Timeout = TimeSpan.FromDays(1);
  347. using (HttpResponseMessage response = client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead).Result)
  348. using (Stream remoteFileStream = response.Content.ReadAsStreamAsync().Result)
  349. {
  350. using Stream updateFileStream = File.Open(updateFile, FileMode.Create);
  351. long totalBytes = response.Content.Headers.ContentLength.Value;
  352. long byteWritten = 0;
  353. byte[] buffer = new byte[32 * 1024];
  354. while (true)
  355. {
  356. int readSize = remoteFileStream.Read(buffer);
  357. if (readSize == 0)
  358. {
  359. break;
  360. }
  361. byteWritten += readSize;
  362. taskDialog.SetProgressBarState(GetPercentage(byteWritten, totalBytes), TaskDialogProgressState.Normal);
  363. updateFileStream.Write(buffer, 0, readSize);
  364. }
  365. }
  366. InstallUpdate(taskDialog, updateFile);
  367. }
  368. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  369. private static double GetPercentage(double value, double max)
  370. {
  371. return max == 0 ? 0 : value / max * 100;
  372. }
  373. private static void DoUpdateWithSingleThread(TaskDialog taskDialog, string downloadUrl, string updateFile)
  374. {
  375. Thread worker = new(() => DoUpdateWithSingleThreadWorker(taskDialog, downloadUrl, updateFile))
  376. {
  377. Name = "Updater.SingleThreadWorker"
  378. };
  379. worker.Start();
  380. }
  381. private static void SetFileExecutable(string path)
  382. {
  383. const UnixFileMode ExecutableFileMode = UnixFileMode.UserExecute |
  384. UnixFileMode.UserWrite |
  385. UnixFileMode.UserRead |
  386. UnixFileMode.GroupRead |
  387. UnixFileMode.GroupWrite |
  388. UnixFileMode.OtherRead |
  389. UnixFileMode.OtherWrite;
  390. if (!OperatingSystem.IsWindows() && File.Exists(path))
  391. {
  392. File.SetUnixFileMode(path, ExecutableFileMode);
  393. }
  394. }
  395. private static async void InstallUpdate(TaskDialog taskDialog, string updateFile)
  396. {
  397. // Extract Update
  398. taskDialog.SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterExtracting];
  399. taskDialog.SetProgressBarState(0, TaskDialogProgressState.Normal);
  400. if (OperatingSystem.IsLinux())
  401. {
  402. using Stream inStream = File.OpenRead(updateFile);
  403. using GZipInputStream gzipStream = new(inStream);
  404. using TarInputStream tarStream = new(gzipStream, Encoding.ASCII);
  405. await Task.Run(() =>
  406. {
  407. TarEntry tarEntry;
  408. while ((tarEntry = tarStream.GetNextEntry()) != null)
  409. {
  410. if (tarEntry.IsDirectory) continue;
  411. string outPath = Path.Combine(UpdateDir, tarEntry.Name);
  412. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  413. using (FileStream outStream = File.OpenWrite(outPath))
  414. {
  415. tarStream.CopyEntryContents(outStream);
  416. }
  417. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc));
  418. TarEntry entry = tarEntry;
  419. Dispatcher.UIThread.Post(() =>
  420. {
  421. taskDialog.SetProgressBarState(GetPercentage(entry.Size, inStream.Length), TaskDialogProgressState.Normal);
  422. });
  423. }
  424. });
  425. taskDialog.SetProgressBarState(100, TaskDialogProgressState.Normal);
  426. }
  427. else
  428. {
  429. using Stream inStream = File.OpenRead(updateFile);
  430. using ZipFile zipFile = new(inStream);
  431. await Task.Run(() =>
  432. {
  433. double count = 0;
  434. foreach (ZipEntry zipEntry in zipFile)
  435. {
  436. count++;
  437. if (zipEntry.IsDirectory) continue;
  438. string outPath = Path.Combine(UpdateDir, zipEntry.Name);
  439. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  440. using (Stream zipStream = zipFile.GetInputStream(zipEntry))
  441. using (FileStream outStream = File.OpenWrite(outPath))
  442. {
  443. zipStream.CopyTo(outStream);
  444. }
  445. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(zipEntry.DateTime, DateTimeKind.Utc));
  446. Dispatcher.UIThread.Post(() =>
  447. {
  448. taskDialog.SetProgressBarState(GetPercentage(count, zipFile.Count), TaskDialogProgressState.Normal);
  449. });
  450. }
  451. });
  452. }
  453. // Delete downloaded zip
  454. File.Delete(updateFile);
  455. List<string> allFiles = EnumerateFilesToDelete().ToList();
  456. taskDialog.SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterRenaming];
  457. taskDialog.SetProgressBarState(0, TaskDialogProgressState.Normal);
  458. // Replace old files
  459. await Task.Run(() =>
  460. {
  461. double count = 0;
  462. foreach (string file in allFiles)
  463. {
  464. count++;
  465. try
  466. {
  467. File.Move(file, file + ".ryuold");
  468. Dispatcher.UIThread.Post(() =>
  469. {
  470. taskDialog.SetProgressBarState(GetPercentage(count, allFiles.Count), TaskDialogProgressState.Normal);
  471. });
  472. }
  473. catch
  474. {
  475. Logger.Warning?.Print(LogClass.Application, LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.UpdaterRenameFailed, file));
  476. }
  477. }
  478. Dispatcher.UIThread.Post(() =>
  479. {
  480. taskDialog.SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterAddingFiles];
  481. taskDialog.SetProgressBarState(0, TaskDialogProgressState.Normal);
  482. });
  483. MoveAllFilesOver(UpdatePublishDir, HomeDir, taskDialog);
  484. });
  485. Directory.Delete(UpdateDir, true);
  486. SetFileExecutable(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ryujinx"));
  487. _updateSuccessful = true;
  488. taskDialog.Hide();
  489. }
  490. public static bool CanUpdate(bool showWarnings)
  491. {
  492. #if !DISABLE_UPDATER
  493. if (RuntimeInformation.OSArchitecture != Architecture.X64)
  494. {
  495. if (showWarnings)
  496. {
  497. Dispatcher.UIThread.Post(async () =>
  498. {
  499. await ContentDialogHelper.CreateWarningDialog(
  500. LocaleManager.Instance[LocaleKeys.DialogUpdaterArchNotSupportedMessage],
  501. LocaleManager.Instance[LocaleKeys.DialogUpdaterArchNotSupportedSubMessage]);
  502. });
  503. }
  504. return false;
  505. }
  506. if (!NetworkInterface.GetIsNetworkAvailable())
  507. {
  508. if (showWarnings)
  509. {
  510. Dispatcher.UIThread.Post(async () =>
  511. {
  512. await ContentDialogHelper.CreateWarningDialog(
  513. LocaleManager.Instance[LocaleKeys.DialogUpdaterNoInternetMessage],
  514. LocaleManager.Instance[LocaleKeys.DialogUpdaterNoInternetSubMessage]);
  515. });
  516. }
  517. return false;
  518. }
  519. if (Program.Version.Contains("dirty") || !ReleaseInformation.IsValid())
  520. {
  521. if (showWarnings)
  522. {
  523. Dispatcher.UIThread.Post(async () =>
  524. {
  525. await ContentDialogHelper.CreateWarningDialog(
  526. LocaleManager.Instance[LocaleKeys.DialogUpdaterDirtyBuildMessage],
  527. LocaleManager.Instance[LocaleKeys.DialogUpdaterDirtyBuildSubMessage]);
  528. });
  529. }
  530. return false;
  531. }
  532. return true;
  533. #else
  534. if (showWarnings)
  535. {
  536. if (ReleaseInformation.IsFlatHubBuild())
  537. {
  538. Dispatcher.UIThread.Post(async () =>
  539. {
  540. await ContentDialogHelper.CreateWarningDialog(
  541. LocaleManager.Instance[LocaleKeys.UpdaterDisabledWarningTitle],
  542. LocaleManager.Instance[LocaleKeys.DialogUpdaterFlatpakNotSupportedMessage]);
  543. });
  544. }
  545. else
  546. {
  547. Dispatcher.UIThread.Post(async () =>
  548. {
  549. await ContentDialogHelper.CreateWarningDialog(
  550. LocaleManager.Instance[LocaleKeys.UpdaterDisabledWarningTitle],
  551. LocaleManager.Instance[LocaleKeys.DialogUpdaterDirtyBuildSubMessage]);
  552. });
  553. }
  554. }
  555. return false;
  556. #endif
  557. }
  558. // NOTE: This method should always reflect the latest build layout.s
  559. private static IEnumerable<string> EnumerateFilesToDelete()
  560. {
  561. var files = Directory.EnumerateFiles(HomeDir); // All files directly in base dir.
  562. if (OperatingSystem.IsWindows())
  563. {
  564. foreach (string dir in WindowsDependencyDirs)
  565. {
  566. string dirPath = Path.Combine(HomeDir, dir);
  567. if (Directory.Exists(dirPath))
  568. {
  569. files = files.Concat(Directory.EnumerateFiles(dirPath, "*", SearchOption.AllDirectories));
  570. }
  571. }
  572. }
  573. return files;
  574. }
  575. private static void MoveAllFilesOver(string root, string dest, TaskDialog taskDialog)
  576. {
  577. int total = Directory.GetFiles(root, "*", SearchOption.AllDirectories).Length;
  578. foreach (string directory in Directory.GetDirectories(root))
  579. {
  580. string dirName = Path.GetFileName(directory);
  581. if (!Directory.Exists(Path.Combine(dest, dirName)))
  582. {
  583. Directory.CreateDirectory(Path.Combine(dest, dirName));
  584. }
  585. MoveAllFilesOver(directory, Path.Combine(dest, dirName), taskDialog);
  586. }
  587. double count = 0;
  588. foreach (string file in Directory.GetFiles(root))
  589. {
  590. count++;
  591. File.Move(file, Path.Combine(dest, Path.GetFileName(file)), true);
  592. Dispatcher.UIThread.InvokeAsync(() =>
  593. {
  594. taskDialog.SetProgressBarState(GetPercentage(count, total), TaskDialogProgressState.Normal);
  595. });
  596. }
  597. }
  598. public static void CleanupUpdate()
  599. {
  600. foreach (string file in Directory.GetFiles(HomeDir, "*.ryuold", SearchOption.AllDirectories))
  601. {
  602. File.Delete(file);
  603. }
  604. }
  605. }
  606. }