ApplicationLibrary.cs 38 KB

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