Updater.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. using Gtk;
  2. using ICSharpCode.SharpZipLib.GZip;
  3. using ICSharpCode.SharpZipLib.Tar;
  4. using ICSharpCode.SharpZipLib.Zip;
  5. using Ryujinx.Common;
  6. using Ryujinx.Common.Logging;
  7. using Ryujinx.Common.Utilities;
  8. using Ryujinx.Ui;
  9. using Ryujinx.Ui.Common.Models.Github;
  10. using Ryujinx.Ui.Widgets;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Net.Http;
  17. using System.Net.NetworkInformation;
  18. using System.Runtime.InteropServices;
  19. using System.Text;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. namespace Ryujinx.Modules
  23. {
  24. public static class Updater
  25. {
  26. private const string GitHubApiURL = "https://api.github.com";
  27. private const int ConnectionCount = 4;
  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 string _buildVer;
  33. private static string _platformExt;
  34. private static string _buildUrl;
  35. private static long _buildSize;
  36. private static readonly GithubReleasesJsonSerializerContext SerializerContext = new(JsonHelper.GetDefaultSerializerOptions());
  37. // On Windows, GtkSharp.Dependencies adds these extra dirs that must be cleaned during updates.
  38. private static readonly string[] WindowsDependencyDirs = new string[] { "bin", "etc", "lib", "share" };
  39. private static HttpClient ConstructHttpClient()
  40. {
  41. HttpClient result = new HttpClient();
  42. // Required by GitHub to interact with APIs.
  43. result.DefaultRequestHeaders.Add("User-Agent", "Ryujinx-Updater/1.0.0");
  44. return result;
  45. }
  46. public static async Task BeginParse(MainWindow mainWindow, bool showVersionUpToDate)
  47. {
  48. if (Running) return;
  49. Running = true;
  50. mainWindow.UpdateMenuItem.Sensitive = false;
  51. int artifactIndex = -1;
  52. // Detect current platform
  53. if (OperatingSystem.IsMacOS())
  54. {
  55. _platformExt = "osx_x64.zip";
  56. artifactIndex = 1;
  57. }
  58. else if (OperatingSystem.IsWindows())
  59. {
  60. _platformExt = "win_x64.zip";
  61. artifactIndex = 2;
  62. }
  63. else if (OperatingSystem.IsLinux())
  64. {
  65. _platformExt = "linux_x64.tar.gz";
  66. artifactIndex = 0;
  67. }
  68. if (artifactIndex == -1)
  69. {
  70. GtkDialog.CreateErrorDialog("Your platform is not supported!");
  71. return;
  72. }
  73. Version newVersion;
  74. Version currentVersion;
  75. try
  76. {
  77. currentVersion = Version.Parse(Program.Version);
  78. }
  79. catch
  80. {
  81. GtkDialog.CreateWarningDialog("Failed to convert the current Ryujinx version.", "Cancelling Update!");
  82. Logger.Error?.Print(LogClass.Application, "Failed to convert the current Ryujinx version!");
  83. return;
  84. }
  85. // Get latest version number from GitHub API
  86. try
  87. {
  88. using HttpClient jsonClient = ConstructHttpClient();
  89. string buildInfoURL = $"{GitHubApiURL}/repos/{ReleaseInformation.ReleaseChannelOwner}/{ReleaseInformation.ReleaseChannelRepo}/releases/latest";
  90. // Fetch latest build information
  91. string fetchedJson = await jsonClient.GetStringAsync(buildInfoURL);
  92. var fetched = JsonHelper.Deserialize(fetchedJson, SerializerContext.GithubReleasesJsonResponse);
  93. _buildVer = fetched.Name;
  94. foreach (var asset in fetched.Assets)
  95. {
  96. if (asset.Name.StartsWith("ryujinx") && asset.Name.EndsWith(_platformExt))
  97. {
  98. _buildUrl = asset.BrowserDownloadUrl;
  99. if (asset.State != "uploaded")
  100. {
  101. if (showVersionUpToDate)
  102. {
  103. GtkDialog.CreateUpdaterInfoDialog("You are already using the latest version of Ryujinx!", "");
  104. }
  105. return;
  106. }
  107. break;
  108. }
  109. }
  110. if (_buildUrl == null)
  111. {
  112. if (showVersionUpToDate)
  113. {
  114. GtkDialog.CreateUpdaterInfoDialog("You are already using the latest version of Ryujinx!", "");
  115. }
  116. return;
  117. }
  118. }
  119. catch (Exception exception)
  120. {
  121. Logger.Error?.Print(LogClass.Application, exception.Message);
  122. GtkDialog.CreateErrorDialog("An error occurred when trying to get release information from GitHub Release. This can be caused if a new release is being compiled by GitHub Actions. Try again in a few minutes.");
  123. return;
  124. }
  125. try
  126. {
  127. newVersion = Version.Parse(_buildVer);
  128. }
  129. catch
  130. {
  131. GtkDialog.CreateWarningDialog("Failed to convert the received Ryujinx version from GitHub Release.", "Cancelling Update!");
  132. Logger.Error?.Print(LogClass.Application, "Failed to convert the received Ryujinx version from GitHub Release!");
  133. return;
  134. }
  135. if (newVersion <= currentVersion)
  136. {
  137. if (showVersionUpToDate)
  138. {
  139. GtkDialog.CreateUpdaterInfoDialog("You are already using the latest version of Ryujinx!", "");
  140. }
  141. Running = false;
  142. mainWindow.UpdateMenuItem.Sensitive = true;
  143. return;
  144. }
  145. // Fetch build size information to learn chunk sizes.
  146. using (HttpClient buildSizeClient = ConstructHttpClient())
  147. {
  148. try
  149. {
  150. buildSizeClient.DefaultRequestHeaders.Add("Range", "bytes=0-0");
  151. HttpResponseMessage message = await buildSizeClient.GetAsync(new Uri(_buildUrl), HttpCompletionOption.ResponseHeadersRead);
  152. _buildSize = message.Content.Headers.ContentRange.Length.Value;
  153. }
  154. catch (Exception ex)
  155. {
  156. Logger.Warning?.Print(LogClass.Application, ex.Message);
  157. Logger.Warning?.Print(LogClass.Application, "Couldn't determine build size for update, using single-threaded updater");
  158. _buildSize = -1;
  159. }
  160. }
  161. // Show a message asking the user if they want to update
  162. UpdateDialog updateDialog = new UpdateDialog(mainWindow, newVersion, _buildUrl);
  163. updateDialog.Show();
  164. }
  165. public static void UpdateRyujinx(UpdateDialog updateDialog, string downloadUrl)
  166. {
  167. // Empty update dir, although it shouldn't ever have anything inside it
  168. if (Directory.Exists(UpdateDir))
  169. {
  170. Directory.Delete(UpdateDir, true);
  171. }
  172. Directory.CreateDirectory(UpdateDir);
  173. string updateFile = Path.Combine(UpdateDir, "update.bin");
  174. // Download the update .zip
  175. updateDialog.MainText.Text = "Downloading Update...";
  176. updateDialog.ProgressBar.Value = 0;
  177. updateDialog.ProgressBar.MaxValue = 100;
  178. if (_buildSize >= 0)
  179. {
  180. DoUpdateWithMultipleThreads(updateDialog, downloadUrl, updateFile);
  181. }
  182. else
  183. {
  184. DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
  185. }
  186. }
  187. private static void DoUpdateWithMultipleThreads(UpdateDialog updateDialog, string downloadUrl, string updateFile)
  188. {
  189. // Multi-Threaded Updater
  190. long chunkSize = _buildSize / ConnectionCount;
  191. long remainderChunk = _buildSize % ConnectionCount;
  192. int completedRequests = 0;
  193. int totalProgressPercentage = 0;
  194. int[] progressPercentage = new int[ConnectionCount];
  195. List<byte[]> list = new List<byte[]>(ConnectionCount);
  196. List<WebClient> webClients = new List<WebClient>(ConnectionCount);
  197. for (int i = 0; i < ConnectionCount; i++)
  198. {
  199. list.Add(Array.Empty<byte>());
  200. }
  201. for (int i = 0; i < ConnectionCount; i++)
  202. {
  203. #pragma warning disable SYSLIB0014
  204. // TODO: WebClient is obsolete and need to be replaced with a more complex logic using HttpClient.
  205. using WebClient client = new WebClient();
  206. #pragma warning restore SYSLIB0014
  207. webClients.Add(client);
  208. if (i == ConnectionCount - 1)
  209. {
  210. client.Headers.Add("Range", $"bytes={chunkSize * i}-{(chunkSize * (i + 1) - 1) + remainderChunk}");
  211. }
  212. else
  213. {
  214. client.Headers.Add("Range", $"bytes={chunkSize * i}-{chunkSize * (i + 1) - 1}");
  215. }
  216. client.DownloadProgressChanged += (_, args) =>
  217. {
  218. int index = (int)args.UserState;
  219. Interlocked.Add(ref totalProgressPercentage, -1 * progressPercentage[index]);
  220. Interlocked.Exchange(ref progressPercentage[index], args.ProgressPercentage);
  221. Interlocked.Add(ref totalProgressPercentage, args.ProgressPercentage);
  222. updateDialog.ProgressBar.Value = totalProgressPercentage / ConnectionCount;
  223. };
  224. client.DownloadDataCompleted += (_, args) =>
  225. {
  226. int index = (int)args.UserState;
  227. if (args.Cancelled)
  228. {
  229. webClients[index].Dispose();
  230. return;
  231. }
  232. list[index] = args.Result;
  233. Interlocked.Increment(ref completedRequests);
  234. if (Equals(completedRequests, ConnectionCount))
  235. {
  236. byte[] mergedFileBytes = new byte[_buildSize];
  237. for (int connectionIndex = 0, destinationOffset = 0; connectionIndex < ConnectionCount; connectionIndex++)
  238. {
  239. Array.Copy(list[connectionIndex], 0, mergedFileBytes, destinationOffset, list[connectionIndex].Length);
  240. destinationOffset += list[connectionIndex].Length;
  241. }
  242. File.WriteAllBytes(updateFile, mergedFileBytes);
  243. try
  244. {
  245. InstallUpdate(updateDialog, updateFile);
  246. }
  247. catch (Exception e)
  248. {
  249. Logger.Warning?.Print(LogClass.Application, e.Message);
  250. Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater.");
  251. DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
  252. return;
  253. }
  254. }
  255. };
  256. try
  257. {
  258. client.DownloadDataAsync(new Uri(downloadUrl), i);
  259. }
  260. catch (WebException ex)
  261. {
  262. Logger.Warning?.Print(LogClass.Application, ex.Message);
  263. Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater.");
  264. foreach (WebClient webClient in webClients)
  265. {
  266. webClient.CancelAsync();
  267. }
  268. DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
  269. return;
  270. }
  271. }
  272. }
  273. private static void DoUpdateWithSingleThreadWorker(UpdateDialog updateDialog, string downloadUrl, string updateFile)
  274. {
  275. using HttpClient client = new HttpClient();
  276. // We do not want to timeout while downloading
  277. client.Timeout = TimeSpan.FromDays(1);
  278. using (HttpResponseMessage response = client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead).Result)
  279. using (Stream remoteFileStream = response.Content.ReadAsStreamAsync().Result)
  280. {
  281. using (Stream updateFileStream = File.Open(updateFile, FileMode.Create))
  282. {
  283. long totalBytes = response.Content.Headers.ContentLength.Value;
  284. long byteWritten = 0;
  285. byte[] buffer = new byte[32 * 1024];
  286. while (true)
  287. {
  288. int readSize = remoteFileStream.Read(buffer);
  289. if (readSize == 0)
  290. {
  291. break;
  292. }
  293. byteWritten += readSize;
  294. updateDialog.ProgressBar.Value = ((double)byteWritten / totalBytes) * 100;
  295. updateFileStream.Write(buffer, 0, readSize);
  296. }
  297. }
  298. }
  299. InstallUpdate(updateDialog, updateFile);
  300. }
  301. private static void DoUpdateWithSingleThread(UpdateDialog updateDialog, string downloadUrl, string updateFile)
  302. {
  303. Thread worker = new Thread(() => DoUpdateWithSingleThreadWorker(updateDialog, downloadUrl, updateFile))
  304. {
  305. Name = "Updater.SingleThreadWorker"
  306. };
  307. worker.Start();
  308. }
  309. private static async void InstallUpdate(UpdateDialog updateDialog, string updateFile)
  310. {
  311. // Extract Update
  312. updateDialog.MainText.Text = "Extracting Update...";
  313. updateDialog.ProgressBar.Value = 0;
  314. if (OperatingSystem.IsLinux())
  315. {
  316. using Stream inStream = File.OpenRead(updateFile);
  317. using Stream gzipStream = new GZipInputStream(inStream);
  318. using TarInputStream tarStream = new TarInputStream(gzipStream, Encoding.ASCII);
  319. updateDialog.ProgressBar.MaxValue = inStream.Length;
  320. await Task.Run(() =>
  321. {
  322. TarEntry tarEntry;
  323. if (!OperatingSystem.IsWindows())
  324. {
  325. while ((tarEntry = tarStream.GetNextEntry()) != null)
  326. {
  327. if (tarEntry.IsDirectory) continue;
  328. string outPath = Path.Combine(UpdateDir, tarEntry.Name);
  329. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  330. using (FileStream outStream = File.OpenWrite(outPath))
  331. {
  332. tarStream.CopyEntryContents(outStream);
  333. }
  334. File.SetUnixFileMode(outPath, (UnixFileMode)tarEntry.TarHeader.Mode);
  335. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc));
  336. TarEntry entry = tarEntry;
  337. Application.Invoke(delegate
  338. {
  339. updateDialog.ProgressBar.Value += entry.Size;
  340. });
  341. }
  342. }
  343. });
  344. updateDialog.ProgressBar.Value = inStream.Length;
  345. }
  346. else
  347. {
  348. using Stream inStream = File.OpenRead(updateFile);
  349. using ZipFile zipFile = new ZipFile(inStream);
  350. updateDialog.ProgressBar.MaxValue = zipFile.Count;
  351. await Task.Run(() =>
  352. {
  353. foreach (ZipEntry zipEntry in zipFile)
  354. {
  355. if (zipEntry.IsDirectory) continue;
  356. string outPath = Path.Combine(UpdateDir, zipEntry.Name);
  357. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  358. using (Stream zipStream = zipFile.GetInputStream(zipEntry))
  359. using (FileStream outStream = File.OpenWrite(outPath))
  360. {
  361. zipStream.CopyTo(outStream);
  362. }
  363. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(zipEntry.DateTime, DateTimeKind.Utc));
  364. Application.Invoke(delegate
  365. {
  366. updateDialog.ProgressBar.Value++;
  367. });
  368. }
  369. });
  370. }
  371. // Delete downloaded zip
  372. File.Delete(updateFile);
  373. List<string> allFiles = EnumerateFilesToDelete().ToList();
  374. updateDialog.MainText.Text = "Renaming Old Files...";
  375. updateDialog.ProgressBar.Value = 0;
  376. updateDialog.ProgressBar.MaxValue = allFiles.Count;
  377. // Replace old files
  378. await Task.Run(() =>
  379. {
  380. foreach (string file in allFiles)
  381. {
  382. try
  383. {
  384. File.Move(file, file + ".ryuold");
  385. Application.Invoke(delegate
  386. {
  387. updateDialog.ProgressBar.Value++;
  388. });
  389. }
  390. catch
  391. {
  392. Logger.Warning?.Print(LogClass.Application, "Updater was unable to rename file: " + file);
  393. }
  394. }
  395. Application.Invoke(delegate
  396. {
  397. updateDialog.MainText.Text = "Adding New Files...";
  398. updateDialog.ProgressBar.Value = 0;
  399. updateDialog.ProgressBar.MaxValue = Directory.GetFiles(UpdatePublishDir, "*", SearchOption.AllDirectories).Length;
  400. });
  401. MoveAllFilesOver(UpdatePublishDir, HomeDir, updateDialog);
  402. });
  403. Directory.Delete(UpdateDir, true);
  404. updateDialog.MainText.Text = "Update Complete!";
  405. updateDialog.SecondaryText.Text = "Do you want to restart Ryujinx now?";
  406. updateDialog.Modal = true;
  407. updateDialog.ProgressBar.Hide();
  408. updateDialog.YesButton.Show();
  409. updateDialog.NoButton.Show();
  410. }
  411. public static bool CanUpdate(bool showWarnings)
  412. {
  413. #if !DISABLE_UPDATER
  414. if (RuntimeInformation.OSArchitecture != Architecture.X64)
  415. {
  416. if (showWarnings)
  417. {
  418. GtkDialog.CreateWarningDialog("You are not running a supported system architecture!", "(Only x64 systems are supported!)");
  419. }
  420. return false;
  421. }
  422. if (!NetworkInterface.GetIsNetworkAvailable())
  423. {
  424. if (showWarnings)
  425. {
  426. GtkDialog.CreateWarningDialog("You are not connected to the Internet!", "Please verify that you have a working Internet connection!");
  427. }
  428. return false;
  429. }
  430. if (Program.Version.Contains("dirty") || !ReleaseInformation.IsValid())
  431. {
  432. if (showWarnings)
  433. {
  434. GtkDialog.CreateWarningDialog("You cannot update a Dirty build of Ryujinx!", "Please download Ryujinx at https://ryujinx.org/ if you are looking for a supported version.");
  435. }
  436. return false;
  437. }
  438. return true;
  439. #else
  440. if (showWarnings)
  441. {
  442. if (ReleaseInformation.IsFlatHubBuild())
  443. {
  444. GtkDialog.CreateWarningDialog("Updater Disabled!", "Please update Ryujinx via FlatHub.");
  445. }
  446. else
  447. {
  448. GtkDialog.CreateWarningDialog("Updater Disabled!", "Please download Ryujinx at https://ryujinx.org/ if you are looking for a supported version.");
  449. }
  450. }
  451. return false;
  452. #endif
  453. }
  454. // NOTE: This method should always reflect the latest build layout.
  455. private static IEnumerable<string> EnumerateFilesToDelete()
  456. {
  457. var files = Directory.EnumerateFiles(HomeDir); // All files directly in base dir.
  458. if (OperatingSystem.IsWindows())
  459. {
  460. foreach (string dir in WindowsDependencyDirs)
  461. {
  462. string dirPath = Path.Combine(HomeDir, dir);
  463. if (Directory.Exists(dirPath))
  464. {
  465. files = files.Concat(Directory.EnumerateFiles(dirPath, "*", SearchOption.AllDirectories));
  466. }
  467. }
  468. }
  469. return files.Where(f => !new FileInfo(f).Attributes.HasFlag(FileAttributes.Hidden | FileAttributes.System));
  470. }
  471. private static void MoveAllFilesOver(string root, string dest, UpdateDialog dialog)
  472. {
  473. foreach (string directory in Directory.GetDirectories(root))
  474. {
  475. string dirName = Path.GetFileName(directory);
  476. if (!Directory.Exists(Path.Combine(dest, dirName)))
  477. {
  478. Directory.CreateDirectory(Path.Combine(dest, dirName));
  479. }
  480. MoveAllFilesOver(directory, Path.Combine(dest, dirName), dialog);
  481. }
  482. foreach (string file in Directory.GetFiles(root))
  483. {
  484. File.Move(file, Path.Combine(dest, Path.GetFileName(file)), true);
  485. Application.Invoke(delegate
  486. {
  487. dialog.ProgressBar.Value++;
  488. });
  489. }
  490. }
  491. public static void CleanupUpdate()
  492. {
  493. foreach (string file in EnumerateFilesToDelete())
  494. {
  495. if (Path.GetExtension(file).EndsWith(".ryuold"))
  496. {
  497. File.Delete(file);
  498. }
  499. }
  500. }
  501. }
  502. }