ApplicationLibrary.cs 37 KB

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