ApplicationLibrary.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. using LibHac;
  2. using LibHac.Common;
  3. using LibHac.Fs;
  4. using LibHac.Fs.Shim;
  5. using LibHac.FsSystem;
  6. using LibHac.FsSystem.NcaUtils;
  7. using LibHac.Ncm;
  8. using LibHac.Ns;
  9. using LibHac.Spl;
  10. using Ryujinx.Common.Logging;
  11. using Ryujinx.Common.Configuration;
  12. using Ryujinx.Configuration.System;
  13. using Ryujinx.HLE.FileSystem;
  14. using Ryujinx.HLE.Loaders.Npdm;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Globalization;
  18. using System.IO;
  19. using System.Reflection;
  20. using System.Text;
  21. using System.Text.Json;
  22. using RightsId = LibHac.Fs.RightsId;
  23. using JsonHelper = Ryujinx.Common.Utilities.JsonHelper;
  24. namespace Ryujinx.Ui
  25. {
  26. public class ApplicationLibrary
  27. {
  28. public static event EventHandler<ApplicationAddedEventArgs> ApplicationAdded;
  29. public static event EventHandler<ApplicationCountUpdatedEventArgs> ApplicationCountUpdated;
  30. private static readonly byte[] _nspIcon = GetResourceBytes("Ryujinx.Ui.assets.NSPIcon.png");
  31. private static readonly byte[] _xciIcon = GetResourceBytes("Ryujinx.Ui.assets.XCIIcon.png");
  32. private static readonly byte[] _ncaIcon = GetResourceBytes("Ryujinx.Ui.assets.NCAIcon.png");
  33. private static readonly byte[] _nroIcon = GetResourceBytes("Ryujinx.Ui.assets.NROIcon.png");
  34. private static readonly byte[] _nsoIcon = GetResourceBytes("Ryujinx.Ui.assets.NSOIcon.png");
  35. private static VirtualFileSystem _virtualFileSystem;
  36. private static Language _desiredTitleLanguage;
  37. private static bool _loadingError;
  38. public static IEnumerable<string> GetFilesInDirectory(string directory)
  39. {
  40. Stack<string> stack = new Stack<string>();
  41. stack.Push(directory);
  42. while (stack.Count > 0)
  43. {
  44. string dir = stack.Pop();
  45. string[] content = { };
  46. try
  47. {
  48. content = Directory.GetFiles(dir, "*");
  49. }
  50. catch (UnauthorizedAccessException)
  51. {
  52. Logger.PrintWarning(LogClass.Application, $"Failed to get access to directory: \"{dir}\"");
  53. }
  54. if (content.Length > 0)
  55. {
  56. foreach (string file in content)
  57. yield return file;
  58. }
  59. try
  60. {
  61. content = Directory.GetDirectories(dir);
  62. }
  63. catch (UnauthorizedAccessException)
  64. {
  65. Logger.PrintWarning(LogClass.Application, $"Failed to get access to directory: \"{dir}\"");
  66. }
  67. if (content.Length > 0)
  68. {
  69. foreach (string subdir in content)
  70. stack.Push(subdir);
  71. }
  72. }
  73. }
  74. public static void ReadControlData(IFileSystem controlFs, Span<byte> outProperty)
  75. {
  76. controlFs.OpenFile(out IFile controlFile, "/control.nacp".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  77. controlFile.Read(out _, 0, outProperty, ReadOption.None).ThrowIfFailure();
  78. }
  79. public static void LoadApplications(List<string> appDirs, VirtualFileSystem virtualFileSystem, Language desiredTitleLanguage)
  80. {
  81. int numApplicationsFound = 0;
  82. int numApplicationsLoaded = 0;
  83. _loadingError = false;
  84. _virtualFileSystem = virtualFileSystem;
  85. _desiredTitleLanguage = desiredTitleLanguage;
  86. // Builds the applications list with paths to found applications
  87. List<string> applications = new List<string>();
  88. foreach (string appDir in appDirs)
  89. {
  90. if (!Directory.Exists(appDir))
  91. {
  92. Logger.PrintWarning(LogClass.Application, $"The \"game_dirs\" section in \"Config.json\" contains an invalid directory: \"{appDir}\"");
  93. continue;
  94. }
  95. foreach (string app in GetFilesInDirectory(appDir))
  96. {
  97. if ((Path.GetExtension(app).ToLower() == ".nsp") ||
  98. (Path.GetExtension(app).ToLower() == ".pfs0") ||
  99. (Path.GetExtension(app).ToLower() == ".xci") ||
  100. (Path.GetExtension(app).ToLower() == ".nca") ||
  101. (Path.GetExtension(app).ToLower() == ".nro") ||
  102. (Path.GetExtension(app).ToLower() == ".nso"))
  103. {
  104. applications.Add(app);
  105. numApplicationsFound++;
  106. }
  107. }
  108. }
  109. // Loops through applications list, creating a struct and then firing an event containing the struct for each application
  110. foreach (string applicationPath in applications)
  111. {
  112. double fileSize = new FileInfo(applicationPath).Length * 0.000000000931;
  113. string titleName = "Unknown";
  114. string titleId = "0000000000000000";
  115. string developer = "Unknown";
  116. string version = "0";
  117. string saveDataPath = null;
  118. byte[] applicationIcon = null;
  119. BlitStruct<ApplicationControlProperty> controlHolder = new BlitStruct<ApplicationControlProperty>(1);
  120. try
  121. {
  122. using (FileStream file = new FileStream(applicationPath, FileMode.Open, FileAccess.Read))
  123. {
  124. if ((Path.GetExtension(applicationPath).ToLower() == ".nsp") ||
  125. (Path.GetExtension(applicationPath).ToLower() == ".pfs0") ||
  126. (Path.GetExtension(applicationPath).ToLower() == ".xci"))
  127. {
  128. try
  129. {
  130. PartitionFileSystem pfs;
  131. bool isExeFs = false;
  132. if (Path.GetExtension(applicationPath).ToLower() == ".xci")
  133. {
  134. Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage());
  135. pfs = xci.OpenPartition(XciPartitionType.Secure);
  136. }
  137. else
  138. {
  139. pfs = new PartitionFileSystem(file.AsStorage());
  140. // If the NSP doesn't have a main NCA, decrement the number of applications found and then continue to the next application.
  141. bool hasMainNca = false;
  142. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*"))
  143. {
  144. if (Path.GetExtension(fileEntry.FullPath).ToLower() == ".nca")
  145. {
  146. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  147. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  148. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  149. if (nca.Header.ContentType == NcaContentType.Program && !nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  150. {
  151. hasMainNca = true;
  152. break;
  153. }
  154. }
  155. else if (Path.GetFileNameWithoutExtension(fileEntry.FullPath) == "main")
  156. {
  157. isExeFs = true;
  158. }
  159. }
  160. if (!hasMainNca && !isExeFs)
  161. {
  162. numApplicationsFound--;
  163. continue;
  164. }
  165. }
  166. if (isExeFs)
  167. {
  168. applicationIcon = _nspIcon;
  169. Result result = pfs.OpenFile(out IFile npdmFile, "/main.npdm".ToU8Span(), OpenMode.Read);
  170. if (ResultFs.PathNotFound.Includes(result))
  171. {
  172. Npdm npdm = new Npdm(npdmFile.AsStream());
  173. titleName = npdm.TitleName;
  174. titleId = npdm.Aci0.TitleId.ToString("x16");
  175. }
  176. }
  177. else
  178. {
  179. // Store the ControlFS in variable called controlFs
  180. GetControlFsAndTitleId(pfs, out IFileSystem controlFs, out titleId);
  181. ReadControlData(controlFs, controlHolder.ByteSpan);
  182. // Creates NACP class from the NACP file
  183. controlFs.OpenFile(out IFile controlNacpFile, "/control.nacp".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  184. // Get the title name, title ID, developer name and version number from the NACP
  185. version = IsUpdateApplied(titleId, out string updateVersion) ? updateVersion : controlHolder.Value.DisplayVersion.ToString();
  186. GetNameIdDeveloper(ref controlHolder.Value, out titleName, out _, out developer);
  187. // Read the icon from the ControlFS and store it as a byte array
  188. try
  189. {
  190. controlFs.OpenFile(out IFile icon, $"/icon_{_desiredTitleLanguage}.dat".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  191. using (MemoryStream stream = new MemoryStream())
  192. {
  193. icon.AsStream().CopyTo(stream);
  194. applicationIcon = stream.ToArray();
  195. }
  196. }
  197. catch (HorizonResultException)
  198. {
  199. foreach (DirectoryEntryEx entry in controlFs.EnumerateEntries("/", "*"))
  200. {
  201. if (entry.Name == "control.nacp")
  202. {
  203. continue;
  204. }
  205. controlFs.OpenFile(out IFile icon, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  206. using (MemoryStream stream = new MemoryStream())
  207. {
  208. icon.AsStream().CopyTo(stream);
  209. applicationIcon = stream.ToArray();
  210. }
  211. if (applicationIcon != null)
  212. {
  213. break;
  214. }
  215. }
  216. if (applicationIcon == null)
  217. {
  218. applicationIcon = Path.GetExtension(applicationPath).ToLower() == ".xci" ? _xciIcon : _nspIcon;
  219. }
  220. }
  221. }
  222. }
  223. catch (MissingKeyException exception)
  224. {
  225. applicationIcon = Path.GetExtension(applicationPath).ToLower() == ".xci" ? _xciIcon : _nspIcon;
  226. Logger.PrintWarning(LogClass.Application, $"Your key set is missing a key with the name: {exception.Name}");
  227. }
  228. catch (InvalidDataException)
  229. {
  230. applicationIcon = Path.GetExtension(applicationPath).ToLower() == ".xci" ? _xciIcon : _nspIcon;
  231. Logger.PrintWarning(LogClass.Application, $"The header key is incorrect or missing and therefore the NCA header content type check has failed. Errored File: {applicationPath}");
  232. }
  233. catch (Exception exception)
  234. {
  235. Logger.PrintWarning(LogClass.Application, $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  236. Logger.PrintDebug(LogClass.Application, exception.ToString());
  237. numApplicationsFound--;
  238. _loadingError = true;
  239. continue;
  240. }
  241. }
  242. else if (Path.GetExtension(applicationPath).ToLower() == ".nro")
  243. {
  244. BinaryReader reader = new BinaryReader(file);
  245. byte[] Read(long position, int size)
  246. {
  247. file.Seek(position, SeekOrigin.Begin);
  248. return reader.ReadBytes(size);
  249. }
  250. try
  251. {
  252. file.Seek(24, SeekOrigin.Begin);
  253. int assetOffset = reader.ReadInt32();
  254. if (Encoding.ASCII.GetString(Read(assetOffset, 4)) == "ASET")
  255. {
  256. byte[] iconSectionInfo = Read(assetOffset + 8, 0x10);
  257. long iconOffset = BitConverter.ToInt64(iconSectionInfo, 0);
  258. long iconSize = BitConverter.ToInt64(iconSectionInfo, 8);
  259. ulong nacpOffset = reader.ReadUInt64();
  260. ulong nacpSize = reader.ReadUInt64();
  261. // Reads and stores game icon as byte array
  262. applicationIcon = Read(assetOffset + iconOffset, (int) iconSize);
  263. // Read the NACP data
  264. Read(assetOffset + (int)nacpOffset, (int)nacpSize).AsSpan().CopyTo(controlHolder.ByteSpan);
  265. // Get the title name, title ID, developer name and version number from the NACP
  266. version = controlHolder.Value.DisplayVersion.ToString();
  267. GetNameIdDeveloper(ref controlHolder.Value, out titleName, out titleId, out developer);
  268. }
  269. else
  270. {
  271. applicationIcon = _nroIcon;
  272. titleName = Path.GetFileNameWithoutExtension(applicationPath);
  273. }
  274. }
  275. catch
  276. {
  277. Logger.PrintWarning(LogClass.Application, $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  278. numApplicationsFound--;
  279. continue;
  280. }
  281. }
  282. else if (Path.GetExtension(applicationPath).ToLower() == ".nca")
  283. {
  284. try
  285. {
  286. Nca nca = new Nca(_virtualFileSystem.KeySet, new FileStream(applicationPath, FileMode.Open, FileAccess.Read).AsStorage());
  287. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  288. if (nca.Header.ContentType != NcaContentType.Program || nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  289. {
  290. numApplicationsFound--;
  291. continue;
  292. }
  293. }
  294. catch (InvalidDataException)
  295. {
  296. Logger.PrintWarning(LogClass.Application, $"The NCA header content type check has failed. This is usually because the header key is incorrect or missing. Errored File: {applicationPath}");
  297. }
  298. catch
  299. {
  300. Logger.PrintWarning(LogClass.Application, $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  301. numApplicationsFound--;
  302. _loadingError = true;
  303. continue;
  304. }
  305. applicationIcon = _ncaIcon;
  306. titleName = Path.GetFileNameWithoutExtension(applicationPath);
  307. }
  308. // If its an NSO we just set defaults
  309. else if (Path.GetExtension(applicationPath).ToLower() == ".nso")
  310. {
  311. applicationIcon = _nsoIcon;
  312. titleName = Path.GetFileNameWithoutExtension(applicationPath);
  313. }
  314. }
  315. }
  316. catch (IOException exception)
  317. {
  318. Logger.PrintWarning(LogClass.Application, exception.Message);
  319. numApplicationsFound--;
  320. _loadingError = true;
  321. continue;
  322. }
  323. ApplicationMetadata appMetadata = LoadAndSaveMetaData(titleId);
  324. if (ulong.TryParse(titleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdNum))
  325. {
  326. SaveDataFilter filter = new SaveDataFilter();
  327. filter.SetUserId(new UserId(1, 0));
  328. filter.SetProgramId(new TitleId(titleIdNum));
  329. Result result = virtualFileSystem.FsClient.FindSaveDataWithFilter(out SaveDataInfo saveDataInfo, SaveDataSpaceId.User, ref filter);
  330. if (result.IsSuccess())
  331. {
  332. saveDataPath = Path.Combine(virtualFileSystem.GetNandPath(), "user", "save", saveDataInfo.SaveDataId.ToString("x16"));
  333. }
  334. }
  335. ApplicationData data = new ApplicationData
  336. {
  337. Favorite = appMetadata.Favorite,
  338. Icon = applicationIcon,
  339. TitleName = titleName,
  340. TitleId = titleId,
  341. Developer = developer,
  342. Version = version,
  343. TimePlayed = ConvertSecondsToReadableString(appMetadata.TimePlayed),
  344. LastPlayed = appMetadata.LastPlayed,
  345. FileExtension = Path.GetExtension(applicationPath).ToUpper().Remove(0, 1),
  346. FileSize = (fileSize < 1) ? (fileSize * 1024).ToString("0.##") + "MB" : fileSize.ToString("0.##") + "GB",
  347. Path = applicationPath,
  348. SaveDataPath = saveDataPath,
  349. ControlHolder = controlHolder
  350. };
  351. numApplicationsLoaded++;
  352. OnApplicationAdded(new ApplicationAddedEventArgs()
  353. {
  354. AppData = data
  355. });
  356. OnApplicationCountUpdated(new ApplicationCountUpdatedEventArgs()
  357. {
  358. NumAppsFound = numApplicationsFound,
  359. NumAppsLoaded = numApplicationsLoaded
  360. });
  361. }
  362. OnApplicationCountUpdated(new ApplicationCountUpdatedEventArgs()
  363. {
  364. NumAppsFound = numApplicationsFound,
  365. NumAppsLoaded = numApplicationsLoaded
  366. });
  367. if (_loadingError)
  368. {
  369. Gtk.Application.Invoke(delegate
  370. {
  371. GtkDialog.CreateErrorDialog("One or more files encountered could not be loaded, check logs for more info.");
  372. });
  373. }
  374. }
  375. protected static void OnApplicationAdded(ApplicationAddedEventArgs e)
  376. {
  377. ApplicationAdded?.Invoke(null, e);
  378. }
  379. protected static void OnApplicationCountUpdated(ApplicationCountUpdatedEventArgs e)
  380. {
  381. ApplicationCountUpdated?.Invoke(null, e);
  382. }
  383. private static byte[] GetResourceBytes(string resourceName)
  384. {
  385. Stream resourceStream = Assembly.GetCallingAssembly().GetManifestResourceStream(resourceName);
  386. byte[] resourceByteArray = new byte[resourceStream.Length];
  387. resourceStream.Read(resourceByteArray);
  388. return resourceByteArray;
  389. }
  390. private static void GetControlFsAndTitleId(PartitionFileSystem pfs, out IFileSystem controlFs, out string titleId)
  391. {
  392. Nca controlNca = null;
  393. // Add keys to key set if needed
  394. _virtualFileSystem.ImportTickets(pfs);
  395. // Find the Control NCA and store it in variable called controlNca
  396. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  397. {
  398. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  399. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  400. if (nca.Header.ContentType == NcaContentType.Control)
  401. {
  402. controlNca = nca;
  403. }
  404. }
  405. // Return the ControlFS
  406. controlFs = controlNca?.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
  407. titleId = controlNca?.Header.TitleId.ToString("x16");
  408. }
  409. internal static ApplicationMetadata LoadAndSaveMetaData(string titleId, Action<ApplicationMetadata> modifyFunction = null)
  410. {
  411. string metadataFolder = Path.Combine(_virtualFileSystem.GetBasePath(), "games", titleId, "gui");
  412. string metadataFile = Path.Combine(metadataFolder, "metadata.json");
  413. ApplicationMetadata appMetadata;
  414. if (!File.Exists(metadataFile))
  415. {
  416. Directory.CreateDirectory(metadataFolder);
  417. appMetadata = new ApplicationMetadata
  418. {
  419. Favorite = false,
  420. TimePlayed = 0,
  421. LastPlayed = "Never"
  422. };
  423. using (FileStream stream = File.Create(metadataFile, 4096, FileOptions.WriteThrough))
  424. {
  425. JsonHelper.Serialize(stream, appMetadata, true);
  426. }
  427. }
  428. try
  429. {
  430. appMetadata = JsonHelper.DeserializeFromFile<ApplicationMetadata>(metadataFile);
  431. }
  432. catch (JsonException)
  433. {
  434. Logger.PrintWarning(LogClass.Application, $"Failed to parse metadata json for {titleId}. Loading defaults.");
  435. appMetadata = new ApplicationMetadata
  436. {
  437. Favorite = false,
  438. TimePlayed = 0,
  439. LastPlayed = "Never"
  440. };
  441. }
  442. if (modifyFunction != null)
  443. {
  444. modifyFunction(appMetadata);
  445. using (FileStream stream = File.Create(metadataFile, 4096, FileOptions.WriteThrough))
  446. {
  447. JsonHelper.Serialize(stream, appMetadata, true);
  448. }
  449. }
  450. return appMetadata;
  451. }
  452. private static string ConvertSecondsToReadableString(double seconds)
  453. {
  454. const int secondsPerMinute = 60;
  455. const int secondsPerHour = secondsPerMinute * 60;
  456. const int secondsPerDay = secondsPerHour * 24;
  457. string readableString;
  458. if (seconds < secondsPerMinute)
  459. {
  460. readableString = $"{seconds}s";
  461. }
  462. else if (seconds < secondsPerHour)
  463. {
  464. readableString = $"{Math.Round(seconds / secondsPerMinute, 2, MidpointRounding.AwayFromZero)} mins";
  465. }
  466. else if (seconds < secondsPerDay)
  467. {
  468. readableString = $"{Math.Round(seconds / secondsPerHour, 2, MidpointRounding.AwayFromZero)} hrs";
  469. }
  470. else
  471. {
  472. readableString = $"{Math.Round(seconds / secondsPerDay, 2, MidpointRounding.AwayFromZero)} days";
  473. }
  474. return readableString;
  475. }
  476. private static void GetNameIdDeveloper(ref ApplicationControlProperty controlData, out string titleName, out string titleId, out string publisher)
  477. {
  478. Enum.TryParse(_desiredTitleLanguage.ToString(), out TitleLanguage desiredTitleLanguage);
  479. if (controlData.Titles.Length > (int)desiredTitleLanguage)
  480. {
  481. titleName = controlData.Titles[(int)desiredTitleLanguage].Name.ToString();
  482. publisher = controlData.Titles[(int)desiredTitleLanguage].Publisher.ToString();
  483. }
  484. else
  485. {
  486. titleName = null;
  487. publisher = null;
  488. }
  489. if (string.IsNullOrWhiteSpace(titleName))
  490. {
  491. foreach (ApplicationControlTitle controlTitle in controlData.Titles)
  492. {
  493. if (!((U8Span)controlTitle.Name).IsEmpty())
  494. {
  495. titleName = controlTitle.Name.ToString();
  496. break;
  497. }
  498. }
  499. }
  500. if (string.IsNullOrWhiteSpace(publisher))
  501. {
  502. foreach (ApplicationControlTitle controlTitle in controlData.Titles)
  503. {
  504. if (!((U8Span)controlTitle.Publisher).IsEmpty())
  505. {
  506. publisher = controlTitle.Publisher.ToString();
  507. break;
  508. }
  509. }
  510. }
  511. if (controlData.PresenceGroupId != 0)
  512. {
  513. titleId = controlData.PresenceGroupId.ToString("x16");
  514. }
  515. else if (controlData.SaveDataOwnerId.Value != 0)
  516. {
  517. titleId = controlData.SaveDataOwnerId.ToString();
  518. }
  519. else if (controlData.AddOnContentBaseId != 0)
  520. {
  521. titleId = (controlData.AddOnContentBaseId - 0x1000).ToString("x16");
  522. }
  523. else
  524. {
  525. titleId = "0000000000000000";
  526. }
  527. }
  528. private static bool IsUpdateApplied(string titleId, out string version)
  529. {
  530. string jsonPath = Path.Combine(_virtualFileSystem.GetBasePath(), "games", titleId, "updates.json");
  531. if (File.Exists(jsonPath))
  532. {
  533. string updatePath = JsonHelper.DeserializeFromFile<TitleUpdateMetadata>(jsonPath).Selected;
  534. if (!File.Exists(updatePath))
  535. {
  536. version = "";
  537. return false;
  538. }
  539. using (FileStream file = new FileStream(updatePath, FileMode.Open, FileAccess.Read))
  540. {
  541. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  542. _virtualFileSystem.ImportTickets(nsp);
  543. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  544. {
  545. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  546. try
  547. {
  548. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  549. if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != titleId)
  550. {
  551. break;
  552. }
  553. if (nca.Header.ContentType == NcaContentType.Control)
  554. {
  555. ApplicationControlProperty controlData = new ApplicationControlProperty();
  556. nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None).OpenFile(out IFile nacpFile, "/control.nacp".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  557. nacpFile.Read(out _, 0, SpanHelpers.AsByteSpan(ref controlData), ReadOption.None).ThrowIfFailure();
  558. version = controlData.DisplayVersion.ToString();
  559. return true;
  560. }
  561. }
  562. catch (InvalidDataException)
  563. {
  564. Logger.PrintWarning(LogClass.Application,
  565. $"The header key is incorrect or missing and therefore the NCA header content type check has failed. Errored File: {updatePath}");
  566. break;
  567. }
  568. catch (MissingKeyException exception)
  569. {
  570. Logger.PrintWarning(LogClass.Application,
  571. $"Your key set is missing a key with the name: {exception.Name}. Errored File: {updatePath}");
  572. break;
  573. }
  574. }
  575. }
  576. }
  577. version = "";
  578. return false;
  579. }
  580. }
  581. }