ApplicationLibrary.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. using LibHac;
  2. using LibHac.Common;
  3. using LibHac.Common.Keys;
  4. using LibHac.Fs;
  5. using LibHac.Fs.Fsa;
  6. using LibHac.FsSystem;
  7. using LibHac.Ns;
  8. using LibHac.Tools.Fs;
  9. using LibHac.Tools.FsSystem;
  10. using LibHac.Tools.FsSystem.NcaUtils;
  11. using Ryujinx.Common;
  12. using Ryujinx.Common.Configuration;
  13. using Ryujinx.Common.Logging;
  14. using Ryujinx.Common.Utilities;
  15. using Ryujinx.HLE.FileSystem;
  16. using Ryujinx.HLE.HOS.SystemState;
  17. using Ryujinx.HLE.Loaders.Npdm;
  18. using Ryujinx.UI.Common.Configuration;
  19. using Ryujinx.UI.Common.Configuration.System;
  20. using System;
  21. using System.Collections.Generic;
  22. using System.Globalization;
  23. using System.IO;
  24. using System.Linq;
  25. using System.Reflection;
  26. using System.Text;
  27. using System.Text.Json;
  28. using System.Threading;
  29. using Path = System.IO.Path;
  30. using TimeSpan = System.TimeSpan;
  31. namespace Ryujinx.UI.App.Common
  32. {
  33. public class ApplicationLibrary
  34. {
  35. public event EventHandler<ApplicationAddedEventArgs> ApplicationAdded;
  36. public event EventHandler<ApplicationCountUpdatedEventArgs> ApplicationCountUpdated;
  37. private readonly byte[] _nspIcon;
  38. private readonly byte[] _xciIcon;
  39. private readonly byte[] _ncaIcon;
  40. private readonly byte[] _nroIcon;
  41. private readonly byte[] _nsoIcon;
  42. private readonly VirtualFileSystem _virtualFileSystem;
  43. private Language _desiredTitleLanguage;
  44. private CancellationTokenSource _cancellationToken;
  45. private static readonly ApplicationJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions());
  46. private static readonly TitleUpdateMetadataJsonSerializerContext _titleSerializerContext = new(JsonHelper.GetDefaultSerializerOptions());
  47. public ApplicationLibrary(VirtualFileSystem virtualFileSystem)
  48. {
  49. _virtualFileSystem = virtualFileSystem;
  50. _nspIcon = GetResourceBytes("Ryujinx.UI.Common.Resources.Icon_NSP.png");
  51. _xciIcon = GetResourceBytes("Ryujinx.UI.Common.Resources.Icon_XCI.png");
  52. _ncaIcon = GetResourceBytes("Ryujinx.UI.Common.Resources.Icon_NCA.png");
  53. _nroIcon = GetResourceBytes("Ryujinx.UI.Common.Resources.Icon_NRO.png");
  54. _nsoIcon = GetResourceBytes("Ryujinx.UI.Common.Resources.Icon_NSO.png");
  55. }
  56. private static byte[] GetResourceBytes(string resourceName)
  57. {
  58. Stream resourceStream = Assembly.GetCallingAssembly().GetManifestResourceStream(resourceName);
  59. byte[] resourceByteArray = new byte[resourceStream.Length];
  60. resourceStream.Read(resourceByteArray);
  61. return resourceByteArray;
  62. }
  63. public void CancelLoading()
  64. {
  65. _cancellationToken?.Cancel();
  66. }
  67. public static void ReadControlData(IFileSystem controlFs, Span<byte> outProperty)
  68. {
  69. using UniqueRef<IFile> controlFile = new();
  70. controlFs.OpenFile(ref controlFile.Ref, "/control.nacp".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  71. controlFile.Get.Read(out _, 0, outProperty, ReadOption.None).ThrowIfFailure();
  72. }
  73. public void LoadApplications(List<string> appDirs, Language desiredTitleLanguage)
  74. {
  75. int numApplicationsFound = 0;
  76. int numApplicationsLoaded = 0;
  77. _desiredTitleLanguage = desiredTitleLanguage;
  78. _cancellationToken = new CancellationTokenSource();
  79. // Builds the applications list with paths to found applications
  80. List<string> applications = new();
  81. try
  82. {
  83. foreach (string appDir in appDirs)
  84. {
  85. if (_cancellationToken.Token.IsCancellationRequested)
  86. {
  87. return;
  88. }
  89. if (!Directory.Exists(appDir))
  90. {
  91. Logger.Warning?.Print(LogClass.Application, $"The \"game_dirs\" section in \"{ReleaseInformation.ConfigName}\" contains an invalid directory: \"{appDir}\"");
  92. continue;
  93. }
  94. try
  95. {
  96. IEnumerable<string> files = Directory.EnumerateFiles(appDir, "*", SearchOption.AllDirectories).Where(file =>
  97. {
  98. return
  99. (Path.GetExtension(file).ToLower() is ".nsp" && ConfigurationState.Instance.UI.ShownFileTypes.NSP.Value) ||
  100. (Path.GetExtension(file).ToLower() is ".pfs0" && ConfigurationState.Instance.UI.ShownFileTypes.PFS0.Value) ||
  101. (Path.GetExtension(file).ToLower() is ".xci" && ConfigurationState.Instance.UI.ShownFileTypes.XCI.Value) ||
  102. (Path.GetExtension(file).ToLower() is ".nca" && ConfigurationState.Instance.UI.ShownFileTypes.NCA.Value) ||
  103. (Path.GetExtension(file).ToLower() is ".nro" && ConfigurationState.Instance.UI.ShownFileTypes.NRO.Value) ||
  104. (Path.GetExtension(file).ToLower() is ".nso" && ConfigurationState.Instance.UI.ShownFileTypes.NSO.Value);
  105. });
  106. foreach (string app in files)
  107. {
  108. if (_cancellationToken.Token.IsCancellationRequested)
  109. {
  110. return;
  111. }
  112. var fileInfo = new FileInfo(app);
  113. string extension = fileInfo.Extension.ToLower();
  114. if (!fileInfo.Attributes.HasFlag(FileAttributes.Hidden) && extension is ".nsp" or ".pfs0" or ".xci" or ".nca" or ".nro" or ".nso")
  115. {
  116. var fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName;
  117. if (!File.Exists(fullPath))
  118. {
  119. Logger.Warning?.Print(LogClass.Application, $"Skipping invalid symlink: {fileInfo.FullName}");
  120. continue;
  121. }
  122. applications.Add(fullPath);
  123. numApplicationsFound++;
  124. }
  125. }
  126. }
  127. catch (UnauthorizedAccessException)
  128. {
  129. Logger.Warning?.Print(LogClass.Application, $"Failed to get access to directory: \"{appDir}\"");
  130. }
  131. }
  132. // Loops through applications list, creating a struct and then firing an event containing the struct for each application
  133. foreach (string applicationPath in applications)
  134. {
  135. if (_cancellationToken.Token.IsCancellationRequested)
  136. {
  137. return;
  138. }
  139. long fileSize = new FileInfo(applicationPath).Length;
  140. string titleName = "Unknown";
  141. string titleId = "0000000000000000";
  142. string developer = "Unknown";
  143. string version = "0";
  144. byte[] applicationIcon = null;
  145. BlitStruct<ApplicationControlProperty> controlHolder = new(1);
  146. try
  147. {
  148. string extension = Path.GetExtension(applicationPath).ToLower();
  149. using FileStream file = new(applicationPath, FileMode.Open, FileAccess.Read);
  150. if (extension == ".nsp" || extension == ".pfs0" || extension == ".xci")
  151. {
  152. try
  153. {
  154. IFileSystem pfs;
  155. bool isExeFs = false;
  156. if (extension == ".xci")
  157. {
  158. Xci xci = new(_virtualFileSystem.KeySet, file.AsStorage());
  159. pfs = xci.OpenPartition(XciPartitionType.Secure);
  160. }
  161. else
  162. {
  163. var pfsTemp = new PartitionFileSystem();
  164. pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure();
  165. pfs = pfsTemp;
  166. // If the NSP doesn't have a main NCA, decrement the number of applications found and then continue to the next application.
  167. bool hasMainNca = false;
  168. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*"))
  169. {
  170. if (Path.GetExtension(fileEntry.FullPath).ToLower() == ".nca")
  171. {
  172. using UniqueRef<IFile> ncaFile = new();
  173. pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  174. Nca nca = new(_virtualFileSystem.KeySet, ncaFile.Get.AsStorage());
  175. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  176. // Some main NCAs don't have a data partition, so check if the partition exists before opening it
  177. if (nca.Header.ContentType == NcaContentType.Program && !(nca.SectionExists(NcaSectionType.Data) && nca.Header.GetFsHeader(dataIndex).IsPatchSection()))
  178. {
  179. hasMainNca = true;
  180. break;
  181. }
  182. }
  183. else if (Path.GetFileNameWithoutExtension(fileEntry.FullPath) == "main")
  184. {
  185. isExeFs = true;
  186. }
  187. }
  188. if (!hasMainNca && !isExeFs)
  189. {
  190. numApplicationsFound--;
  191. continue;
  192. }
  193. }
  194. if (isExeFs)
  195. {
  196. applicationIcon = _nspIcon;
  197. using UniqueRef<IFile> npdmFile = new();
  198. Result result = pfs.OpenFile(ref npdmFile.Ref, "/main.npdm".ToU8Span(), OpenMode.Read);
  199. if (ResultFs.PathNotFound.Includes(result))
  200. {
  201. Npdm npdm = new(npdmFile.Get.AsStream());
  202. titleName = npdm.TitleName;
  203. titleId = npdm.Aci0.TitleId.ToString("x16");
  204. }
  205. }
  206. else
  207. {
  208. GetControlFsAndTitleId(pfs, out IFileSystem controlFs, out titleId);
  209. // Check if there is an update available.
  210. if (IsUpdateApplied(titleId, out IFileSystem updatedControlFs))
  211. {
  212. // Replace the original ControlFs by the updated one.
  213. controlFs = updatedControlFs;
  214. }
  215. ReadControlData(controlFs, controlHolder.ByteSpan);
  216. GetGameInformation(ref controlHolder.Value, out titleName, out _, out developer, out version);
  217. // Read the icon from the ControlFS and store it as a byte array
  218. try
  219. {
  220. using UniqueRef<IFile> icon = new();
  221. controlFs.OpenFile(ref icon.Ref, $"/icon_{_desiredTitleLanguage}.dat".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  222. using MemoryStream stream = new();
  223. icon.Get.AsStream().CopyTo(stream);
  224. applicationIcon = stream.ToArray();
  225. }
  226. catch (HorizonResultException)
  227. {
  228. foreach (DirectoryEntryEx entry in controlFs.EnumerateEntries("/", "*"))
  229. {
  230. if (entry.Name == "control.nacp")
  231. {
  232. continue;
  233. }
  234. using var icon = new UniqueRef<IFile>();
  235. controlFs.OpenFile(ref icon.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  236. using MemoryStream stream = new();
  237. icon.Get.AsStream().CopyTo(stream);
  238. applicationIcon = stream.ToArray();
  239. if (applicationIcon != null)
  240. {
  241. break;
  242. }
  243. }
  244. applicationIcon ??= extension == ".xci" ? _xciIcon : _nspIcon;
  245. }
  246. }
  247. }
  248. catch (MissingKeyException exception)
  249. {
  250. applicationIcon = extension == ".xci" ? _xciIcon : _nspIcon;
  251. Logger.Warning?.Print(LogClass.Application, $"Your key set is missing a key with the name: {exception.Name}");
  252. }
  253. catch (InvalidDataException)
  254. {
  255. applicationIcon = extension == ".xci" ? _xciIcon : _nspIcon;
  256. 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}");
  257. }
  258. catch (Exception exception)
  259. {
  260. Logger.Warning?.Print(LogClass.Application, $"The file encountered was not of a valid type. File: '{applicationPath}' Error: {exception}");
  261. numApplicationsFound--;
  262. continue;
  263. }
  264. }
  265. else if (extension == ".nro")
  266. {
  267. BinaryReader reader = new(file);
  268. byte[] Read(long position, int size)
  269. {
  270. file.Seek(position, SeekOrigin.Begin);
  271. return reader.ReadBytes(size);
  272. }
  273. try
  274. {
  275. file.Seek(24, SeekOrigin.Begin);
  276. int assetOffset = reader.ReadInt32();
  277. if (Encoding.ASCII.GetString(Read(assetOffset, 4)) == "ASET")
  278. {
  279. byte[] iconSectionInfo = Read(assetOffset + 8, 0x10);
  280. long iconOffset = BitConverter.ToInt64(iconSectionInfo, 0);
  281. long iconSize = BitConverter.ToInt64(iconSectionInfo, 8);
  282. ulong nacpOffset = reader.ReadUInt64();
  283. ulong nacpSize = reader.ReadUInt64();
  284. // Reads and stores game icon as byte array
  285. if (iconSize > 0)
  286. {
  287. applicationIcon = Read(assetOffset + iconOffset, (int)iconSize);
  288. }
  289. else
  290. {
  291. applicationIcon = _nroIcon;
  292. }
  293. // Read the NACP data
  294. Read(assetOffset + (int)nacpOffset, (int)nacpSize).AsSpan().CopyTo(controlHolder.ByteSpan);
  295. GetGameInformation(ref controlHolder.Value, out titleName, out titleId, out developer, out version);
  296. }
  297. else
  298. {
  299. applicationIcon = _nroIcon;
  300. titleName = Path.GetFileNameWithoutExtension(applicationPath);
  301. }
  302. }
  303. catch
  304. {
  305. Logger.Warning?.Print(LogClass.Application, $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  306. numApplicationsFound--;
  307. continue;
  308. }
  309. }
  310. else if (extension == ".nca")
  311. {
  312. try
  313. {
  314. Nca nca = new(_virtualFileSystem.KeySet, new FileStream(applicationPath, FileMode.Open, FileAccess.Read).AsStorage());
  315. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  316. if (nca.Header.ContentType != NcaContentType.Program || (nca.SectionExists(NcaSectionType.Data) && nca.Header.GetFsHeader(dataIndex).IsPatchSection()))
  317. {
  318. numApplicationsFound--;
  319. continue;
  320. }
  321. }
  322. catch (InvalidDataException)
  323. {
  324. 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}");
  325. }
  326. catch
  327. {
  328. Logger.Warning?.Print(LogClass.Application, $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  329. numApplicationsFound--;
  330. continue;
  331. }
  332. applicationIcon = _ncaIcon;
  333. titleName = Path.GetFileNameWithoutExtension(applicationPath);
  334. }
  335. // If its an NSO we just set defaults
  336. else if (extension == ".nso")
  337. {
  338. applicationIcon = _nsoIcon;
  339. titleName = Path.GetFileNameWithoutExtension(applicationPath);
  340. }
  341. }
  342. catch (IOException exception)
  343. {
  344. Logger.Warning?.Print(LogClass.Application, exception.Message);
  345. numApplicationsFound--;
  346. continue;
  347. }
  348. ApplicationMetadata appMetadata = LoadAndSaveMetaData(titleId, appMetadata =>
  349. {
  350. appMetadata.Title = titleName;
  351. // Only do the migration if time_played has a value and timespan_played hasn't been updated yet.
  352. if (appMetadata.TimePlayedOld != default && appMetadata.TimePlayed == TimeSpan.Zero)
  353. {
  354. appMetadata.TimePlayed = TimeSpan.FromSeconds(appMetadata.TimePlayedOld);
  355. appMetadata.TimePlayedOld = default;
  356. }
  357. // Only do the migration if last_played has a value and last_played_utc doesn't exist yet.
  358. if (appMetadata.LastPlayedOld != default && !appMetadata.LastPlayed.HasValue)
  359. {
  360. // Migrate from string-based last_played to DateTime-based last_played_utc.
  361. if (DateTime.TryParse(appMetadata.LastPlayedOld, out DateTime lastPlayedOldParsed))
  362. {
  363. appMetadata.LastPlayed = lastPlayedOldParsed;
  364. // Migration successful: deleting last_played from the metadata file.
  365. appMetadata.LastPlayedOld = default;
  366. }
  367. }
  368. });
  369. ApplicationData data = new()
  370. {
  371. Favorite = appMetadata.Favorite,
  372. Icon = applicationIcon,
  373. TitleName = titleName,
  374. TitleId = titleId,
  375. Developer = developer,
  376. Version = version,
  377. TimePlayed = appMetadata.TimePlayed,
  378. LastPlayed = appMetadata.LastPlayed,
  379. FileExtension = Path.GetExtension(applicationPath).TrimStart('.').ToUpper(),
  380. FileSize = fileSize,
  381. Path = applicationPath,
  382. ControlHolder = controlHolder,
  383. };
  384. numApplicationsLoaded++;
  385. OnApplicationAdded(new ApplicationAddedEventArgs
  386. {
  387. AppData = data,
  388. });
  389. OnApplicationCountUpdated(new ApplicationCountUpdatedEventArgs
  390. {
  391. NumAppsFound = numApplicationsFound,
  392. NumAppsLoaded = numApplicationsLoaded,
  393. });
  394. }
  395. OnApplicationCountUpdated(new ApplicationCountUpdatedEventArgs
  396. {
  397. NumAppsFound = numApplicationsFound,
  398. NumAppsLoaded = numApplicationsLoaded,
  399. });
  400. }
  401. finally
  402. {
  403. _cancellationToken.Dispose();
  404. _cancellationToken = null;
  405. }
  406. }
  407. protected void OnApplicationAdded(ApplicationAddedEventArgs e)
  408. {
  409. ApplicationAdded?.Invoke(null, e);
  410. }
  411. protected void OnApplicationCountUpdated(ApplicationCountUpdatedEventArgs e)
  412. {
  413. ApplicationCountUpdated?.Invoke(null, e);
  414. }
  415. private void GetControlFsAndTitleId(IFileSystem pfs, out IFileSystem controlFs, out string titleId)
  416. {
  417. (_, _, Nca controlNca) = GetGameData(_virtualFileSystem, pfs, 0);
  418. // Return the ControlFS
  419. controlFs = controlNca?.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
  420. titleId = controlNca?.Header.TitleId.ToString("x16");
  421. }
  422. public static ApplicationMetadata LoadAndSaveMetaData(string titleId, Action<ApplicationMetadata> modifyFunction = null)
  423. {
  424. string metadataFolder = Path.Combine(AppDataManager.GamesDirPath, titleId, "gui");
  425. string metadataFile = Path.Combine(metadataFolder, "metadata.json");
  426. ApplicationMetadata appMetadata;
  427. if (!File.Exists(metadataFile))
  428. {
  429. Directory.CreateDirectory(metadataFolder);
  430. appMetadata = new ApplicationMetadata();
  431. JsonHelper.SerializeToFile(metadataFile, appMetadata, _serializerContext.ApplicationMetadata);
  432. }
  433. try
  434. {
  435. appMetadata = JsonHelper.DeserializeFromFile(metadataFile, _serializerContext.ApplicationMetadata);
  436. }
  437. catch (JsonException)
  438. {
  439. Logger.Warning?.Print(LogClass.Application, $"Failed to parse metadata json for {titleId}. Loading defaults.");
  440. appMetadata = new ApplicationMetadata();
  441. }
  442. if (modifyFunction != null)
  443. {
  444. modifyFunction(appMetadata);
  445. JsonHelper.SerializeToFile(metadataFile, appMetadata, _serializerContext.ApplicationMetadata);
  446. }
  447. return appMetadata;
  448. }
  449. public byte[] GetApplicationIcon(string applicationPath, Language desiredTitleLanguage)
  450. {
  451. byte[] applicationIcon = null;
  452. try
  453. {
  454. // Look for icon only if applicationPath is not a directory
  455. if (!Directory.Exists(applicationPath))
  456. {
  457. string extension = Path.GetExtension(applicationPath).ToLower();
  458. using FileStream file = new(applicationPath, FileMode.Open, FileAccess.Read);
  459. if (extension == ".nsp" || extension == ".pfs0" || extension == ".xci")
  460. {
  461. try
  462. {
  463. IFileSystem pfs;
  464. bool isExeFs = false;
  465. if (extension == ".xci")
  466. {
  467. Xci xci = new(_virtualFileSystem.KeySet, file.AsStorage());
  468. pfs = xci.OpenPartition(XciPartitionType.Secure);
  469. }
  470. else
  471. {
  472. var pfsTemp = new PartitionFileSystem();
  473. pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure();
  474. pfs = pfsTemp;
  475. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*"))
  476. {
  477. if (Path.GetFileNameWithoutExtension(fileEntry.FullPath) == "main")
  478. {
  479. isExeFs = true;
  480. }
  481. }
  482. }
  483. if (isExeFs)
  484. {
  485. applicationIcon = _nspIcon;
  486. }
  487. else
  488. {
  489. // Store the ControlFS in variable called controlFs
  490. GetControlFsAndTitleId(pfs, out IFileSystem controlFs, out _);
  491. // Read the icon from the ControlFS and store it as a byte array
  492. try
  493. {
  494. using var icon = new UniqueRef<IFile>();
  495. controlFs.OpenFile(ref icon.Ref, $"/icon_{desiredTitleLanguage}.dat".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  496. using MemoryStream stream = new();
  497. icon.Get.AsStream().CopyTo(stream);
  498. applicationIcon = stream.ToArray();
  499. }
  500. catch (HorizonResultException)
  501. {
  502. foreach (DirectoryEntryEx entry in controlFs.EnumerateEntries("/", "*"))
  503. {
  504. if (entry.Name == "control.nacp")
  505. {
  506. continue;
  507. }
  508. using var icon = new UniqueRef<IFile>();
  509. controlFs.OpenFile(ref icon.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  510. using (MemoryStream stream = new())
  511. {
  512. icon.Get.AsStream().CopyTo(stream);
  513. applicationIcon = stream.ToArray();
  514. }
  515. if (applicationIcon != null)
  516. {
  517. break;
  518. }
  519. }
  520. applicationIcon ??= extension == ".xci" ? _xciIcon : _nspIcon;
  521. }
  522. }
  523. }
  524. catch (MissingKeyException)
  525. {
  526. applicationIcon = extension == ".xci" ? _xciIcon : _nspIcon;
  527. }
  528. catch (InvalidDataException)
  529. {
  530. applicationIcon = extension == ".xci" ? _xciIcon : _nspIcon;
  531. }
  532. catch (Exception exception)
  533. {
  534. Logger.Warning?.Print(LogClass.Application, $"The file encountered was not of a valid type. File: '{applicationPath}' Error: {exception}");
  535. }
  536. }
  537. else if (extension == ".nro")
  538. {
  539. BinaryReader reader = new(file);
  540. byte[] Read(long position, int size)
  541. {
  542. file.Seek(position, SeekOrigin.Begin);
  543. return reader.ReadBytes(size);
  544. }
  545. try
  546. {
  547. file.Seek(24, SeekOrigin.Begin);
  548. int assetOffset = reader.ReadInt32();
  549. if (Encoding.ASCII.GetString(Read(assetOffset, 4)) == "ASET")
  550. {
  551. byte[] iconSectionInfo = Read(assetOffset + 8, 0x10);
  552. long iconOffset = BitConverter.ToInt64(iconSectionInfo, 0);
  553. long iconSize = BitConverter.ToInt64(iconSectionInfo, 8);
  554. // Reads and stores game icon as byte array
  555. if (iconSize > 0)
  556. {
  557. applicationIcon = Read(assetOffset + iconOffset, (int)iconSize);
  558. }
  559. else
  560. {
  561. applicationIcon = _nroIcon;
  562. }
  563. }
  564. else
  565. {
  566. applicationIcon = _nroIcon;
  567. }
  568. }
  569. catch
  570. {
  571. Logger.Warning?.Print(LogClass.Application, $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  572. }
  573. }
  574. else if (extension == ".nca")
  575. {
  576. applicationIcon = _ncaIcon;
  577. }
  578. // If its an NSO we just set defaults
  579. else if (extension == ".nso")
  580. {
  581. applicationIcon = _nsoIcon;
  582. }
  583. }
  584. }
  585. catch (Exception)
  586. {
  587. Logger.Warning?.Print(LogClass.Application, $"Could not retrieve a valid icon for the app. Default icon will be used. Errored File: {applicationPath}");
  588. }
  589. return applicationIcon ?? _ncaIcon;
  590. }
  591. private void GetGameInformation(ref ApplicationControlProperty controlData, out string titleName, out string titleId, out string publisher, out string version)
  592. {
  593. _ = Enum.TryParse(_desiredTitleLanguage.ToString(), out TitleLanguage desiredTitleLanguage);
  594. if (controlData.Title.ItemsRo.Length > (int)desiredTitleLanguage)
  595. {
  596. titleName = controlData.Title[(int)desiredTitleLanguage].NameString.ToString();
  597. publisher = controlData.Title[(int)desiredTitleLanguage].PublisherString.ToString();
  598. }
  599. else
  600. {
  601. titleName = null;
  602. publisher = null;
  603. }
  604. if (string.IsNullOrWhiteSpace(titleName))
  605. {
  606. foreach (ref readonly var controlTitle in controlData.Title.ItemsRo)
  607. {
  608. if (!controlTitle.NameString.IsEmpty())
  609. {
  610. titleName = controlTitle.NameString.ToString();
  611. break;
  612. }
  613. }
  614. }
  615. if (string.IsNullOrWhiteSpace(publisher))
  616. {
  617. foreach (ref readonly var controlTitle in controlData.Title.ItemsRo)
  618. {
  619. if (!controlTitle.PublisherString.IsEmpty())
  620. {
  621. publisher = controlTitle.PublisherString.ToString();
  622. break;
  623. }
  624. }
  625. }
  626. if (controlData.PresenceGroupId != 0)
  627. {
  628. titleId = controlData.PresenceGroupId.ToString("x16");
  629. }
  630. else if (controlData.SaveDataOwnerId != 0)
  631. {
  632. titleId = controlData.SaveDataOwnerId.ToString();
  633. }
  634. else if (controlData.AddOnContentBaseId != 0)
  635. {
  636. titleId = (controlData.AddOnContentBaseId - 0x1000).ToString("x16");
  637. }
  638. else
  639. {
  640. titleId = "0000000000000000";
  641. }
  642. version = controlData.DisplayVersionString.ToString();
  643. }
  644. private bool IsUpdateApplied(string titleId, out IFileSystem updatedControlFs)
  645. {
  646. updatedControlFs = null;
  647. string updatePath = "(unknown)";
  648. try
  649. {
  650. (Nca patchNca, Nca controlNca) = GetGameUpdateData(_virtualFileSystem, titleId, 0, out updatePath);
  651. if (patchNca != null && controlNca != null)
  652. {
  653. updatedControlFs = controlNca?.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
  654. return true;
  655. }
  656. }
  657. catch (InvalidDataException)
  658. {
  659. Logger.Warning?.Print(LogClass.Application, $"The header key is incorrect or missing and therefore the NCA header content type check has failed. Errored File: {updatePath}");
  660. }
  661. catch (MissingKeyException exception)
  662. {
  663. Logger.Warning?.Print(LogClass.Application, $"Your key set is missing a key with the name: {exception.Name}. Errored File: {updatePath}");
  664. }
  665. return false;
  666. }
  667. public static (Nca main, Nca patch, Nca control) GetGameData(VirtualFileSystem fileSystem, IFileSystem pfs, int programIndex)
  668. {
  669. Nca mainNca = null;
  670. Nca patchNca = null;
  671. Nca controlNca = null;
  672. fileSystem.ImportTickets(pfs);
  673. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  674. {
  675. using var ncaFile = new UniqueRef<IFile>();
  676. pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  677. Nca nca = new(fileSystem.KeySet, ncaFile.Release().AsStorage());
  678. int ncaProgramIndex = (int)(nca.Header.TitleId & 0xF);
  679. if (ncaProgramIndex != programIndex)
  680. {
  681. continue;
  682. }
  683. if (nca.Header.ContentType == NcaContentType.Program)
  684. {
  685. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  686. if (nca.SectionExists(NcaSectionType.Data) && nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  687. {
  688. patchNca = nca;
  689. }
  690. else
  691. {
  692. mainNca = nca;
  693. }
  694. }
  695. else if (nca.Header.ContentType == NcaContentType.Control)
  696. {
  697. controlNca = nca;
  698. }
  699. }
  700. return (mainNca, patchNca, controlNca);
  701. }
  702. public static (Nca patch, Nca control) GetGameUpdateDataFromPartition(VirtualFileSystem fileSystem, PartitionFileSystem pfs, string titleId, int programIndex)
  703. {
  704. Nca patchNca = null;
  705. Nca controlNca = null;
  706. fileSystem.ImportTickets(pfs);
  707. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  708. {
  709. using var ncaFile = new UniqueRef<IFile>();
  710. pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  711. Nca nca = new(fileSystem.KeySet, ncaFile.Release().AsStorage());
  712. int ncaProgramIndex = (int)(nca.Header.TitleId & 0xF);
  713. if (ncaProgramIndex != programIndex)
  714. {
  715. continue;
  716. }
  717. if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != titleId)
  718. {
  719. break;
  720. }
  721. if (nca.Header.ContentType == NcaContentType.Program)
  722. {
  723. patchNca = nca;
  724. }
  725. else if (nca.Header.ContentType == NcaContentType.Control)
  726. {
  727. controlNca = nca;
  728. }
  729. }
  730. return (patchNca, controlNca);
  731. }
  732. public static (Nca patch, Nca control) GetGameUpdateData(VirtualFileSystem fileSystem, string titleId, int programIndex, out string updatePath)
  733. {
  734. updatePath = null;
  735. if (ulong.TryParse(titleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdBase))
  736. {
  737. // Clear the program index part.
  738. titleIdBase &= ~0xFUL;
  739. // Load update information if exists.
  740. string titleUpdateMetadataPath = Path.Combine(AppDataManager.GamesDirPath, titleIdBase.ToString("x16"), "updates.json");
  741. if (File.Exists(titleUpdateMetadataPath))
  742. {
  743. updatePath = JsonHelper.DeserializeFromFile(titleUpdateMetadataPath, _titleSerializerContext.TitleUpdateMetadata).Selected;
  744. if (File.Exists(updatePath))
  745. {
  746. FileStream file = new(updatePath, FileMode.Open, FileAccess.Read);
  747. PartitionFileSystem nsp = new();
  748. nsp.Initialize(file.AsStorage()).ThrowIfFailure();
  749. return GetGameUpdateDataFromPartition(fileSystem, nsp, titleIdBase.ToString("x16"), programIndex);
  750. }
  751. }
  752. }
  753. return (null, null);
  754. }
  755. }
  756. }