Updater.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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.Configuration;
  8. using Ryujinx.Common.Logging;
  9. using Ryujinx.Ui;
  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.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 (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  46. {
  47. _platformExt = "osx_x64.zip";
  48. artifactIndex = 1;
  49. }
  50. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  51. {
  52. _platformExt = "win_x64.zip";
  53. artifactIndex = 2;
  54. }
  55. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  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 (WebClient jsonClient = new WebClient())
  81. {
  82. // Fetch latest build information
  83. string fetchedJson = await jsonClient.DownloadStringTaskAsync($"{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 (WebClient buildSizeClient = new WebClient())
  128. {
  129. try
  130. {
  131. buildSizeClient.Headers.Add("Range", "bytes=0-0");
  132. await buildSizeClient.DownloadDataTaskAsync(new Uri(_buildUrl));
  133. string contentRange = buildSizeClient.ResponseHeaders["Content-Range"];
  134. _buildSize = long.Parse(contentRange.Substring(contentRange.IndexOf('/') + 1));
  135. }
  136. catch (Exception ex)
  137. {
  138. Logger.Warning?.Print(LogClass.Application, ex.Message);
  139. Logger.Warning?.Print(LogClass.Application, "Couldn't determine build size for update, using single-threaded updater");
  140. _buildSize = -1;
  141. }
  142. }
  143. // Show a message asking the user if they want to update
  144. UpdateDialog updateDialog = new UpdateDialog(mainWindow, newVersion, _buildUrl);
  145. updateDialog.Show();
  146. }
  147. public static void UpdateRyujinx(UpdateDialog updateDialog, string downloadUrl)
  148. {
  149. // Empty update dir, although it shouldn't ever have anything inside it
  150. if (Directory.Exists(UpdateDir))
  151. {
  152. Directory.Delete(UpdateDir, true);
  153. }
  154. Directory.CreateDirectory(UpdateDir);
  155. string updateFile = Path.Combine(UpdateDir, "update.bin");
  156. // Download the update .zip
  157. updateDialog.MainText.Text = "Downloading Update...";
  158. updateDialog.ProgressBar.Value = 0;
  159. updateDialog.ProgressBar.MaxValue = 100;
  160. if (_buildSize >= 0)
  161. {
  162. DoUpdateWithMultipleThreads(updateDialog, downloadUrl, updateFile);
  163. }
  164. else
  165. {
  166. DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
  167. }
  168. }
  169. private static void DoUpdateWithMultipleThreads(UpdateDialog updateDialog, string downloadUrl, string updateFile)
  170. {
  171. // Multi-Threaded Updater
  172. long chunkSize = _buildSize / ConnectionCount;
  173. long remainderChunk = _buildSize % ConnectionCount;
  174. int completedRequests = 0;
  175. int totalProgressPercentage = 0;
  176. int[] progressPercentage = new int[ConnectionCount];
  177. List<byte[]> list = new List<byte[]>(ConnectionCount);
  178. List<WebClient> webClients = new List<WebClient>(ConnectionCount);
  179. for (int i = 0; i < ConnectionCount; i++)
  180. {
  181. list.Add(new byte[0]);
  182. }
  183. for (int i = 0; i < ConnectionCount; i++)
  184. {
  185. using (WebClient client = new WebClient())
  186. {
  187. webClients.Add(client);
  188. if (i == ConnectionCount - 1)
  189. {
  190. client.Headers.Add("Range", $"bytes={chunkSize * i}-{(chunkSize * (i + 1) - 1) + remainderChunk}");
  191. }
  192. else
  193. {
  194. client.Headers.Add("Range", $"bytes={chunkSize * i}-{chunkSize * (i + 1) - 1}");
  195. }
  196. client.DownloadProgressChanged += (_, args) =>
  197. {
  198. int index = (int)args.UserState;
  199. Interlocked.Add(ref totalProgressPercentage, -1 * progressPercentage[index]);
  200. Interlocked.Exchange(ref progressPercentage[index], args.ProgressPercentage);
  201. Interlocked.Add(ref totalProgressPercentage, args.ProgressPercentage);
  202. updateDialog.ProgressBar.Value = totalProgressPercentage / ConnectionCount;
  203. };
  204. client.DownloadDataCompleted += (_, args) =>
  205. {
  206. int index = (int)args.UserState;
  207. if (args.Cancelled)
  208. {
  209. webClients[index].Dispose();
  210. return;
  211. }
  212. list[index] = args.Result;
  213. Interlocked.Increment(ref completedRequests);
  214. if (Interlocked.Equals(completedRequests, ConnectionCount))
  215. {
  216. byte[] mergedFileBytes = new byte[_buildSize];
  217. for (int connectionIndex = 0, destinationOffset = 0; connectionIndex < ConnectionCount; connectionIndex++)
  218. {
  219. Array.Copy(list[connectionIndex], 0, mergedFileBytes, destinationOffset, list[connectionIndex].Length);
  220. destinationOffset += list[connectionIndex].Length;
  221. }
  222. File.WriteAllBytes(updateFile, mergedFileBytes);
  223. try
  224. {
  225. InstallUpdate(updateDialog, updateFile);
  226. }
  227. catch (Exception e)
  228. {
  229. Logger.Warning?.Print(LogClass.Application, e.Message);
  230. Logger.Warning?.Print(LogClass.Application, $"Multi-Threaded update failed, falling back to single-threaded updater.");
  231. DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
  232. return;
  233. }
  234. }
  235. };
  236. try
  237. {
  238. client.DownloadDataAsync(new Uri(downloadUrl), i);
  239. }
  240. catch (WebException ex)
  241. {
  242. Logger.Warning?.Print(LogClass.Application, ex.Message);
  243. Logger.Warning?.Print(LogClass.Application, $"Multi-Threaded update failed, falling back to single-threaded updater.");
  244. for (int j = 0; j < webClients.Count; j++)
  245. {
  246. webClients[j].CancelAsync();
  247. }
  248. DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
  249. return;
  250. }
  251. }
  252. }
  253. }
  254. private static void DoUpdateWithSingleThread(UpdateDialog updateDialog, string downloadUrl, string updateFile)
  255. {
  256. // Single-Threaded Updater
  257. using (WebClient client = new WebClient())
  258. {
  259. client.DownloadProgressChanged += (_, args) =>
  260. {
  261. updateDialog.ProgressBar.Value = args.ProgressPercentage;
  262. };
  263. client.DownloadDataCompleted += (_, args) =>
  264. {
  265. File.WriteAllBytes(updateFile, args.Result);
  266. InstallUpdate(updateDialog, updateFile);
  267. };
  268. client.DownloadDataAsync(new Uri(downloadUrl));
  269. }
  270. }
  271. private static void SetUnixPermissions()
  272. {
  273. string ryuBin = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ryujinx");
  274. if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  275. {
  276. UnixFileInfo unixFileInfo = new UnixFileInfo(ryuBin);
  277. unixFileInfo.FileAccessPermissions |= FileAccessPermissions.UserExecute;
  278. }
  279. }
  280. private static async void InstallUpdate(UpdateDialog updateDialog, string updateFile)
  281. {
  282. // Extract Update
  283. updateDialog.MainText.Text = "Extracting Update...";
  284. updateDialog.ProgressBar.Value = 0;
  285. if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  286. {
  287. using (Stream inStream = File.OpenRead(updateFile))
  288. using (Stream gzipStream = new GZipInputStream(inStream))
  289. using (TarInputStream tarStream = new TarInputStream(gzipStream, Encoding.ASCII))
  290. {
  291. updateDialog.ProgressBar.MaxValue = inStream.Length;
  292. await Task.Run(() =>
  293. {
  294. TarEntry tarEntry;
  295. while ((tarEntry = tarStream.GetNextEntry()) != null)
  296. {
  297. if (tarEntry.IsDirectory) continue;
  298. string outPath = Path.Combine(UpdateDir, tarEntry.Name);
  299. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  300. using (FileStream outStream = File.OpenWrite(outPath))
  301. {
  302. tarStream.CopyEntryContents(outStream);
  303. }
  304. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc));
  305. TarEntry entry = tarEntry;
  306. Application.Invoke(delegate
  307. {
  308. updateDialog.ProgressBar.Value += entry.Size;
  309. });
  310. }
  311. });
  312. updateDialog.ProgressBar.Value = inStream.Length;
  313. }
  314. }
  315. else
  316. {
  317. using (Stream inStream = File.OpenRead(updateFile))
  318. using (ZipFile zipFile = new ZipFile(inStream))
  319. {
  320. updateDialog.ProgressBar.MaxValue = zipFile.Count;
  321. await Task.Run(() =>
  322. {
  323. foreach (ZipEntry zipEntry in zipFile)
  324. {
  325. if (zipEntry.IsDirectory) continue;
  326. string outPath = Path.Combine(UpdateDir, zipEntry.Name);
  327. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  328. using (Stream zipStream = zipFile.GetInputStream(zipEntry))
  329. using (FileStream outStream = File.OpenWrite(outPath))
  330. {
  331. zipStream.CopyTo(outStream);
  332. }
  333. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(zipEntry.DateTime, DateTimeKind.Utc));
  334. Application.Invoke(delegate
  335. {
  336. updateDialog.ProgressBar.Value++;
  337. });
  338. }
  339. });
  340. }
  341. }
  342. // Delete downloaded zip
  343. File.Delete(updateFile);
  344. List<string> allFiles = EnumerateFilesToDelete().ToList();
  345. updateDialog.MainText.Text = "Renaming Old Files...";
  346. updateDialog.ProgressBar.Value = 0;
  347. updateDialog.ProgressBar.MaxValue = allFiles.Count;
  348. // Replace old files
  349. await Task.Run(() =>
  350. {
  351. foreach (string file in allFiles)
  352. {
  353. try
  354. {
  355. File.Move(file, file + ".ryuold");
  356. Application.Invoke(delegate
  357. {
  358. updateDialog.ProgressBar.Value++;
  359. });
  360. }
  361. catch
  362. {
  363. Logger.Warning?.Print(LogClass.Application, "Updater was unable to rename file: " + file);
  364. }
  365. }
  366. Application.Invoke(delegate
  367. {
  368. updateDialog.MainText.Text = "Adding New Files...";
  369. updateDialog.ProgressBar.Value = 0;
  370. updateDialog.ProgressBar.MaxValue = Directory.GetFiles(UpdatePublishDir, "*", SearchOption.AllDirectories).Length;
  371. });
  372. MoveAllFilesOver(UpdatePublishDir, HomeDir, updateDialog);
  373. });
  374. Directory.Delete(UpdateDir, true);
  375. SetUnixPermissions();
  376. updateDialog.MainText.Text = "Update Complete!";
  377. updateDialog.SecondaryText.Text = "Do you want to restart Ryujinx now?";
  378. updateDialog.Modal = true;
  379. updateDialog.ProgressBar.Hide();
  380. updateDialog.YesButton.Show();
  381. updateDialog.NoButton.Show();
  382. }
  383. public static bool CanUpdate(bool showWarnings)
  384. {
  385. #if !DISABLE_UPDATER
  386. if (RuntimeInformation.OSArchitecture != Architecture.X64)
  387. {
  388. if (showWarnings)
  389. {
  390. GtkDialog.CreateWarningDialog("You are not running a supported system architecture!", "(Only x64 systems are supported!)");
  391. }
  392. return false;
  393. }
  394. if (!NetworkInterface.GetIsNetworkAvailable())
  395. {
  396. if (showWarnings)
  397. {
  398. GtkDialog.CreateWarningDialog("You are not connected to the Internet!", "Please verify that you have a working Internet connection!");
  399. }
  400. return false;
  401. }
  402. if (Program.Version.Contains("dirty"))
  403. {
  404. if (showWarnings)
  405. {
  406. 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.");
  407. }
  408. return false;
  409. }
  410. return true;
  411. #else
  412. if (showWarnings)
  413. {
  414. GtkDialog.CreateWarningDialog("Updater Disabled!", "Please download Ryujinx at https://ryujinx.org/ if you are looking for a supported version.");
  415. }
  416. return false;
  417. #endif
  418. }
  419. // NOTE: This method should always reflect the latest build layout.
  420. private static IEnumerable<string> EnumerateFilesToDelete()
  421. {
  422. var files = Directory.EnumerateFiles(HomeDir); // All files directly in base dir.
  423. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  424. {
  425. foreach (string dir in WindowsDependencyDirs)
  426. {
  427. string dirPath = Path.Combine(HomeDir, dir);
  428. if (Directory.Exists(dirPath))
  429. {
  430. files = files.Concat(Directory.EnumerateFiles(dirPath, "*", SearchOption.AllDirectories));
  431. }
  432. }
  433. }
  434. return files;
  435. }
  436. private static void MoveAllFilesOver(string root, string dest, UpdateDialog dialog)
  437. {
  438. foreach (string directory in Directory.GetDirectories(root))
  439. {
  440. string dirName = Path.GetFileName(directory);
  441. if (!Directory.Exists(Path.Combine(dest, dirName)))
  442. {
  443. Directory.CreateDirectory(Path.Combine(dest, dirName));
  444. }
  445. MoveAllFilesOver(directory, Path.Combine(dest, dirName), dialog);
  446. }
  447. foreach (string file in Directory.GetFiles(root))
  448. {
  449. File.Move(file, Path.Combine(dest, Path.GetFileName(file)), true);
  450. Application.Invoke(delegate
  451. {
  452. dialog.ProgressBar.Value++;
  453. });
  454. }
  455. }
  456. public static void CleanupUpdate()
  457. {
  458. foreach (string file in EnumerateFilesToDelete())
  459. {
  460. if (Path.GetExtension(file).EndsWith(".ryuold"))
  461. {
  462. File.Delete(file);
  463. }
  464. }
  465. }
  466. }
  467. }