Updater.cs 30 KB

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