ApplicationLibrary.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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 Utf8Json;
  22. using Utf8Json.Resolvers;
  23. using RightsId = LibHac.Fs.RightsId;
  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 long _, 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. foreach (DirectoryEntryEx ticketEntry in pfs.EnumerateEntries("/", "*.tik"))
  395. {
  396. Result result = pfs.OpenFile(out IFile ticketFile, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
  397. if (result.IsSuccess())
  398. {
  399. Ticket ticket = new Ticket(ticketFile.AsStream());
  400. _virtualFileSystem.KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(_virtualFileSystem.KeySet)));
  401. }
  402. }
  403. // Find the Control NCA and store it in variable called controlNca
  404. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  405. {
  406. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  407. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  408. if (nca.Header.ContentType == NcaContentType.Control)
  409. {
  410. controlNca = nca;
  411. }
  412. }
  413. // Return the ControlFS
  414. controlFs = controlNca?.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
  415. titleId = controlNca?.Header.TitleId.ToString("x16");
  416. }
  417. internal static ApplicationMetadata LoadAndSaveMetaData(string titleId, Action<ApplicationMetadata> modifyFunction = null)
  418. {
  419. string metadataFolder = Path.Combine(_virtualFileSystem.GetBasePath(), "games", titleId, "gui");
  420. string metadataFile = Path.Combine(metadataFolder, "metadata.json");
  421. IJsonFormatterResolver resolver = CompositeResolver.Create(StandardResolver.AllowPrivateSnakeCase);
  422. ApplicationMetadata appMetadata;
  423. if (!File.Exists(metadataFile))
  424. {
  425. Directory.CreateDirectory(metadataFolder);
  426. appMetadata = new ApplicationMetadata
  427. {
  428. Favorite = false,
  429. TimePlayed = 0,
  430. LastPlayed = "Never"
  431. };
  432. using (FileStream stream = File.Create(metadataFile, 4096, FileOptions.WriteThrough))
  433. {
  434. JsonSerializer.Serialize(stream, appMetadata, resolver);
  435. }
  436. }
  437. using (Stream stream = File.OpenRead(metadataFile))
  438. {
  439. try
  440. {
  441. appMetadata = JsonSerializer.Deserialize<ApplicationMetadata>(stream, resolver);
  442. }
  443. catch (JsonParsingException)
  444. {
  445. Logger.PrintWarning(LogClass.Application, $"Failed to parse metadata json for {titleId}. Loading defaults.");
  446. appMetadata = new ApplicationMetadata
  447. {
  448. Favorite = false,
  449. TimePlayed = 0,
  450. LastPlayed = "Never"
  451. };
  452. }
  453. }
  454. if (modifyFunction != null)
  455. {
  456. modifyFunction(appMetadata);
  457. using (FileStream stream = File.Create(metadataFile, 4096, FileOptions.WriteThrough))
  458. {
  459. JsonSerializer.Serialize(stream, appMetadata, resolver);
  460. }
  461. }
  462. return appMetadata;
  463. }
  464. private static string ConvertSecondsToReadableString(double seconds)
  465. {
  466. const int secondsPerMinute = 60;
  467. const int secondsPerHour = secondsPerMinute * 60;
  468. const int secondsPerDay = secondsPerHour * 24;
  469. string readableString;
  470. if (seconds < secondsPerMinute)
  471. {
  472. readableString = $"{seconds}s";
  473. }
  474. else if (seconds < secondsPerHour)
  475. {
  476. readableString = $"{Math.Round(seconds / secondsPerMinute, 2, MidpointRounding.AwayFromZero)} mins";
  477. }
  478. else if (seconds < secondsPerDay)
  479. {
  480. readableString = $"{Math.Round(seconds / secondsPerHour, 2, MidpointRounding.AwayFromZero)} hrs";
  481. }
  482. else
  483. {
  484. readableString = $"{Math.Round(seconds / secondsPerDay, 2, MidpointRounding.AwayFromZero)} days";
  485. }
  486. return readableString;
  487. }
  488. private static void GetNameIdDeveloper(ref ApplicationControlProperty controlData, out string titleName, out string titleId, out string publisher)
  489. {
  490. Enum.TryParse(_desiredTitleLanguage.ToString(), out TitleLanguage desiredTitleLanguage);
  491. if (controlData.Titles.Length > (int)desiredTitleLanguage)
  492. {
  493. titleName = controlData.Titles[(int)desiredTitleLanguage].Name.ToString();
  494. publisher = controlData.Titles[(int)desiredTitleLanguage].Publisher.ToString();
  495. }
  496. else
  497. {
  498. titleName = null;
  499. publisher = null;
  500. }
  501. if (string.IsNullOrWhiteSpace(titleName))
  502. {
  503. foreach (ApplicationControlTitle controlTitle in controlData.Titles)
  504. {
  505. if (!((U8Span)controlTitle.Name).IsEmpty())
  506. {
  507. titleName = controlTitle.Name.ToString();
  508. break;
  509. }
  510. }
  511. }
  512. if (string.IsNullOrWhiteSpace(publisher))
  513. {
  514. foreach (ApplicationControlTitle controlTitle in controlData.Titles)
  515. {
  516. if (!((U8Span)controlTitle.Publisher).IsEmpty())
  517. {
  518. publisher = controlTitle.Publisher.ToString();
  519. break;
  520. }
  521. }
  522. }
  523. if (controlData.PresenceGroupId != 0)
  524. {
  525. titleId = controlData.PresenceGroupId.ToString("x16");
  526. }
  527. else if (controlData.SaveDataOwnerId.Value != 0)
  528. {
  529. titleId = controlData.SaveDataOwnerId.ToString();
  530. }
  531. else if (controlData.AddOnContentBaseId != 0)
  532. {
  533. titleId = (controlData.AddOnContentBaseId - 0x1000).ToString("x16");
  534. }
  535. else
  536. {
  537. titleId = "0000000000000000";
  538. }
  539. }
  540. private static bool IsUpdateApplied(string titleId, out string version)
  541. {
  542. string jsonPath = Path.Combine(_virtualFileSystem.GetBasePath(), "games", titleId, "updates.json");
  543. if (File.Exists(jsonPath))
  544. {
  545. using (Stream stream = File.OpenRead(jsonPath))
  546. {
  547. IJsonFormatterResolver resolver = CompositeResolver.Create(StandardResolver.AllowPrivateSnakeCase);
  548. string updatePath = JsonSerializer.Deserialize<TitleUpdateMetadata>(stream, resolver).Selected;
  549. if (!File.Exists(updatePath))
  550. {
  551. version = "";
  552. return false;
  553. }
  554. using (FileStream file = new FileStream(updatePath, FileMode.Open, FileAccess.Read))
  555. {
  556. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  557. foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik"))
  558. {
  559. Result result = nsp.OpenFile(out IFile ticketFile, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
  560. if (result.IsSuccess())
  561. {
  562. Ticket ticket = new Ticket(ticketFile.AsStream());
  563. _virtualFileSystem.KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(_virtualFileSystem.KeySet)));
  564. }
  565. }
  566. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  567. {
  568. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  569. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  570. if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != titleId)
  571. {
  572. break;
  573. }
  574. if (nca.Header.ContentType == NcaContentType.Control)
  575. {
  576. ApplicationControlProperty controlData = new ApplicationControlProperty();
  577. nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None).OpenFile(out IFile nacpFile, "/control.nacp".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  578. nacpFile.Read(out long _, 0, SpanHelpers.AsByteSpan(ref controlData), ReadOption.None).ThrowIfFailure();
  579. version = controlData.DisplayVersion.ToString();
  580. return true;
  581. }
  582. }
  583. }
  584. }
  585. }
  586. version = "";
  587. return false;
  588. }
  589. }
  590. }