Updater.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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 (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. private static void SetFileExecutable(string path)
  316. {
  317. const UnixFileMode ExecutableFileMode = UnixFileMode.UserExecute |
  318. UnixFileMode.UserWrite |
  319. UnixFileMode.UserRead |
  320. UnixFileMode.GroupRead |
  321. UnixFileMode.GroupWrite |
  322. UnixFileMode.OtherRead |
  323. UnixFileMode.OtherWrite;
  324. if (!OperatingSystem.IsWindows() && File.Exists(path))
  325. {
  326. File.SetUnixFileMode(path, ExecutableFileMode);
  327. }
  328. }
  329. private static async void InstallUpdate(UpdateDialog updateDialog, string updateFile)
  330. {
  331. // Extract Update
  332. updateDialog.MainText.Text = "Extracting Update...";
  333. updateDialog.ProgressBar.Value = 0;
  334. if (OperatingSystem.IsLinux())
  335. {
  336. using (Stream inStream = File.OpenRead(updateFile))
  337. using (Stream gzipStream = new GZipInputStream(inStream))
  338. using (TarInputStream tarStream = new TarInputStream(gzipStream, Encoding.ASCII))
  339. {
  340. updateDialog.ProgressBar.MaxValue = inStream.Length;
  341. await Task.Run(() =>
  342. {
  343. TarEntry tarEntry;
  344. while ((tarEntry = tarStream.GetNextEntry()) != null)
  345. {
  346. if (tarEntry.IsDirectory) continue;
  347. string outPath = Path.Combine(UpdateDir, tarEntry.Name);
  348. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  349. using (FileStream outStream = File.OpenWrite(outPath))
  350. {
  351. tarStream.CopyEntryContents(outStream);
  352. }
  353. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc));
  354. TarEntry entry = tarEntry;
  355. Application.Invoke(delegate
  356. {
  357. updateDialog.ProgressBar.Value += entry.Size;
  358. });
  359. }
  360. });
  361. updateDialog.ProgressBar.Value = inStream.Length;
  362. }
  363. }
  364. else
  365. {
  366. using (Stream inStream = File.OpenRead(updateFile))
  367. using (ZipFile zipFile = new ZipFile(inStream))
  368. {
  369. updateDialog.ProgressBar.MaxValue = zipFile.Count;
  370. await Task.Run(() =>
  371. {
  372. foreach (ZipEntry zipEntry in zipFile)
  373. {
  374. if (zipEntry.IsDirectory) continue;
  375. string outPath = Path.Combine(UpdateDir, zipEntry.Name);
  376. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  377. using (Stream zipStream = zipFile.GetInputStream(zipEntry))
  378. using (FileStream outStream = File.OpenWrite(outPath))
  379. {
  380. zipStream.CopyTo(outStream);
  381. }
  382. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(zipEntry.DateTime, DateTimeKind.Utc));
  383. Application.Invoke(delegate
  384. {
  385. updateDialog.ProgressBar.Value++;
  386. });
  387. }
  388. });
  389. }
  390. }
  391. // Delete downloaded zip
  392. File.Delete(updateFile);
  393. List<string> allFiles = EnumerateFilesToDelete().ToList();
  394. updateDialog.MainText.Text = "Renaming Old Files...";
  395. updateDialog.ProgressBar.Value = 0;
  396. updateDialog.ProgressBar.MaxValue = allFiles.Count;
  397. // Replace old files
  398. await Task.Run(() =>
  399. {
  400. foreach (string file in allFiles)
  401. {
  402. try
  403. {
  404. File.Move(file, file + ".ryuold");
  405. Application.Invoke(delegate
  406. {
  407. updateDialog.ProgressBar.Value++;
  408. });
  409. }
  410. catch
  411. {
  412. Logger.Warning?.Print(LogClass.Application, "Updater was unable to rename file: " + file);
  413. }
  414. }
  415. Application.Invoke(delegate
  416. {
  417. updateDialog.MainText.Text = "Adding New Files...";
  418. updateDialog.ProgressBar.Value = 0;
  419. updateDialog.ProgressBar.MaxValue = Directory.GetFiles(UpdatePublishDir, "*", SearchOption.AllDirectories).Length;
  420. });
  421. MoveAllFilesOver(UpdatePublishDir, HomeDir, updateDialog);
  422. });
  423. Directory.Delete(UpdateDir, true);
  424. SetFileExecutable(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ryujinx"));
  425. updateDialog.MainText.Text = "Update Complete!";
  426. updateDialog.SecondaryText.Text = "Do you want to restart Ryujinx now?";
  427. updateDialog.Modal = true;
  428. updateDialog.ProgressBar.Hide();
  429. updateDialog.YesButton.Show();
  430. updateDialog.NoButton.Show();
  431. }
  432. public static bool CanUpdate(bool showWarnings)
  433. {
  434. #if !DISABLE_UPDATER
  435. if (RuntimeInformation.OSArchitecture != Architecture.X64)
  436. {
  437. if (showWarnings)
  438. {
  439. GtkDialog.CreateWarningDialog("You are not running a supported system architecture!", "(Only x64 systems are supported!)");
  440. }
  441. return false;
  442. }
  443. if (!NetworkInterface.GetIsNetworkAvailable())
  444. {
  445. if (showWarnings)
  446. {
  447. GtkDialog.CreateWarningDialog("You are not connected to the Internet!", "Please verify that you have a working Internet connection!");
  448. }
  449. return false;
  450. }
  451. if (Program.Version.Contains("dirty") || !ReleaseInformations.IsValid())
  452. {
  453. if (showWarnings)
  454. {
  455. 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.");
  456. }
  457. return false;
  458. }
  459. return true;
  460. #else
  461. if (showWarnings)
  462. {
  463. if (ReleaseInformations.IsFlatHubBuild())
  464. {
  465. GtkDialog.CreateWarningDialog("Updater Disabled!", "Please update Ryujinx via FlatHub.");
  466. }
  467. else
  468. {
  469. GtkDialog.CreateWarningDialog("Updater Disabled!", "Please download Ryujinx at https://ryujinx.org/ if you are looking for a supported version.");
  470. }
  471. }
  472. return false;
  473. #endif
  474. }
  475. // NOTE: This method should always reflect the latest build layout.
  476. private static IEnumerable<string> EnumerateFilesToDelete()
  477. {
  478. var files = Directory.EnumerateFiles(HomeDir); // All files directly in base dir.
  479. if (OperatingSystem.IsWindows())
  480. {
  481. foreach (string dir in WindowsDependencyDirs)
  482. {
  483. string dirPath = Path.Combine(HomeDir, dir);
  484. if (Directory.Exists(dirPath))
  485. {
  486. files = files.Concat(Directory.EnumerateFiles(dirPath, "*", SearchOption.AllDirectories));
  487. }
  488. }
  489. }
  490. return files;
  491. }
  492. private static void MoveAllFilesOver(string root, string dest, UpdateDialog dialog)
  493. {
  494. foreach (string directory in Directory.GetDirectories(root))
  495. {
  496. string dirName = Path.GetFileName(directory);
  497. if (!Directory.Exists(Path.Combine(dest, dirName)))
  498. {
  499. Directory.CreateDirectory(Path.Combine(dest, dirName));
  500. }
  501. MoveAllFilesOver(directory, Path.Combine(dest, dirName), dialog);
  502. }
  503. foreach (string file in Directory.GetFiles(root))
  504. {
  505. File.Move(file, Path.Combine(dest, Path.GetFileName(file)), true);
  506. Application.Invoke(delegate
  507. {
  508. dialog.ProgressBar.Value++;
  509. });
  510. }
  511. }
  512. public static void CleanupUpdate()
  513. {
  514. foreach (string file in EnumerateFilesToDelete())
  515. {
  516. if (Path.GetExtension(file).EndsWith(".ryuold"))
  517. {
  518. File.Delete(file);
  519. }
  520. }
  521. }
  522. }
  523. }