Updater.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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. if (!Version.TryParse(Program.Version, out Version currentVersion))
  69. {
  70. Logger.Error?.Print(LogClass.Application, $"Failed to convert the current {App.FullAppName} version!");
  71. await ContentDialogHelper.CreateWarningDialog(
  72. LocaleManager.Instance[LocaleKeys.DialogUpdaterConvertFailedMessage],
  73. LocaleManager.Instance[LocaleKeys.DialogUpdaterCancelUpdateMessage]);
  74. _running = false;
  75. return;
  76. }
  77. // Get latest version number from GitHub API
  78. try
  79. {
  80. using HttpClient jsonClient = ConstructHttpClient();
  81. string fetchedJson = await jsonClient.GetStringAsync(LatestReleaseUrl);
  82. var fetched = JsonHelper.Deserialize(fetchedJson, _serializerContext.GithubReleasesJsonResponse);
  83. _buildVer = fetched.TagName;
  84. foreach (var asset in fetched.Assets)
  85. {
  86. if (asset.Name.StartsWith("ryujinx") && asset.Name.EndsWith(_platformExt))
  87. {
  88. _buildUrl = asset.BrowserDownloadUrl;
  89. if (asset.State != "uploaded")
  90. {
  91. if (showVersionUpToDate)
  92. {
  93. UserResult userResult = await ContentDialogHelper.CreateUpdaterUpToDateInfoDialog(
  94. LocaleManager.Instance[LocaleKeys.DialogUpdaterAlreadyOnLatestVersionMessage],
  95. string.Empty);
  96. if (userResult is UserResult.Ok)
  97. {
  98. OpenHelper.OpenUrl(ReleaseInformation.GetChangelogForVersion(currentVersion));
  99. }
  100. }
  101. _running = false;
  102. return;
  103. }
  104. break;
  105. }
  106. }
  107. // If build not done, assume no new update are available.
  108. if (_buildUrl is null)
  109. {
  110. if (showVersionUpToDate)
  111. {
  112. UserResult userResult = await ContentDialogHelper.CreateUpdaterUpToDateInfoDialog(
  113. LocaleManager.Instance[LocaleKeys.DialogUpdaterAlreadyOnLatestVersionMessage],
  114. string.Empty);
  115. if (userResult is UserResult.Ok)
  116. {
  117. OpenHelper.OpenUrl(ReleaseInformation.GetChangelogForVersion(currentVersion));
  118. }
  119. }
  120. _running = false;
  121. return;
  122. }
  123. }
  124. catch (Exception exception)
  125. {
  126. Logger.Error?.Print(LogClass.Application, exception.Message);
  127. await ContentDialogHelper.CreateErrorDialog(
  128. LocaleManager.Instance[LocaleKeys.DialogUpdaterFailedToGetVersionMessage]);
  129. _running = false;
  130. return;
  131. }
  132. if (!Version.TryParse(_buildVer, out Version newVersion))
  133. {
  134. Logger.Error?.Print(LogClass.Application, $"Failed to convert the received {App.FullAppName} version from GitHub!");
  135. await ContentDialogHelper.CreateWarningDialog(
  136. LocaleManager.Instance[LocaleKeys.DialogUpdaterConvertFailedGithubMessage],
  137. LocaleManager.Instance[LocaleKeys.DialogUpdaterCancelUpdateMessage]);
  138. _running = false;
  139. return;
  140. }
  141. if (newVersion <= currentVersion)
  142. {
  143. if (showVersionUpToDate)
  144. {
  145. UserResult userResult = await ContentDialogHelper.CreateUpdaterUpToDateInfoDialog(
  146. LocaleManager.Instance[LocaleKeys.DialogUpdaterAlreadyOnLatestVersionMessage],
  147. string.Empty);
  148. if (userResult is UserResult.Ok)
  149. {
  150. OpenHelper.OpenUrl(ReleaseInformation.GetChangelogForVersion(currentVersion));
  151. }
  152. }
  153. _running = false;
  154. return;
  155. }
  156. // Fetch build size information to learn chunk sizes.
  157. using HttpClient buildSizeClient = ConstructHttpClient();
  158. try
  159. {
  160. buildSizeClient.DefaultRequestHeaders.Add("Range", "bytes=0-0");
  161. HttpResponseMessage message = await buildSizeClient.GetAsync(new Uri(_buildUrl), HttpCompletionOption.ResponseHeadersRead);
  162. _buildSize = message.Content.Headers.ContentRange.Length.Value;
  163. }
  164. catch (Exception ex)
  165. {
  166. Logger.Warning?.Print(LogClass.Application, ex.Message);
  167. Logger.Warning?.Print(LogClass.Application, "Couldn't determine build size for update, using single-threaded updater");
  168. _buildSize = -1;
  169. }
  170. await Dispatcher.UIThread.InvokeAsync(async () =>
  171. {
  172. string newVersionString = ReleaseInformation.IsCanaryBuild
  173. ? $"Canary {currentVersion} -> Canary {newVersion}"
  174. : $"{currentVersion} -> {newVersion}";
  175. RequestUserToUpdate:
  176. // Show a message asking the user if they want to update
  177. UserResult shouldUpdate = await ContentDialogHelper.CreateUpdaterChoiceDialog(
  178. LocaleManager.Instance[LocaleKeys.RyujinxUpdater],
  179. LocaleManager.Instance[LocaleKeys.RyujinxUpdaterMessage],
  180. newVersionString);
  181. switch (shouldUpdate)
  182. {
  183. case UserResult.Yes:
  184. await UpdateRyujinx(_buildUrl);
  185. break;
  186. // Secondary button maps to no, which in this case is the show changelog button.
  187. case UserResult.No:
  188. OpenHelper.OpenUrl(ReleaseInformation.GetChangelogUrl(currentVersion, newVersion));
  189. goto RequestUserToUpdate;
  190. default:
  191. _running = false;
  192. break;
  193. }
  194. });
  195. }
  196. private static HttpClient ConstructHttpClient()
  197. {
  198. HttpClient result = new();
  199. // Required by GitHub to interact with APIs.
  200. result.DefaultRequestHeaders.Add("User-Agent", "Ryujinx-Updater/1.0.0");
  201. return result;
  202. }
  203. private static async Task UpdateRyujinx(string downloadUrl)
  204. {
  205. _updateSuccessful = false;
  206. // Empty update dir, although it shouldn't ever have anything inside it
  207. if (Directory.Exists(_updateDir))
  208. {
  209. Directory.Delete(_updateDir, true);
  210. }
  211. Directory.CreateDirectory(_updateDir);
  212. string updateFile = Path.Combine(_updateDir, "update.bin");
  213. TaskDialog taskDialog = new()
  214. {
  215. Header = LocaleManager.Instance[LocaleKeys.RyujinxUpdater],
  216. SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterDownloading],
  217. IconSource = new SymbolIconSource { Symbol = Symbol.Download },
  218. ShowProgressBar = true,
  219. XamlRoot = App.MainWindow,
  220. };
  221. taskDialog.Opened += (s, e) =>
  222. {
  223. if (_buildSize >= 0)
  224. {
  225. DoUpdateWithMultipleThreads(taskDialog, downloadUrl, updateFile);
  226. }
  227. else
  228. {
  229. DoUpdateWithSingleThread(taskDialog, downloadUrl, updateFile);
  230. }
  231. };
  232. await taskDialog.ShowAsync(true);
  233. if (_updateSuccessful)
  234. {
  235. bool shouldRestart = true;
  236. if (!OperatingSystem.IsMacOS())
  237. {
  238. shouldRestart = await ContentDialogHelper.CreateChoiceDialog(LocaleManager.Instance[LocaleKeys.RyujinxUpdater],
  239. LocaleManager.Instance[LocaleKeys.DialogUpdaterCompleteMessage],
  240. LocaleManager.Instance[LocaleKeys.DialogUpdaterRestartMessage]);
  241. }
  242. if (shouldRestart)
  243. {
  244. List<string> arguments = CommandLineState.Arguments.ToList();
  245. string executableDirectory = AppDomain.CurrentDomain.BaseDirectory;
  246. // On macOS we perform the update at relaunch.
  247. if (OperatingSystem.IsMacOS())
  248. {
  249. string baseBundlePath = Path.GetFullPath(Path.Combine(executableDirectory, "..", ".."));
  250. string newBundlePath = Path.Combine(_updateDir, "Ryujinx.app");
  251. string updaterScriptPath = Path.Combine(newBundlePath, "Contents", "Resources", "updater.sh");
  252. string currentPid = Environment.ProcessId.ToString();
  253. arguments.InsertRange(0, new List<string> { updaterScriptPath, baseBundlePath, newBundlePath, currentPid });
  254. Process.Start("/bin/bash", arguments);
  255. }
  256. else
  257. {
  258. // Find the process name.
  259. string ryuName = Path.GetFileName(Environment.ProcessPath) ?? string.Empty;
  260. // Some operating systems can see the renamed executable, so strip off the .ryuold if found.
  261. if (ryuName.EndsWith(".ryuold"))
  262. {
  263. ryuName = ryuName[..^7];
  264. }
  265. // Fallback if the executable could not be found.
  266. if (ryuName.Length == 0 || !Path.Exists(Path.Combine(executableDirectory, ryuName)))
  267. {
  268. ryuName = OperatingSystem.IsWindows() ? "Ryujinx.exe" : "Ryujinx";
  269. }
  270. ProcessStartInfo processStart = new(ryuName)
  271. {
  272. UseShellExecute = true,
  273. WorkingDirectory = executableDirectory,
  274. };
  275. foreach (string argument in CommandLineState.Arguments)
  276. {
  277. processStart.ArgumentList.Add(argument);
  278. }
  279. Process.Start(processStart);
  280. }
  281. Environment.Exit(0);
  282. }
  283. }
  284. }
  285. private static void DoUpdateWithMultipleThreads(TaskDialog taskDialog, string downloadUrl, string updateFile)
  286. {
  287. // Multi-Threaded Updater
  288. long chunkSize = _buildSize / ConnectionCount;
  289. long remainderChunk = _buildSize % ConnectionCount;
  290. int completedRequests = 0;
  291. int totalProgressPercentage = 0;
  292. int[] progressPercentage = new int[ConnectionCount];
  293. List<byte[]> list = new(ConnectionCount);
  294. List<WebClient> webClients = new(ConnectionCount);
  295. for (int i = 0; i < ConnectionCount; i++)
  296. {
  297. list.Add(Array.Empty<byte>());
  298. }
  299. for (int i = 0; i < ConnectionCount; i++)
  300. {
  301. #pragma warning disable SYSLIB0014
  302. // TODO: WebClient is obsolete and need to be replaced with a more complex logic using HttpClient.
  303. using WebClient client = new();
  304. #pragma warning restore SYSLIB0014
  305. webClients.Add(client);
  306. if (i == ConnectionCount - 1)
  307. {
  308. client.Headers.Add("Range", $"bytes={chunkSize * i}-{(chunkSize * (i + 1) - 1) + remainderChunk}");
  309. }
  310. else
  311. {
  312. client.Headers.Add("Range", $"bytes={chunkSize * i}-{chunkSize * (i + 1) - 1}");
  313. }
  314. client.DownloadProgressChanged += (_, args) =>
  315. {
  316. int index = (int)args.UserState;
  317. Interlocked.Add(ref totalProgressPercentage, -1 * progressPercentage[index]);
  318. Interlocked.Exchange(ref progressPercentage[index], args.ProgressPercentage);
  319. Interlocked.Add(ref totalProgressPercentage, args.ProgressPercentage);
  320. taskDialog.SetProgressBarState(totalProgressPercentage / ConnectionCount, TaskDialogProgressState.Normal);
  321. };
  322. client.DownloadDataCompleted += (_, args) =>
  323. {
  324. int index = (int)args.UserState;
  325. if (args.Cancelled)
  326. {
  327. webClients[index].Dispose();
  328. taskDialog.Hide();
  329. return;
  330. }
  331. list[index] = args.Result;
  332. Interlocked.Increment(ref completedRequests);
  333. if (Equals(completedRequests, ConnectionCount))
  334. {
  335. byte[] mergedFileBytes = new byte[_buildSize];
  336. for (int connectionIndex = 0, destinationOffset = 0; connectionIndex < ConnectionCount; connectionIndex++)
  337. {
  338. Array.Copy(list[connectionIndex], 0, mergedFileBytes, destinationOffset, list[connectionIndex].Length);
  339. destinationOffset += list[connectionIndex].Length;
  340. }
  341. File.WriteAllBytes(updateFile, mergedFileBytes);
  342. // On macOS, ensure that we remove the quarantine bit to prevent Gatekeeper from blocking execution.
  343. if (OperatingSystem.IsMacOS())
  344. {
  345. using Process xattrProcess = Process.Start("xattr", new List<string> { "-d", "com.apple.quarantine", updateFile });
  346. xattrProcess.WaitForExit();
  347. }
  348. try
  349. {
  350. InstallUpdate(taskDialog, updateFile);
  351. }
  352. catch (Exception e)
  353. {
  354. Logger.Warning?.Print(LogClass.Application, e.Message);
  355. Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater.");
  356. DoUpdateWithSingleThread(taskDialog, downloadUrl, updateFile);
  357. }
  358. }
  359. };
  360. try
  361. {
  362. client.DownloadDataAsync(new Uri(downloadUrl), i);
  363. }
  364. catch (WebException ex)
  365. {
  366. Logger.Warning?.Print(LogClass.Application, ex.Message);
  367. Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater.");
  368. foreach (WebClient webClient in webClients)
  369. {
  370. webClient.CancelAsync();
  371. }
  372. DoUpdateWithSingleThread(taskDialog, downloadUrl, updateFile);
  373. return;
  374. }
  375. }
  376. }
  377. private static void DoUpdateWithSingleThreadWorker(TaskDialog taskDialog, string downloadUrl, string updateFile)
  378. {
  379. using HttpClient client = new();
  380. // We do not want to timeout while downloading
  381. client.Timeout = TimeSpan.FromDays(1);
  382. using HttpResponseMessage response = client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead).Result;
  383. using Stream remoteFileStream = response.Content.ReadAsStreamAsync().Result;
  384. using Stream updateFileStream = File.Open(updateFile, FileMode.Create);
  385. long totalBytes = response.Content.Headers.ContentLength.Value;
  386. long bytesWritten = 0;
  387. byte[] buffer = new byte[32 * 1024];
  388. while (true)
  389. {
  390. int readSize = remoteFileStream.Read(buffer);
  391. if (readSize == 0)
  392. {
  393. break;
  394. }
  395. bytesWritten += readSize;
  396. taskDialog.SetProgressBarState(GetPercentage(bytesWritten, totalBytes), TaskDialogProgressState.Normal);
  397. App.SetTaskbarProgressValue(bytesWritten, totalBytes);
  398. updateFileStream.Write(buffer, 0, readSize);
  399. }
  400. InstallUpdate(taskDialog, updateFile);
  401. }
  402. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  403. private static double GetPercentage(double value, double max)
  404. {
  405. return max == 0 ? 0 : value / max * 100;
  406. }
  407. private static void DoUpdateWithSingleThread(TaskDialog taskDialog, string downloadUrl, string updateFile)
  408. {
  409. Thread worker = new(() => DoUpdateWithSingleThreadWorker(taskDialog, downloadUrl, updateFile))
  410. {
  411. Name = "Updater.SingleThreadWorker",
  412. };
  413. worker.Start();
  414. }
  415. [SupportedOSPlatform("linux")]
  416. [SupportedOSPlatform("macos")]
  417. private static void ExtractTarGzipFile(TaskDialog taskDialog, string archivePath, string outputDirectoryPath)
  418. {
  419. using Stream inStream = File.OpenRead(archivePath);
  420. using GZipInputStream gzipStream = new(inStream);
  421. using TarInputStream tarStream = new(gzipStream, Encoding.ASCII);
  422. TarEntry tarEntry;
  423. while ((tarEntry = tarStream.GetNextEntry()) is not null)
  424. {
  425. if (tarEntry.IsDirectory)
  426. {
  427. continue;
  428. }
  429. string outPath = Path.Combine(outputDirectoryPath, tarEntry.Name);
  430. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  431. using FileStream outStream = File.OpenWrite(outPath);
  432. tarStream.CopyEntryContents(outStream);
  433. File.SetUnixFileMode(outPath, (UnixFileMode)tarEntry.TarHeader.Mode);
  434. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc));
  435. Dispatcher.UIThread.Post(() =>
  436. {
  437. if (tarEntry is null)
  438. {
  439. return;
  440. }
  441. taskDialog.SetProgressBarState(GetPercentage(tarEntry.Size, inStream.Length), TaskDialogProgressState.Normal);
  442. });
  443. }
  444. }
  445. private static void ExtractZipFile(TaskDialog taskDialog, string archivePath, string outputDirectoryPath)
  446. {
  447. using Stream inStream = File.OpenRead(archivePath);
  448. using ZipFile zipFile = new(inStream);
  449. double count = 0;
  450. foreach (ZipEntry zipEntry in zipFile)
  451. {
  452. count++;
  453. if (zipEntry.IsDirectory)
  454. {
  455. continue;
  456. }
  457. string outPath = Path.Combine(outputDirectoryPath, zipEntry.Name);
  458. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  459. using Stream zipStream = zipFile.GetInputStream(zipEntry);
  460. using FileStream outStream = File.OpenWrite(outPath);
  461. zipStream.CopyTo(outStream);
  462. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(zipEntry.DateTime, DateTimeKind.Utc));
  463. Dispatcher.UIThread.Post(() =>
  464. {
  465. taskDialog.SetProgressBarState(GetPercentage(count, zipFile.Count), TaskDialogProgressState.Normal);
  466. });
  467. }
  468. }
  469. private static void InstallUpdate(TaskDialog taskDialog, string updateFile)
  470. {
  471. // Extract Update
  472. taskDialog.SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterExtracting];
  473. taskDialog.SetProgressBarState(0, TaskDialogProgressState.Normal);
  474. if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
  475. {
  476. ExtractTarGzipFile(taskDialog, updateFile, _updateDir);
  477. }
  478. else if (OperatingSystem.IsWindows())
  479. {
  480. ExtractZipFile(taskDialog, updateFile, _updateDir);
  481. }
  482. else
  483. {
  484. throw new NotSupportedException();
  485. }
  486. // Delete downloaded zip
  487. File.Delete(updateFile);
  488. List<string> allFiles = EnumerateFilesToDelete().ToList();
  489. taskDialog.SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterRenaming];
  490. taskDialog.SetProgressBarState(0, TaskDialogProgressState.Normal);
  491. // NOTE: On macOS, replacement is delayed to the restart phase.
  492. if (!OperatingSystem.IsMacOS())
  493. {
  494. // Replace old files
  495. double count = 0;
  496. foreach (string file in allFiles)
  497. {
  498. count++;
  499. try
  500. {
  501. File.Move(file, file + ".ryuold");
  502. Dispatcher.UIThread.InvokeAsync(() =>
  503. {
  504. taskDialog.SetProgressBarState(GetPercentage(count, allFiles.Count), TaskDialogProgressState.Normal);
  505. });
  506. }
  507. catch
  508. {
  509. Logger.Warning?.Print(LogClass.Application, LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.UpdaterRenameFailed, file));
  510. }
  511. }
  512. Dispatcher.UIThread.InvokeAsync(() =>
  513. {
  514. taskDialog.SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterAddingFiles];
  515. taskDialog.SetProgressBarState(0, TaskDialogProgressState.Normal);
  516. });
  517. MoveAllFilesOver(_updatePublishDir, _homeDir, taskDialog);
  518. Directory.Delete(_updateDir, true);
  519. }
  520. _updateSuccessful = true;
  521. taskDialog.Hide();
  522. }
  523. public static bool CanUpdate(bool showWarnings = false)
  524. {
  525. #if !DISABLE_UPDATER
  526. if (!NetworkInterface.GetIsNetworkAvailable())
  527. {
  528. if (showWarnings)
  529. {
  530. Dispatcher.UIThread.InvokeAsync(() =>
  531. ContentDialogHelper.CreateWarningDialog(
  532. LocaleManager.Instance[LocaleKeys.DialogUpdaterNoInternetMessage],
  533. LocaleManager.Instance[LocaleKeys.DialogUpdaterNoInternetSubMessage])
  534. );
  535. }
  536. return false;
  537. }
  538. if (Program.Version.Contains("dirty") || !ReleaseInformation.IsValid)
  539. {
  540. if (showWarnings)
  541. {
  542. Dispatcher.UIThread.InvokeAsync(() =>
  543. ContentDialogHelper.CreateWarningDialog(
  544. LocaleManager.Instance[LocaleKeys.DialogUpdaterDirtyBuildMessage],
  545. LocaleManager.Instance[LocaleKeys.DialogUpdaterDirtyBuildSubMessage])
  546. );
  547. }
  548. return false;
  549. }
  550. return true;
  551. #else
  552. if (showWarnings)
  553. {
  554. Dispatcher.UIThread.InvokeAsync(() =>
  555. ContentDialogHelper.CreateWarningDialog(
  556. LocaleManager.Instance[LocaleKeys.UpdaterDisabledWarningTitle],
  557. LocaleManager.Instance[LocaleKeys.DialogUpdaterDirtyBuildSubMessage])
  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. }