Updater.cs 30 KB

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