Updater.cs 23 KB

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