ApplicationLibrary.cs 29 KB

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