Updater.cs 30 KB

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