ApplicationLibrary.cs 38 KB

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