Updater.cs 29 KB

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