Updater.cs 29 KB

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