ApplicationLibrary.cs 31 KB

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