Updater.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. using Avalonia.Threading;
  2. using ICSharpCode.SharpZipLib.GZip;
  3. using ICSharpCode.SharpZipLib.Tar;
  4. using ICSharpCode.SharpZipLib.Zip;
  5. using Newtonsoft.Json.Linq;
  6. using Ryujinx.Ava;
  7. using Ryujinx.Ava.Common.Locale;
  8. using Ryujinx.Ava.Ui.Controls;
  9. using Ryujinx.Ava.Ui.Windows;
  10. using Ryujinx.Common;
  11. using Ryujinx.Common.Logging;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Net;
  17. using System.Net.Http;
  18. using System.Net.NetworkInformation;
  19. using System.Runtime.InteropServices;
  20. using System.Text;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. namespace Ryujinx.Modules
  24. {
  25. internal static class Updater
  26. {
  27. private const string GitHubApiURL = "https://api.github.com";
  28. internal static bool Running;
  29. private static readonly string HomeDir = AppDomain.CurrentDomain.BaseDirectory;
  30. private static readonly string UpdateDir = Path.Combine(Path.GetTempPath(), "Ryujinx", "update");
  31. private static readonly string UpdatePublishDir = Path.Combine(UpdateDir, "publish");
  32. private static readonly int ConnectionCount = 4;
  33. private static string _buildVer;
  34. private static string _platformExt;
  35. private static string _buildUrl;
  36. private static long _buildSize;
  37. private static readonly string[] WindowsDependencyDirs = Array.Empty<string>();
  38. public static async Task BeginParse(MainWindow mainWindow, bool showVersionUpToDate)
  39. {
  40. if (Running)
  41. {
  42. return;
  43. }
  44. Running = true;
  45. mainWindow.CanUpdate = false;
  46. // Detect current platform
  47. if (OperatingSystem.IsMacOS())
  48. {
  49. _platformExt = "osx_x64.zip";
  50. }
  51. else if (OperatingSystem.IsWindows())
  52. {
  53. _platformExt = "win_x64.zip";
  54. }
  55. else if (OperatingSystem.IsLinux())
  56. {
  57. _platformExt = "linux_x64.tar.gz";
  58. }
  59. Version newVersion;
  60. Version currentVersion;
  61. try
  62. {
  63. currentVersion = Version.Parse(Program.Version);
  64. }
  65. catch
  66. {
  67. Logger.Error?.Print(LogClass.Application, "Failed to convert the current Ryujinx version!");
  68. Dispatcher.UIThread.Post(async () =>
  69. {
  70. await ContentDialogHelper.CreateWarningDialog(mainWindow, LocaleManager.Instance["DialogUpdaterConvertFailedMessage"], LocaleManager.Instance["DialogUpdaterCancelUpdateMessage"]);
  71. });
  72. return;
  73. }
  74. // Get latest version number from GitHub API
  75. try
  76. {
  77. using (HttpClient jsonClient = ConstructHttpClient())
  78. {
  79. string buildInfoURL = $"{GitHubApiURL}/repos/{ReleaseInformations.ReleaseChannelOwner}/{ReleaseInformations.ReleaseChannelRepo}/releases/latest";
  80. string fetchedJson = await jsonClient.GetStringAsync(buildInfoURL);
  81. JObject jsonRoot = JObject.Parse(fetchedJson);
  82. JToken assets = jsonRoot["assets"];
  83. _buildVer = (string)jsonRoot["name"];
  84. foreach (JToken asset in assets)
  85. {
  86. string assetName = (string)asset["name"];
  87. string assetState = (string)asset["state"];
  88. string downloadURL = (string)asset["browser_download_url"];
  89. if (assetName.StartsWith("test-ava-ryujinx") && assetName.EndsWith(_platformExt))
  90. {
  91. _buildUrl = downloadURL;
  92. if (assetState != "uploaded")
  93. {
  94. if (showVersionUpToDate)
  95. {
  96. Dispatcher.UIThread.Post(async () =>
  97. {
  98. await ContentDialogHelper.CreateUpdaterInfoDialog(mainWindow, LocaleManager.Instance["DialogUpdaterAlreadyOnLatestVersionMessage"], "");
  99. });
  100. }
  101. return;
  102. }
  103. break;
  104. }
  105. }
  106. // If build not done, assume no new update are availaible.
  107. if (_buildUrl == null)
  108. {
  109. if (showVersionUpToDate)
  110. {
  111. Dispatcher.UIThread.Post(async () =>
  112. {
  113. await ContentDialogHelper.CreateUpdaterInfoDialog(mainWindow, LocaleManager.Instance["DialogUpdaterAlreadyOnLatestVersionMessage"], "");
  114. });
  115. }
  116. return;
  117. }
  118. }
  119. }
  120. catch (Exception exception)
  121. {
  122. Logger.Error?.Print(LogClass.Application, exception.Message);
  123. Dispatcher.UIThread.Post(async () =>
  124. {
  125. await ContentDialogHelper.CreateErrorDialog(mainWindow, LocaleManager.Instance["DialogUpdaterFailedToGetVersionMessage"]);
  126. });
  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. Dispatcher.UIThread.Post(async () =>
  137. {
  138. await ContentDialogHelper.CreateWarningDialog(mainWindow, LocaleManager.Instance["DialogUpdaterConvertFailedGithubMessage"], LocaleManager.Instance["DialogUpdaterCancelUpdateMessage"]);
  139. });
  140. return;
  141. }
  142. if (newVersion <= currentVersion)
  143. {
  144. if (showVersionUpToDate)
  145. {
  146. Dispatcher.UIThread.Post(async () =>
  147. {
  148. await ContentDialogHelper.CreateUpdaterInfoDialog(mainWindow, LocaleManager.Instance["DialogUpdaterAlreadyOnLatestVersionMessage"], "");
  149. });
  150. }
  151. Running = false;
  152. mainWindow.CanUpdate = true;
  153. return;
  154. }
  155. // Fetch build size information to learn chunk sizes.
  156. using (HttpClient buildSizeClient = ConstructHttpClient())
  157. {
  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. }
  171. Dispatcher.UIThread.Post(async () =>
  172. {
  173. // Show a message asking the user if they want to update
  174. UpdaterWindow updateDialog = new(mainWindow, newVersion, _buildUrl);
  175. await updateDialog.ShowDialog(mainWindow);
  176. });
  177. }
  178. private static HttpClient ConstructHttpClient()
  179. {
  180. HttpClient result = new HttpClient();
  181. // Required by GitHub to interract with APIs.
  182. result.DefaultRequestHeaders.Add("User-Agent", "Ryujinx-Updater/1.0.0");
  183. return result;
  184. }
  185. public static void UpdateRyujinx(UpdaterWindow updateDialog, string downloadUrl)
  186. {
  187. // Empty update dir, although it shouldn't ever have anything inside it
  188. if (Directory.Exists(UpdateDir))
  189. {
  190. Directory.Delete(UpdateDir, true);
  191. }
  192. Directory.CreateDirectory(UpdateDir);
  193. string updateFile = Path.Combine(UpdateDir, "update.bin");
  194. // Download the update .zip
  195. updateDialog.MainText.Text = LocaleManager.Instance["UpdaterDownloading"];
  196. updateDialog.ProgressBar.Value = 0;
  197. updateDialog.ProgressBar.Maximum = 100;
  198. Task.Run(() =>
  199. {
  200. if (_buildSize >= 0)
  201. {
  202. DoUpdateWithMultipleThreads(updateDialog, downloadUrl, updateFile);
  203. }
  204. else
  205. {
  206. DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
  207. }
  208. });
  209. }
  210. private static void DoUpdateWithMultipleThreads(UpdaterWindow updateDialog, string downloadUrl, string updateFile)
  211. {
  212. // Multi-Threaded Updater
  213. long chunkSize = _buildSize / ConnectionCount;
  214. long remainderChunk = _buildSize % ConnectionCount;
  215. int completedRequests = 0;
  216. int totalProgressPercentage = 0;
  217. int[] progressPercentage = new int[ConnectionCount];
  218. List<byte[]> list = new List<byte[]>(ConnectionCount);
  219. List<WebClient> webClients = new List<WebClient>(ConnectionCount);
  220. for (int i = 0; i < ConnectionCount; i++)
  221. {
  222. list.Add(Array.Empty<byte>());
  223. }
  224. for (int i = 0; i < ConnectionCount; i++)
  225. {
  226. #pragma warning disable SYSLIB0014
  227. // TODO: WebClient is obsolete and need to be replaced with a more complex logic using HttpClient.
  228. using (WebClient client = new WebClient())
  229. #pragma warning restore SYSLIB0014
  230. {
  231. webClients.Add(client);
  232. if (i == ConnectionCount - 1)
  233. {
  234. client.Headers.Add("Range", $"bytes={chunkSize * i}-{(chunkSize * (i + 1) - 1) + remainderChunk}");
  235. }
  236. else
  237. {
  238. client.Headers.Add("Range", $"bytes={chunkSize * i}-{chunkSize * (i + 1) - 1}");
  239. }
  240. client.DownloadProgressChanged += (_, args) =>
  241. {
  242. int index = (int)args.UserState;
  243. Interlocked.Add(ref totalProgressPercentage, -1 * progressPercentage[index]);
  244. Interlocked.Exchange(ref progressPercentage[index], args.ProgressPercentage);
  245. Interlocked.Add(ref totalProgressPercentage, args.ProgressPercentage);
  246. updateDialog.ProgressBar.Value = totalProgressPercentage / ConnectionCount;
  247. };
  248. client.DownloadDataCompleted += (_, args) =>
  249. {
  250. int index = (int)args.UserState;
  251. if (args.Cancelled)
  252. {
  253. webClients[index].Dispose();
  254. return;
  255. }
  256. list[index] = args.Result;
  257. Interlocked.Increment(ref completedRequests);
  258. if (Interlocked.Equals(completedRequests, ConnectionCount))
  259. {
  260. byte[] mergedFileBytes = new byte[_buildSize];
  261. for (int connectionIndex = 0, destinationOffset = 0; connectionIndex < ConnectionCount; connectionIndex++)
  262. {
  263. Array.Copy(list[connectionIndex], 0, mergedFileBytes, destinationOffset, list[connectionIndex].Length);
  264. destinationOffset += list[connectionIndex].Length;
  265. }
  266. File.WriteAllBytes(updateFile, mergedFileBytes);
  267. try
  268. {
  269. InstallUpdate(updateDialog, updateFile);
  270. }
  271. catch (Exception e)
  272. {
  273. Logger.Warning?.Print(LogClass.Application, e.Message);
  274. Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater.");
  275. DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
  276. return;
  277. }
  278. }
  279. };
  280. try
  281. {
  282. client.DownloadDataAsync(new Uri(downloadUrl), i);
  283. }
  284. catch (WebException ex)
  285. {
  286. Logger.Warning?.Print(LogClass.Application, ex.Message);
  287. Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater.");
  288. for (int j = 0; j < webClients.Count; j++)
  289. {
  290. webClients[j].CancelAsync();
  291. }
  292. DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
  293. return;
  294. }
  295. }
  296. }
  297. }
  298. private static void DoUpdateWithSingleThreadWorker(UpdaterWindow updateDialog, string downloadUrl, string updateFile)
  299. {
  300. using (HttpClient client = new HttpClient())
  301. {
  302. // We do not want to timeout while downloading
  303. client.Timeout = TimeSpan.FromDays(1);
  304. using (HttpResponseMessage response = client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead).Result)
  305. using (Stream remoteFileStream = response.Content.ReadAsStreamAsync().Result)
  306. {
  307. using (Stream updateFileStream = File.Open(updateFile, FileMode.Create))
  308. {
  309. long totalBytes = response.Content.Headers.ContentLength.Value;
  310. long byteWritten = 0;
  311. byte[] buffer = new byte[32 * 1024];
  312. while (true)
  313. {
  314. int readSize = remoteFileStream.Read(buffer);
  315. if (readSize == 0)
  316. {
  317. break;
  318. }
  319. byteWritten += readSize;
  320. updateDialog.ProgressBar.Value = ((double)byteWritten / totalBytes) * 100;
  321. updateFileStream.Write(buffer, 0, readSize);
  322. }
  323. }
  324. }
  325. InstallUpdate(updateDialog, updateFile);
  326. }
  327. }
  328. private static void DoUpdateWithSingleThread(UpdaterWindow updateDialog, string downloadUrl, string updateFile)
  329. {
  330. Thread worker = new Thread(() => DoUpdateWithSingleThreadWorker(updateDialog, downloadUrl, updateFile));
  331. worker.Name = "Updater.SingleThreadWorker";
  332. worker.Start();
  333. }
  334. [DllImport("libc", SetLastError = true)]
  335. private static extern int chmod(string path, uint mode);
  336. private static void SetUnixPermissions()
  337. {
  338. string ryuBin = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ryujinx");
  339. if (!OperatingSystem.IsWindows())
  340. {
  341. chmod(ryuBin, 493);
  342. }
  343. }
  344. private static async void InstallUpdate(UpdaterWindow updateDialog, string updateFile)
  345. {
  346. // Extract Update
  347. updateDialog.MainText.Text = LocaleManager.Instance["UpdaterExtracting"];
  348. updateDialog.ProgressBar.Value = 0;
  349. if (OperatingSystem.IsLinux())
  350. {
  351. using (Stream inStream = File.OpenRead(updateFile))
  352. using (Stream gzipStream = new GZipInputStream(inStream))
  353. using (TarInputStream tarStream = new TarInputStream(gzipStream, Encoding.ASCII))
  354. {
  355. updateDialog.ProgressBar.Maximum = inStream.Length;
  356. await Task.Run(() =>
  357. {
  358. TarEntry tarEntry;
  359. while ((tarEntry = tarStream.GetNextEntry()) != null)
  360. {
  361. if (tarEntry.IsDirectory) continue;
  362. string outPath = Path.Combine(UpdateDir, tarEntry.Name);
  363. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  364. using (FileStream outStream = File.OpenWrite(outPath))
  365. {
  366. tarStream.CopyEntryContents(outStream);
  367. }
  368. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc));
  369. TarEntry entry = tarEntry;
  370. Dispatcher.UIThread.Post(() =>
  371. {
  372. updateDialog.ProgressBar.Value += entry.Size;
  373. });
  374. }
  375. });
  376. updateDialog.ProgressBar.Value = inStream.Length;
  377. }
  378. }
  379. else
  380. {
  381. using (Stream inStream = File.OpenRead(updateFile))
  382. using (ZipFile zipFile = new ZipFile(inStream))
  383. {
  384. updateDialog.ProgressBar.Maximum = zipFile.Count;
  385. await Task.Run(() =>
  386. {
  387. foreach (ZipEntry zipEntry in zipFile)
  388. {
  389. if (zipEntry.IsDirectory) continue;
  390. string outPath = Path.Combine(UpdateDir, zipEntry.Name);
  391. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  392. using (Stream zipStream = zipFile.GetInputStream(zipEntry))
  393. using (FileStream outStream = File.OpenWrite(outPath))
  394. {
  395. zipStream.CopyTo(outStream);
  396. }
  397. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(zipEntry.DateTime, DateTimeKind.Utc));
  398. Dispatcher.UIThread.Post(() =>
  399. {
  400. updateDialog.ProgressBar.Value++;
  401. });
  402. }
  403. });
  404. }
  405. }
  406. // Delete downloaded zip
  407. File.Delete(updateFile);
  408. List<string> allFiles = EnumerateFilesToDelete().ToList();
  409. updateDialog.MainText.Text = LocaleManager.Instance["UpdaterRenaming"];
  410. updateDialog.ProgressBar.Value = 0;
  411. updateDialog.ProgressBar.Maximum = allFiles.Count;
  412. // Replace old files
  413. await Task.Run(() =>
  414. {
  415. foreach (string file in allFiles)
  416. {
  417. try
  418. {
  419. File.Move(file, file + ".ryuold");
  420. Dispatcher.UIThread.Post(() =>
  421. {
  422. updateDialog.ProgressBar.Value++;
  423. });
  424. }
  425. catch
  426. {
  427. Logger.Warning?.Print(LogClass.Application, string.Format(LocaleManager.Instance["UpdaterRenameFailed"], file));
  428. }
  429. }
  430. Dispatcher.UIThread.Post(() =>
  431. {
  432. updateDialog.MainText.Text = LocaleManager.Instance["UpdaterAddingFiles"];
  433. updateDialog.ProgressBar.Value = 0;
  434. updateDialog.ProgressBar.Maximum = Directory.GetFiles(UpdatePublishDir, "*", SearchOption.AllDirectories).Length;
  435. });
  436. MoveAllFilesOver(UpdatePublishDir, HomeDir, updateDialog);
  437. });
  438. Directory.Delete(UpdateDir, true);
  439. SetUnixPermissions();
  440. updateDialog.MainText.Text = LocaleManager.Instance["DialogUpdaterCompleteMessage"];
  441. updateDialog.SecondaryText.Text = LocaleManager.Instance["DialogUpdaterRestartMessage"];
  442. updateDialog.ProgressBar.IsVisible = false;
  443. updateDialog.ButtonBox.IsVisible = true;
  444. }
  445. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  446. public static bool CanUpdate(bool showWarnings, StyleableWindow parent)
  447. {
  448. #if !DISABLE_UPDATER
  449. if (RuntimeInformation.OSArchitecture != Architecture.X64)
  450. {
  451. if (showWarnings)
  452. {
  453. ContentDialogHelper.CreateWarningDialog(parent, LocaleManager.Instance["DialogUpdaterArchNotSupportedMessage"],
  454. LocaleManager.Instance["DialogUpdaterArchNotSupportedSubMessage"]);
  455. }
  456. return false;
  457. }
  458. if (!NetworkInterface.GetIsNetworkAvailable())
  459. {
  460. if (showWarnings)
  461. {
  462. ContentDialogHelper.CreateWarningDialog(parent, LocaleManager.Instance["DialogUpdaterNoInternetMessage"],
  463. LocaleManager.Instance["DialogUpdaterNoInternetSubMessage"]);
  464. }
  465. return false;
  466. }
  467. if (Program.Version.Contains("dirty") || !ReleaseInformations.IsValid())
  468. {
  469. if (showWarnings)
  470. {
  471. ContentDialogHelper.CreateWarningDialog(parent, LocaleManager.Instance["DialogUpdaterDirtyBuildMessage"],
  472. LocaleManager.Instance["DialogUpdaterDirtyBuildSubMessage"]);
  473. }
  474. return false;
  475. }
  476. return true;
  477. #else
  478. if (showWarnings)
  479. {
  480. if (ReleaseInformations.IsFlatHubBuild())
  481. {
  482. ContentDialogHelper.CreateWarningDialog(parent,
  483. LocaleManager.Instance["UpdaterDisabledWarningTitle"], LocaleManager.Instance["DialogUpdaterFlatpakNotSupportedMessage"]);
  484. }
  485. else
  486. {
  487. ContentDialogHelper.CreateWarningDialog(parent,
  488. LocaleManager.Instance["UpdaterDisabledWarningTitle"], LocaleManager.Instance["DialogUpdaterDirtyBuildSubMessage"]);
  489. }
  490. }
  491. return false;
  492. #endif
  493. }
  494. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  495. // NOTE: This method should always reflect the latest build layout.s
  496. private static IEnumerable<string> EnumerateFilesToDelete()
  497. {
  498. var files = Directory.EnumerateFiles(HomeDir); // All files directly in base dir.
  499. if (OperatingSystem.IsWindows())
  500. {
  501. foreach (string dir in WindowsDependencyDirs)
  502. {
  503. string dirPath = Path.Combine(HomeDir, dir);
  504. if (Directory.Exists(dirPath))
  505. {
  506. files = files.Concat(Directory.EnumerateFiles(dirPath, "*", SearchOption.AllDirectories));
  507. }
  508. }
  509. }
  510. return files;
  511. }
  512. private static void MoveAllFilesOver(string root, string dest, UpdaterWindow dialog)
  513. {
  514. foreach (string directory in Directory.GetDirectories(root))
  515. {
  516. string dirName = Path.GetFileName(directory);
  517. if (!Directory.Exists(Path.Combine(dest, dirName)))
  518. {
  519. Directory.CreateDirectory(Path.Combine(dest, dirName));
  520. }
  521. MoveAllFilesOver(directory, Path.Combine(dest, dirName), dialog);
  522. }
  523. foreach (string file in Directory.GetFiles(root))
  524. {
  525. File.Move(file, Path.Combine(dest, Path.GetFileName(file)), true);
  526. Dispatcher.UIThread.InvokeAsync(() =>
  527. {
  528. dialog.ProgressBar.Value++;
  529. });
  530. }
  531. }
  532. public static void CleanupUpdate()
  533. {
  534. foreach (string file in Directory.GetFiles(HomeDir, "*.ryuold", SearchOption.AllDirectories))
  535. {
  536. File.Delete(file);
  537. }
  538. }
  539. }
  540. }