ApplicationLibrary.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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);
  364. if (appMetadata.LastPlayed != "Never" && !DateTime.TryParse(appMetadata.LastPlayed, out _))
  365. {
  366. Logger.Warning?.Print(LogClass.Application, $"Last played datetime \"{appMetadata.LastPlayed}\" is invalid for current system culture, skipping (did current culture change?)");
  367. appMetadata.LastPlayed = "Never";
  368. }
  369. ApplicationData data = new ApplicationData
  370. {
  371. Favorite = appMetadata.Favorite,
  372. Icon = applicationIcon,
  373. TitleName = titleName,
  374. TitleId = titleId,
  375. Developer = developer,
  376. Version = version,
  377. TimePlayed = ConvertSecondsToReadableString(appMetadata.TimePlayed),
  378. LastPlayed = appMetadata.LastPlayed,
  379. FileExtension = Path.GetExtension(applicationPath).ToUpper().Remove(0, 1),
  380. FileSize = (fileSize < 1) ? (fileSize * 1024).ToString("0.##") + "MB" : fileSize.ToString("0.##") + "GB",
  381. Path = applicationPath,
  382. ControlHolder = controlHolder
  383. };
  384. numApplicationsLoaded++;
  385. OnApplicationAdded(new ApplicationAddedEventArgs()
  386. {
  387. AppData = data
  388. });
  389. OnApplicationCountUpdated(new ApplicationCountUpdatedEventArgs()
  390. {
  391. NumAppsFound = numApplicationsFound,
  392. NumAppsLoaded = numApplicationsLoaded
  393. });
  394. }
  395. OnApplicationCountUpdated(new ApplicationCountUpdatedEventArgs()
  396. {
  397. NumAppsFound = numApplicationsFound,
  398. NumAppsLoaded = numApplicationsLoaded
  399. });
  400. }
  401. finally
  402. {
  403. _cancellationToken.Dispose();
  404. _cancellationToken = null;
  405. }
  406. }
  407. protected void OnApplicationAdded(ApplicationAddedEventArgs e)
  408. {
  409. ApplicationAdded?.Invoke(null, e);
  410. }
  411. protected void OnApplicationCountUpdated(ApplicationCountUpdatedEventArgs e)
  412. {
  413. ApplicationCountUpdated?.Invoke(null, e);
  414. }
  415. private void GetControlFsAndTitleId(PartitionFileSystem pfs, out IFileSystem controlFs, out string titleId)
  416. {
  417. (_, _, Nca controlNca) = ApplicationLoader.GetGameData(_virtualFileSystem, pfs, 0);
  418. // Return the ControlFS
  419. controlFs = controlNca?.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
  420. titleId = controlNca?.Header.TitleId.ToString("x16");
  421. }
  422. public ApplicationMetadata LoadAndSaveMetaData(string titleId, Action<ApplicationMetadata> modifyFunction = null)
  423. {
  424. string metadataFolder = Path.Combine(AppDataManager.GamesDirPath, titleId, "gui");
  425. string metadataFile = Path.Combine(metadataFolder, "metadata.json");
  426. ApplicationMetadata appMetadata;
  427. if (!File.Exists(metadataFile))
  428. {
  429. Directory.CreateDirectory(metadataFolder);
  430. appMetadata = new ApplicationMetadata();
  431. using (FileStream stream = File.Create(metadataFile, 4096, FileOptions.WriteThrough))
  432. {
  433. JsonHelper.Serialize(stream, appMetadata, true);
  434. }
  435. }
  436. try
  437. {
  438. appMetadata = JsonHelper.DeserializeFromFile<ApplicationMetadata>(metadataFile);
  439. }
  440. catch (JsonException)
  441. {
  442. Logger.Warning?.Print(LogClass.Application, $"Failed to parse metadata json for {titleId}. Loading defaults.");
  443. appMetadata = new ApplicationMetadata();
  444. }
  445. if (modifyFunction != null)
  446. {
  447. modifyFunction(appMetadata);
  448. using (FileStream stream = File.Create(metadataFile, 4096, FileOptions.WriteThrough))
  449. {
  450. JsonHelper.Serialize(stream, appMetadata, true);
  451. }
  452. }
  453. return appMetadata;
  454. }
  455. public byte[] GetApplicationIcon(string applicationPath)
  456. {
  457. byte[] applicationIcon = null;
  458. try
  459. {
  460. // Look for icon only if applicationPath is not a directory
  461. if (!Directory.Exists(applicationPath))
  462. {
  463. string extension = Path.GetExtension(applicationPath).ToLower();
  464. using (FileStream file = new FileStream(applicationPath, FileMode.Open, FileAccess.Read))
  465. {
  466. if (extension == ".nsp" || extension == ".pfs0" || extension == ".xci")
  467. {
  468. try
  469. {
  470. PartitionFileSystem pfs;
  471. bool isExeFs = false;
  472. if (extension == ".xci")
  473. {
  474. Xci xci = new(_virtualFileSystem.KeySet, file.AsStorage());
  475. pfs = xci.OpenPartition(XciPartitionType.Secure);
  476. }
  477. else
  478. {
  479. pfs = new PartitionFileSystem(file.AsStorage());
  480. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*"))
  481. {
  482. if (Path.GetFileNameWithoutExtension(fileEntry.FullPath) == "main")
  483. {
  484. isExeFs = true;
  485. }
  486. }
  487. }
  488. if (isExeFs)
  489. {
  490. applicationIcon = _nspIcon;
  491. }
  492. else
  493. {
  494. // Store the ControlFS in variable called controlFs
  495. GetControlFsAndTitleId(pfs, out IFileSystem controlFs, out _);
  496. // Read the icon from the ControlFS and store it as a byte array
  497. try
  498. {
  499. using var icon = new UniqueRef<IFile>();
  500. controlFs.OpenFile(ref icon.Ref(), $"/icon_{_desiredTitleLanguage}.dat".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  501. using (MemoryStream stream = new MemoryStream())
  502. {
  503. icon.Get.AsStream().CopyTo(stream);
  504. applicationIcon = stream.ToArray();
  505. }
  506. }
  507. catch (HorizonResultException)
  508. {
  509. foreach (DirectoryEntryEx entry in controlFs.EnumerateEntries("/", "*"))
  510. {
  511. if (entry.Name == "control.nacp")
  512. {
  513. continue;
  514. }
  515. using var icon = new UniqueRef<IFile>();
  516. controlFs.OpenFile(ref icon.Ref(), entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  517. using (MemoryStream stream = new MemoryStream())
  518. {
  519. icon.Get.AsStream().CopyTo(stream);
  520. applicationIcon = stream.ToArray();
  521. }
  522. if (applicationIcon != null)
  523. {
  524. break;
  525. }
  526. }
  527. if (applicationIcon == null)
  528. {
  529. applicationIcon = extension == ".xci" ? _xciIcon : _nspIcon;
  530. }
  531. }
  532. }
  533. }
  534. catch (MissingKeyException)
  535. {
  536. applicationIcon = extension == ".xci"
  537. ? _xciIcon
  538. : _nspIcon;
  539. }
  540. catch (InvalidDataException)
  541. {
  542. applicationIcon = extension == ".xci"
  543. ? _xciIcon
  544. : _nspIcon;
  545. }
  546. catch (Exception exception)
  547. {
  548. Logger.Warning?.Print(LogClass.Application,
  549. $"The file encountered was not of a valid type. File: '{applicationPath}' Error: {exception}");
  550. }
  551. }
  552. else if (extension == ".nro")
  553. {
  554. BinaryReader reader = new(file);
  555. byte[] Read(long position, int size)
  556. {
  557. file.Seek(position, SeekOrigin.Begin);
  558. return reader.ReadBytes(size);
  559. }
  560. try
  561. {
  562. file.Seek(24, SeekOrigin.Begin);
  563. int assetOffset = reader.ReadInt32();
  564. if (Encoding.ASCII.GetString(Read(assetOffset, 4)) == "ASET")
  565. {
  566. byte[] iconSectionInfo = Read(assetOffset + 8, 0x10);
  567. long iconOffset = BitConverter.ToInt64(iconSectionInfo, 0);
  568. long iconSize = BitConverter.ToInt64(iconSectionInfo, 8);
  569. // Reads and stores game icon as byte array
  570. applicationIcon = Read(assetOffset + iconOffset, (int)iconSize);
  571. }
  572. else
  573. {
  574. applicationIcon = _nroIcon;
  575. }
  576. }
  577. catch
  578. {
  579. Logger.Warning?.Print(LogClass.Application,
  580. $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  581. }
  582. }
  583. else if (extension == ".nca")
  584. {
  585. applicationIcon = _ncaIcon;
  586. }
  587. // If its an NSO we just set defaults
  588. else if (extension == ".nso")
  589. {
  590. applicationIcon = _nsoIcon;
  591. }
  592. }
  593. }
  594. }
  595. catch(Exception)
  596. {
  597. Logger.Warning?.Print(LogClass.Application,
  598. $"Could not retrieve a valid icon for the app. Default icon will be used. Errored File: {applicationPath}");
  599. }
  600. return applicationIcon ?? _ncaIcon;
  601. }
  602. private string ConvertSecondsToReadableString(double seconds)
  603. {
  604. const int secondsPerMinute = 60;
  605. const int secondsPerHour = secondsPerMinute * 60;
  606. const int secondsPerDay = secondsPerHour * 24;
  607. string readableString;
  608. if (seconds < secondsPerMinute)
  609. {
  610. readableString = $"{seconds}s";
  611. }
  612. else if (seconds < secondsPerHour)
  613. {
  614. readableString = $"{Math.Round(seconds / secondsPerMinute, 2, MidpointRounding.AwayFromZero)} mins";
  615. }
  616. else if (seconds < secondsPerDay)
  617. {
  618. readableString = $"{Math.Round(seconds / secondsPerHour, 2, MidpointRounding.AwayFromZero)} hrs";
  619. }
  620. else
  621. {
  622. readableString = $"{Math.Round(seconds / secondsPerDay, 2, MidpointRounding.AwayFromZero)} days";
  623. }
  624. return readableString;
  625. }
  626. private void GetGameInformation(ref ApplicationControlProperty controlData, out string titleName, out string titleId, out string publisher, out string version)
  627. {
  628. _ = Enum.TryParse(_desiredTitleLanguage.ToString(), out TitleLanguage desiredTitleLanguage);
  629. if (controlData.Title.ItemsRo.Length > (int)desiredTitleLanguage)
  630. {
  631. titleName = controlData.Title[(int)desiredTitleLanguage].NameString.ToString();
  632. publisher = controlData.Title[(int)desiredTitleLanguage].PublisherString.ToString();
  633. }
  634. else
  635. {
  636. titleName = null;
  637. publisher = null;
  638. }
  639. if (string.IsNullOrWhiteSpace(titleName))
  640. {
  641. foreach (ref readonly var controlTitle in controlData.Title.ItemsRo)
  642. {
  643. if (!controlTitle.NameString.IsEmpty())
  644. {
  645. titleName = controlTitle.NameString.ToString();
  646. break;
  647. }
  648. }
  649. }
  650. if (string.IsNullOrWhiteSpace(publisher))
  651. {
  652. foreach (ref readonly var controlTitle in controlData.Title.ItemsRo)
  653. {
  654. if (!controlTitle.PublisherString.IsEmpty())
  655. {
  656. publisher = controlTitle.PublisherString.ToString();
  657. break;
  658. }
  659. }
  660. }
  661. if (controlData.PresenceGroupId != 0)
  662. {
  663. titleId = controlData.PresenceGroupId.ToString("x16");
  664. }
  665. else if (controlData.SaveDataOwnerId != 0)
  666. {
  667. titleId = controlData.SaveDataOwnerId.ToString();
  668. }
  669. else if (controlData.AddOnContentBaseId != 0)
  670. {
  671. titleId = (controlData.AddOnContentBaseId - 0x1000).ToString("x16");
  672. }
  673. else
  674. {
  675. titleId = "0000000000000000";
  676. }
  677. version = controlData.DisplayVersionString.ToString();
  678. }
  679. private bool IsUpdateApplied(string titleId, out IFileSystem updatedControlFs)
  680. {
  681. updatedControlFs = null;
  682. string updatePath = "(unknown)";
  683. try
  684. {
  685. (Nca patchNca, Nca controlNca) = ApplicationLoader.GetGameUpdateData(_virtualFileSystem, titleId, 0, out updatePath);
  686. if (patchNca != null && controlNca != null)
  687. {
  688. updatedControlFs = controlNca?.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
  689. return true;
  690. }
  691. }
  692. catch (InvalidDataException)
  693. {
  694. Logger.Warning?.Print(LogClass.Application,
  695. $"The header key is incorrect or missing and therefore the NCA header content type check has failed. Errored File: {updatePath}");
  696. }
  697. catch (MissingKeyException exception)
  698. {
  699. Logger.Warning?.Print(LogClass.Application, $"Your key set is missing a key with the name: {exception.Name}. Errored File: {updatePath}");
  700. }
  701. return false;
  702. }
  703. }
  704. }