Updater.cs 24 KB

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