ApplicationLibrary.cs 36 KB

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