Updater.cs 22 KB

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