Updater.cs 21 KB

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