ApplicationLibrary.cs 30 KB

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