Updater.cs 20 KB

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