Updater.cs 29 KB

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