Updater.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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.Logging;
  7. using Ryujinx.Ui;
  8. using Ryujinx.Ui.Widgets;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Net;
  13. using System.Net.NetworkInformation;
  14. using System.Runtime.InteropServices;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace Ryujinx.Modules
  19. {
  20. public static class Updater
  21. {
  22. internal static bool Running;
  23. private static readonly string HomeDir = AppDomain.CurrentDomain.BaseDirectory;
  24. private static readonly string UpdateDir = Path.Combine(Path.GetTempPath(), "Ryujinx", "update");
  25. private static readonly string UpdatePublishDir = Path.Combine(UpdateDir, "publish");
  26. private static readonly int ConnectionCount = 4;
  27. private static string _jobId;
  28. private static string _buildVer;
  29. private static string _platformExt;
  30. private static string _buildUrl;
  31. private static long _buildSize;
  32. private const string AppveyorApiUrl = "https://ci.appveyor.com/api";
  33. public static async Task BeginParse(MainWindow mainWindow, bool showVersionUpToDate)
  34. {
  35. if (Running) return;
  36. Running = true;
  37. mainWindow.UpdateMenuItem.Sensitive = false;
  38. int artifactIndex = -1;
  39. // Detect current platform
  40. if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  41. {
  42. _platformExt = "osx_x64.zip";
  43. artifactIndex = 1;
  44. }
  45. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  46. {
  47. _platformExt = "win_x64.zip";
  48. artifactIndex = 2;
  49. }
  50. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  51. {
  52. _platformExt = "linux_x64.tar.gz";
  53. artifactIndex = 0;
  54. }
  55. if (artifactIndex == -1)
  56. {
  57. GtkDialog.CreateErrorDialog("Your platform is not supported!");
  58. return;
  59. }
  60. Version newVersion;
  61. Version currentVersion;
  62. try
  63. {
  64. currentVersion = Version.Parse(Program.Version);
  65. }
  66. catch
  67. {
  68. GtkDialog.CreateWarningDialog("Failed to convert the current Ryujinx version.", "Cancelling Update!");
  69. Logger.Error?.Print(LogClass.Application, "Failed to convert the current Ryujinx version!");
  70. return;
  71. }
  72. // Get latest version number from Appveyor
  73. try
  74. {
  75. using (WebClient jsonClient = new WebClient())
  76. {
  77. // Fetch latest build information
  78. string fetchedJson = await jsonClient.DownloadStringTaskAsync($"{AppveyorApiUrl}/projects/gdkchan/ryujinx/branch/master");
  79. JObject jsonRoot = JObject.Parse(fetchedJson);
  80. JToken buildToken = jsonRoot["build"];
  81. _jobId = (string)buildToken["jobs"][0]["jobId"];
  82. _buildVer = (string)buildToken["version"];
  83. _buildUrl = $"{AppveyorApiUrl}/buildjobs/{_jobId}/artifacts/ryujinx-{_buildVer}-{_platformExt}";
  84. // If build not done, assume no new update are availaible.
  85. if ((string)buildToken["jobs"][0]["status"] != "success")
  86. {
  87. if (showVersionUpToDate)
  88. {
  89. GtkDialog.CreateUpdaterInfoDialog("You are already using the most updated version of Ryujinx!", "");
  90. }
  91. return;
  92. }
  93. }
  94. }
  95. catch (Exception exception)
  96. {
  97. Logger.Error?.Print(LogClass.Application, exception.Message);
  98. GtkDialog.CreateErrorDialog("An error has occurred when trying to get release information from AppVeyor.");
  99. return;
  100. }
  101. try
  102. {
  103. newVersion = Version.Parse(_buildVer);
  104. }
  105. catch
  106. {
  107. GtkDialog.CreateWarningDialog("Failed to convert the received Ryujinx version from AppVeyor.", "Cancelling Update!");
  108. Logger.Error?.Print(LogClass.Application, "Failed to convert the received Ryujinx version from AppVeyor!");
  109. return;
  110. }
  111. if (newVersion <= currentVersion)
  112. {
  113. if (showVersionUpToDate)
  114. {
  115. GtkDialog.CreateUpdaterInfoDialog("You are already using the most updated version of Ryujinx!", "");
  116. }
  117. Running = false;
  118. mainWindow.UpdateMenuItem.Sensitive = true;
  119. return;
  120. }
  121. // Fetch build size information to learn chunk sizes.
  122. using (WebClient buildSizeClient = new WebClient())
  123. {
  124. try
  125. {
  126. buildSizeClient.Headers.Add("Range", "bytes=0-0");
  127. await buildSizeClient.DownloadDataTaskAsync(new Uri(_buildUrl));
  128. string contentRange = buildSizeClient.ResponseHeaders["Content-Range"];
  129. _buildSize = long.Parse(contentRange.Substring(contentRange.IndexOf('/') + 1));
  130. }
  131. catch (Exception ex)
  132. {
  133. Logger.Warning?.Print(LogClass.Application, ex.Message);
  134. Logger.Warning?.Print(LogClass.Application, "Couldn't determine build size for update, will use single-threaded updater");
  135. _buildSize = -1;
  136. }
  137. }
  138. // Show a message asking the user if they want to update
  139. UpdateDialog updateDialog = new UpdateDialog(mainWindow, newVersion, _buildUrl);
  140. updateDialog.Show();
  141. }
  142. public static void UpdateRyujinx(UpdateDialog updateDialog, string downloadUrl)
  143. {
  144. // Empty update dir, although it shouldn't ever have anything inside it
  145. if (Directory.Exists(UpdateDir))
  146. {
  147. Directory.Delete(UpdateDir, true);
  148. }
  149. Directory.CreateDirectory(UpdateDir);
  150. string updateFile = Path.Combine(UpdateDir, "update.bin");
  151. // Download the update .zip
  152. updateDialog.MainText.Text = "Downloading Update...";
  153. updateDialog.ProgressBar.Value = 0;
  154. updateDialog.ProgressBar.MaxValue = 100;
  155. if (_buildSize >= 0)
  156. {
  157. DoUpdateWithMultipleThreads(updateDialog, downloadUrl, updateFile);
  158. }
  159. else
  160. {
  161. DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
  162. }
  163. }
  164. private static void DoUpdateWithMultipleThreads(UpdateDialog updateDialog, string downloadUrl, string updateFile)
  165. {
  166. // Multi-Threaded Updater
  167. long chunkSize = _buildSize / ConnectionCount;
  168. long remainderChunk = _buildSize % ConnectionCount;
  169. int completedRequests = 0;
  170. int totalProgressPercentage = 0;
  171. int[] progressPercentage = new int[ConnectionCount];
  172. List<byte[]> list = new List<byte[]>(ConnectionCount);
  173. List<WebClient> webClients = new List<WebClient>(ConnectionCount);
  174. for (int i = 0; i < ConnectionCount; i++)
  175. {
  176. list.Add(new byte[0]);
  177. }
  178. for (int i = 0; i < ConnectionCount; i++)
  179. {
  180. using (WebClient client = new WebClient())
  181. {
  182. webClients.Add(client);
  183. if (i == ConnectionCount - 1)
  184. {
  185. client.Headers.Add("Range", $"bytes={chunkSize * i}-{(chunkSize * (i + 1) - 1) + remainderChunk}");
  186. }
  187. else
  188. {
  189. client.Headers.Add("Range", $"bytes={chunkSize * i}-{chunkSize * (i + 1) - 1}");
  190. }
  191. client.DownloadProgressChanged += (_, args) =>
  192. {
  193. int index = (int)args.UserState;
  194. Interlocked.Add(ref totalProgressPercentage, -1 * progressPercentage[index]);
  195. Interlocked.Exchange(ref progressPercentage[index], args.ProgressPercentage);
  196. Interlocked.Add(ref totalProgressPercentage, args.ProgressPercentage);
  197. updateDialog.ProgressBar.Value = totalProgressPercentage / ConnectionCount;
  198. };
  199. client.DownloadDataCompleted += (_, args) =>
  200. {
  201. int index = (int)args.UserState;
  202. if (args.Cancelled)
  203. {
  204. webClients[index].Dispose();
  205. return;
  206. }
  207. list[index] = args.Result;
  208. Interlocked.Increment(ref completedRequests);
  209. if (Interlocked.Equals(completedRequests, ConnectionCount))
  210. {
  211. byte[] mergedFileBytes = new byte[_buildSize];
  212. for (int connectionIndex = 0, destinationOffset = 0; connectionIndex < ConnectionCount; connectionIndex++)
  213. {
  214. Array.Copy(list[connectionIndex], 0, mergedFileBytes, destinationOffset, list[connectionIndex].Length);
  215. destinationOffset += list[connectionIndex].Length;
  216. }
  217. File.WriteAllBytes(updateFile, mergedFileBytes);
  218. try
  219. {
  220. InstallUpdate(updateDialog, updateFile);
  221. }
  222. catch (Exception e)
  223. {
  224. Logger.Warning?.Print(LogClass.Application, e.Message);
  225. Logger.Warning?.Print(LogClass.Application, $"Multi-Threaded update failed, falling back to single-threaded updater.");
  226. DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
  227. return;
  228. }
  229. }
  230. };
  231. try
  232. {
  233. client.DownloadDataAsync(new Uri(downloadUrl), i);
  234. }
  235. catch (WebException ex)
  236. {
  237. Logger.Warning?.Print(LogClass.Application, ex.Message);
  238. Logger.Warning?.Print(LogClass.Application, $"Multi-Threaded update failed, falling back to single-threaded updater.");
  239. for (int j = 0; j < webClients.Count; j++)
  240. {
  241. webClients[j].CancelAsync();
  242. }
  243. DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
  244. return;
  245. }
  246. }
  247. }
  248. }
  249. private static void DoUpdateWithSingleThread(UpdateDialog updateDialog, string downloadUrl, string updateFile)
  250. {
  251. // Single-Threaded Updater
  252. using (WebClient client = new WebClient())
  253. {
  254. client.DownloadProgressChanged += (_, args) =>
  255. {
  256. updateDialog.ProgressBar.Value = args.ProgressPercentage;
  257. };
  258. client.DownloadDataCompleted += (_, args) =>
  259. {
  260. File.WriteAllBytes(updateFile, args.Result);
  261. InstallUpdate(updateDialog, updateFile);
  262. };
  263. client.DownloadDataAsync(new Uri(downloadUrl));
  264. }
  265. }
  266. private static async void InstallUpdate(UpdateDialog updateDialog, string updateFile)
  267. {
  268. // Extract Update
  269. updateDialog.MainText.Text = "Extracting Update...";
  270. updateDialog.ProgressBar.Value = 0;
  271. if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  272. {
  273. using (Stream inStream = File.OpenRead(updateFile))
  274. using (Stream gzipStream = new GZipInputStream(inStream))
  275. using (TarInputStream tarStream = new TarInputStream(gzipStream, Encoding.ASCII))
  276. {
  277. updateDialog.ProgressBar.MaxValue = inStream.Length;
  278. await Task.Run(() =>
  279. {
  280. TarEntry tarEntry;
  281. while ((tarEntry = tarStream.GetNextEntry()) != null)
  282. {
  283. if (tarEntry.IsDirectory) continue;
  284. string outPath = Path.Combine(UpdateDir, tarEntry.Name);
  285. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  286. using (FileStream outStream = File.OpenWrite(outPath))
  287. {
  288. tarStream.CopyEntryContents(outStream);
  289. }
  290. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc));
  291. TarEntry entry = tarEntry;
  292. Application.Invoke(delegate
  293. {
  294. updateDialog.ProgressBar.Value += entry.Size;
  295. });
  296. }
  297. });
  298. updateDialog.ProgressBar.Value = inStream.Length;
  299. }
  300. }
  301. else
  302. {
  303. using (Stream inStream = File.OpenRead(updateFile))
  304. using (ZipFile zipFile = new ZipFile(inStream))
  305. {
  306. updateDialog.ProgressBar.MaxValue = zipFile.Count;
  307. await Task.Run(() =>
  308. {
  309. foreach (ZipEntry zipEntry in zipFile)
  310. {
  311. if (zipEntry.IsDirectory) continue;
  312. string outPath = Path.Combine(UpdateDir, zipEntry.Name);
  313. Directory.CreateDirectory(Path.GetDirectoryName(outPath));
  314. using (Stream zipStream = zipFile.GetInputStream(zipEntry))
  315. using (FileStream outStream = File.OpenWrite(outPath))
  316. {
  317. zipStream.CopyTo(outStream);
  318. }
  319. File.SetLastWriteTime(outPath, DateTime.SpecifyKind(zipEntry.DateTime, DateTimeKind.Utc));
  320. Application.Invoke(delegate
  321. {
  322. updateDialog.ProgressBar.Value++;
  323. });
  324. }
  325. });
  326. }
  327. }
  328. // Delete downloaded zip
  329. File.Delete(updateFile);
  330. string[] allFiles = Directory.GetFiles(HomeDir, "*", SearchOption.AllDirectories);
  331. updateDialog.MainText.Text = "Renaming Old Files...";
  332. updateDialog.ProgressBar.Value = 0;
  333. updateDialog.ProgressBar.MaxValue = allFiles.Length;
  334. // Replace old files
  335. await Task.Run(() =>
  336. {
  337. foreach (string file in allFiles)
  338. {
  339. if (!Path.GetExtension(file).Equals(".log"))
  340. {
  341. try
  342. {
  343. File.Move(file, file + ".ryuold");
  344. Application.Invoke(delegate
  345. {
  346. updateDialog.ProgressBar.Value++;
  347. });
  348. }
  349. catch
  350. {
  351. Logger.Warning?.Print(LogClass.Application, "Updater wasn't able to rename file: " + file);
  352. }
  353. }
  354. }
  355. Application.Invoke(delegate
  356. {
  357. updateDialog.MainText.Text = "Adding New Files...";
  358. updateDialog.ProgressBar.Value = 0;
  359. updateDialog.ProgressBar.MaxValue = Directory.GetFiles(UpdatePublishDir, "*", SearchOption.AllDirectories).Length;
  360. });
  361. MoveAllFilesOver(UpdatePublishDir, HomeDir, updateDialog);
  362. });
  363. Directory.Delete(UpdateDir, true);
  364. updateDialog.MainText.Text = "Update Complete!";
  365. updateDialog.SecondaryText.Text = "Do you want to restart Ryujinx now?";
  366. updateDialog.Modal = true;
  367. updateDialog.ProgressBar.Hide();
  368. updateDialog.YesButton.Show();
  369. updateDialog.NoButton.Show();
  370. }
  371. public static bool CanUpdate(bool showWarnings)
  372. {
  373. if (RuntimeInformation.OSArchitecture != Architecture.X64)
  374. {
  375. if (showWarnings)
  376. {
  377. GtkDialog.CreateWarningDialog("You are not running a supported system architecture!", "(Only x64 systems are supported!)");
  378. }
  379. return false;
  380. }
  381. if (!NetworkInterface.GetIsNetworkAvailable())
  382. {
  383. if (showWarnings)
  384. {
  385. GtkDialog.CreateWarningDialog("You are not connected to the Internet!", "Please verify that you have a working Internet connection!");
  386. }
  387. return false;
  388. }
  389. if (Program.Version.Contains("dirty"))
  390. {
  391. if (showWarnings)
  392. {
  393. 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.");
  394. }
  395. return false;
  396. }
  397. return true;
  398. }
  399. private static void MoveAllFilesOver(string root, string dest, UpdateDialog dialog)
  400. {
  401. foreach (string directory in Directory.GetDirectories(root))
  402. {
  403. string dirName = Path.GetFileName(directory);
  404. if (!Directory.Exists(Path.Combine(dest, dirName)))
  405. {
  406. Directory.CreateDirectory(Path.Combine(dest, dirName));
  407. }
  408. MoveAllFilesOver(directory, Path.Combine(dest, dirName), dialog);
  409. }
  410. foreach (string file in Directory.GetFiles(root))
  411. {
  412. File.Move(file, Path.Combine(dest, Path.GetFileName(file)), true);
  413. Application.Invoke(delegate
  414. {
  415. dialog.ProgressBar.Value++;
  416. });
  417. }
  418. }
  419. public static void CleanupUpdate()
  420. {
  421. foreach (string file in Directory.GetFiles(HomeDir, "*", SearchOption.AllDirectories))
  422. {
  423. if (Path.GetExtension(file).EndsWith(".ryuold"))
  424. {
  425. File.Delete(file);
  426. }
  427. }
  428. }
  429. }
  430. }