Updater.cs 29 KB

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