ApplicationLibrary.cs 40 KB

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