ApplicationLibrary.cs 39 KB

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