ApplicationLibrary.cs 37 KB

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