ApplicationLibrary.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  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. if (appMetadata.LastPlayedOld == default || appMetadata.LastPlayed.HasValue)
  336. {
  337. // Don't do the migration if last_played doesn't exist or last_played_utc already has a value.
  338. return;
  339. }
  340. // Migrate from string-based last_played to DateTime-based last_played_utc.
  341. if (DateTime.TryParse(appMetadata.LastPlayedOld, out DateTime lastPlayedOldParsed))
  342. {
  343. Logger.Info?.Print(LogClass.Application, $"last_played found: \"{appMetadata.LastPlayedOld}\", migrating to last_played_utc");
  344. appMetadata.LastPlayed = lastPlayedOldParsed;
  345. // Migration successful: deleting last_played from the metadata file.
  346. appMetadata.LastPlayedOld = default;
  347. }
  348. else
  349. {
  350. // Migration failed: emitting warning but leaving the unparsable value in the metadata file so the user can fix it.
  351. Logger.Warning?.Print(LogClass.Application, $"Last played string \"{appMetadata.LastPlayedOld}\" is invalid for current system culture, skipping (did current culture change?)");
  352. }
  353. });
  354. ApplicationData data = new()
  355. {
  356. Favorite = appMetadata.Favorite,
  357. Icon = applicationIcon,
  358. TitleName = titleName,
  359. TitleId = titleId,
  360. Developer = developer,
  361. Version = version,
  362. TimePlayed = ConvertSecondsToFormattedString(appMetadata.TimePlayed),
  363. TimePlayedNum = appMetadata.TimePlayed,
  364. LastPlayed = appMetadata.LastPlayed,
  365. FileExtension = Path.GetExtension(applicationPath).ToUpper().Remove(0, 1),
  366. FileSize = (fileSize < 1) ? (fileSize * 1024).ToString("0.##") + " MiB" : fileSize.ToString("0.##") + " GiB",
  367. FileSizeBytes = fileSize,
  368. Path = applicationPath,
  369. ControlHolder = controlHolder
  370. };
  371. numApplicationsLoaded++;
  372. OnApplicationAdded(new ApplicationAddedEventArgs()
  373. {
  374. AppData = data
  375. });
  376. OnApplicationCountUpdated(new ApplicationCountUpdatedEventArgs()
  377. {
  378. NumAppsFound = numApplicationsFound,
  379. NumAppsLoaded = numApplicationsLoaded
  380. });
  381. }
  382. OnApplicationCountUpdated(new ApplicationCountUpdatedEventArgs()
  383. {
  384. NumAppsFound = numApplicationsFound,
  385. NumAppsLoaded = numApplicationsLoaded
  386. });
  387. }
  388. finally
  389. {
  390. _cancellationToken.Dispose();
  391. _cancellationToken = null;
  392. }
  393. }
  394. protected void OnApplicationAdded(ApplicationAddedEventArgs e)
  395. {
  396. ApplicationAdded?.Invoke(null, e);
  397. }
  398. protected void OnApplicationCountUpdated(ApplicationCountUpdatedEventArgs e)
  399. {
  400. ApplicationCountUpdated?.Invoke(null, e);
  401. }
  402. private void GetControlFsAndTitleId(PartitionFileSystem pfs, out IFileSystem controlFs, out string titleId)
  403. {
  404. (_, _, Nca controlNca) = GetGameData(_virtualFileSystem, pfs, 0);
  405. // Return the ControlFS
  406. controlFs = controlNca?.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
  407. titleId = controlNca?.Header.TitleId.ToString("x16");
  408. }
  409. public ApplicationMetadata LoadAndSaveMetaData(string titleId, Action<ApplicationMetadata> modifyFunction = null)
  410. {
  411. string metadataFolder = Path.Combine(AppDataManager.GamesDirPath, titleId, "gui");
  412. string metadataFile = Path.Combine(metadataFolder, "metadata.json");
  413. ApplicationMetadata appMetadata;
  414. if (!File.Exists(metadataFile))
  415. {
  416. Directory.CreateDirectory(metadataFolder);
  417. appMetadata = new ApplicationMetadata();
  418. JsonHelper.SerializeToFile(metadataFile, appMetadata, SerializerContext.ApplicationMetadata);
  419. }
  420. try
  421. {
  422. appMetadata = JsonHelper.DeserializeFromFile(metadataFile, SerializerContext.ApplicationMetadata);
  423. }
  424. catch (JsonException)
  425. {
  426. Logger.Warning?.Print(LogClass.Application, $"Failed to parse metadata json for {titleId}. Loading defaults.");
  427. appMetadata = new ApplicationMetadata();
  428. }
  429. if (modifyFunction != null)
  430. {
  431. modifyFunction(appMetadata);
  432. JsonHelper.SerializeToFile(metadataFile, appMetadata, SerializerContext.ApplicationMetadata);
  433. }
  434. return appMetadata;
  435. }
  436. public byte[] GetApplicationIcon(string applicationPath)
  437. {
  438. byte[] applicationIcon = null;
  439. try
  440. {
  441. // Look for icon only if applicationPath is not a directory
  442. if (!Directory.Exists(applicationPath))
  443. {
  444. string extension = Path.GetExtension(applicationPath).ToLower();
  445. using FileStream file = new(applicationPath, FileMode.Open, FileAccess.Read);
  446. if (extension == ".nsp" || extension == ".pfs0" || extension == ".xci")
  447. {
  448. try
  449. {
  450. PartitionFileSystem pfs;
  451. bool isExeFs = false;
  452. if (extension == ".xci")
  453. {
  454. Xci xci = new(_virtualFileSystem.KeySet, file.AsStorage());
  455. pfs = xci.OpenPartition(XciPartitionType.Secure);
  456. }
  457. else
  458. {
  459. pfs = new PartitionFileSystem(file.AsStorage());
  460. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*"))
  461. {
  462. if (Path.GetFileNameWithoutExtension(fileEntry.FullPath) == "main")
  463. {
  464. isExeFs = true;
  465. }
  466. }
  467. }
  468. if (isExeFs)
  469. {
  470. applicationIcon = _nspIcon;
  471. }
  472. else
  473. {
  474. // Store the ControlFS in variable called controlFs
  475. GetControlFsAndTitleId(pfs, out IFileSystem controlFs, out _);
  476. // Read the icon from the ControlFS and store it as a byte array
  477. try
  478. {
  479. using var icon = new UniqueRef<IFile>();
  480. controlFs.OpenFile(ref icon.Ref, $"/icon_{_desiredTitleLanguage}.dat".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  481. using MemoryStream stream = new();
  482. icon.Get.AsStream().CopyTo(stream);
  483. applicationIcon = stream.ToArray();
  484. }
  485. catch (HorizonResultException)
  486. {
  487. foreach (DirectoryEntryEx entry in controlFs.EnumerateEntries("/", "*"))
  488. {
  489. if (entry.Name == "control.nacp")
  490. {
  491. continue;
  492. }
  493. using var icon = new UniqueRef<IFile>();
  494. controlFs.OpenFile(ref icon.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  495. using (MemoryStream stream = new())
  496. {
  497. icon.Get.AsStream().CopyTo(stream);
  498. applicationIcon = stream.ToArray();
  499. }
  500. if (applicationIcon != null)
  501. {
  502. break;
  503. }
  504. }
  505. applicationIcon ??= extension == ".xci" ? _xciIcon : _nspIcon;
  506. }
  507. }
  508. }
  509. catch (MissingKeyException)
  510. {
  511. applicationIcon = extension == ".xci" ? _xciIcon : _nspIcon;
  512. }
  513. catch (InvalidDataException)
  514. {
  515. applicationIcon = extension == ".xci" ? _xciIcon : _nspIcon;
  516. }
  517. catch (Exception exception)
  518. {
  519. Logger.Warning?.Print(LogClass.Application, $"The file encountered was not of a valid type. File: '{applicationPath}' Error: {exception}");
  520. }
  521. }
  522. else if (extension == ".nro")
  523. {
  524. BinaryReader reader = new(file);
  525. byte[] Read(long position, int size)
  526. {
  527. file.Seek(position, SeekOrigin.Begin);
  528. return reader.ReadBytes(size);
  529. }
  530. try
  531. {
  532. file.Seek(24, SeekOrigin.Begin);
  533. int assetOffset = reader.ReadInt32();
  534. if (Encoding.ASCII.GetString(Read(assetOffset, 4)) == "ASET")
  535. {
  536. byte[] iconSectionInfo = Read(assetOffset + 8, 0x10);
  537. long iconOffset = BitConverter.ToInt64(iconSectionInfo, 0);
  538. long iconSize = BitConverter.ToInt64(iconSectionInfo, 8);
  539. // Reads and stores game icon as byte array
  540. applicationIcon = Read(assetOffset + iconOffset, (int)iconSize);
  541. }
  542. else
  543. {
  544. applicationIcon = _nroIcon;
  545. }
  546. }
  547. catch
  548. {
  549. Logger.Warning?.Print(LogClass.Application, $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  550. }
  551. }
  552. else if (extension == ".nca")
  553. {
  554. applicationIcon = _ncaIcon;
  555. }
  556. // If its an NSO we just set defaults
  557. else if (extension == ".nso")
  558. {
  559. applicationIcon = _nsoIcon;
  560. }
  561. }
  562. }
  563. catch(Exception)
  564. {
  565. Logger.Warning?.Print(LogClass.Application, $"Could not retrieve a valid icon for the app. Default icon will be used. Errored File: {applicationPath}");
  566. }
  567. return applicationIcon ?? _ncaIcon;
  568. }
  569. private static string ConvertSecondsToFormattedString(double seconds)
  570. {
  571. System.TimeSpan time = System.TimeSpan.FromSeconds(seconds);
  572. string timeString;
  573. if (time.Days != 0)
  574. {
  575. timeString = $"{time.Days}d {time.Hours:D2}h {time.Minutes:D2}m";
  576. }
  577. else if (time.Hours != 0)
  578. {
  579. timeString = $"{time.Hours:D2}h {time.Minutes:D2}m";
  580. }
  581. else if (time.Minutes != 0)
  582. {
  583. timeString = $"{time.Minutes:D2}m";
  584. }
  585. else
  586. {
  587. timeString = "Never";
  588. }
  589. return timeString;
  590. }
  591. private void GetGameInformation(ref ApplicationControlProperty controlData, out string titleName, out string titleId, out string publisher, out string version)
  592. {
  593. _ = Enum.TryParse(_desiredTitleLanguage.ToString(), out TitleLanguage desiredTitleLanguage);
  594. if (controlData.Title.ItemsRo.Length > (int)desiredTitleLanguage)
  595. {
  596. titleName = controlData.Title[(int)desiredTitleLanguage].NameString.ToString();
  597. publisher = controlData.Title[(int)desiredTitleLanguage].PublisherString.ToString();
  598. }
  599. else
  600. {
  601. titleName = null;
  602. publisher = null;
  603. }
  604. if (string.IsNullOrWhiteSpace(titleName))
  605. {
  606. foreach (ref readonly var controlTitle in controlData.Title.ItemsRo)
  607. {
  608. if (!controlTitle.NameString.IsEmpty())
  609. {
  610. titleName = controlTitle.NameString.ToString();
  611. break;
  612. }
  613. }
  614. }
  615. if (string.IsNullOrWhiteSpace(publisher))
  616. {
  617. foreach (ref readonly var controlTitle in controlData.Title.ItemsRo)
  618. {
  619. if (!controlTitle.PublisherString.IsEmpty())
  620. {
  621. publisher = controlTitle.PublisherString.ToString();
  622. break;
  623. }
  624. }
  625. }
  626. if (controlData.PresenceGroupId != 0)
  627. {
  628. titleId = controlData.PresenceGroupId.ToString("x16");
  629. }
  630. else if (controlData.SaveDataOwnerId != 0)
  631. {
  632. titleId = controlData.SaveDataOwnerId.ToString();
  633. }
  634. else if (controlData.AddOnContentBaseId != 0)
  635. {
  636. titleId = (controlData.AddOnContentBaseId - 0x1000).ToString("x16");
  637. }
  638. else
  639. {
  640. titleId = "0000000000000000";
  641. }
  642. version = controlData.DisplayVersionString.ToString();
  643. }
  644. private bool IsUpdateApplied(string titleId, out IFileSystem updatedControlFs)
  645. {
  646. updatedControlFs = null;
  647. string updatePath = "(unknown)";
  648. try
  649. {
  650. (Nca patchNca, Nca controlNca) = GetGameUpdateData(_virtualFileSystem, titleId, 0, out updatePath);
  651. if (patchNca != null && controlNca != null)
  652. {
  653. updatedControlFs = controlNca?.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
  654. return true;
  655. }
  656. }
  657. catch (InvalidDataException)
  658. {
  659. 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}");
  660. }
  661. catch (MissingKeyException exception)
  662. {
  663. Logger.Warning?.Print(LogClass.Application, $"Your key set is missing a key with the name: {exception.Name}. Errored File: {updatePath}");
  664. }
  665. return false;
  666. }
  667. public static (Nca main, Nca patch, Nca control) GetGameData(VirtualFileSystem fileSystem, PartitionFileSystem pfs, int programIndex)
  668. {
  669. Nca mainNca = null;
  670. Nca patchNca = null;
  671. Nca controlNca = null;
  672. fileSystem.ImportTickets(pfs);
  673. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  674. {
  675. using var ncaFile = new UniqueRef<IFile>();
  676. pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  677. Nca nca = new Nca(fileSystem.KeySet, ncaFile.Release().AsStorage());
  678. int ncaProgramIndex = (int)(nca.Header.TitleId & 0xF);
  679. if (ncaProgramIndex != programIndex)
  680. {
  681. continue;
  682. }
  683. if (nca.Header.ContentType == NcaContentType.Program)
  684. {
  685. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  686. if (nca.SectionExists(NcaSectionType.Data) && nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  687. {
  688. patchNca = nca;
  689. }
  690. else
  691. {
  692. mainNca = nca;
  693. }
  694. }
  695. else if (nca.Header.ContentType == NcaContentType.Control)
  696. {
  697. controlNca = nca;
  698. }
  699. }
  700. return (mainNca, patchNca, controlNca);
  701. }
  702. public static (Nca patch, Nca control) GetGameUpdateDataFromPartition(VirtualFileSystem fileSystem, PartitionFileSystem pfs, string titleId, int programIndex)
  703. {
  704. Nca patchNca = null;
  705. Nca controlNca = null;
  706. fileSystem.ImportTickets(pfs);
  707. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  708. {
  709. using var ncaFile = new UniqueRef<IFile>();
  710. pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  711. Nca nca = new Nca(fileSystem.KeySet, ncaFile.Release().AsStorage());
  712. int ncaProgramIndex = (int)(nca.Header.TitleId & 0xF);
  713. if (ncaProgramIndex != programIndex)
  714. {
  715. continue;
  716. }
  717. if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != titleId)
  718. {
  719. break;
  720. }
  721. if (nca.Header.ContentType == NcaContentType.Program)
  722. {
  723. patchNca = nca;
  724. }
  725. else if (nca.Header.ContentType == NcaContentType.Control)
  726. {
  727. controlNca = nca;
  728. }
  729. }
  730. return (patchNca, controlNca);
  731. }
  732. public static (Nca patch, Nca control) GetGameUpdateData(VirtualFileSystem fileSystem, string titleId, int programIndex, out string updatePath)
  733. {
  734. updatePath = null;
  735. if (ulong.TryParse(titleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdBase))
  736. {
  737. // Clear the program index part.
  738. titleIdBase &= ~0xFUL;
  739. // Load update information if exists.
  740. string titleUpdateMetadataPath = Path.Combine(AppDataManager.GamesDirPath, titleIdBase.ToString("x16"), "updates.json");
  741. if (File.Exists(titleUpdateMetadataPath))
  742. {
  743. updatePath = JsonHelper.DeserializeFromFile(titleUpdateMetadataPath, TitleSerializerContext.TitleUpdateMetadata).Selected;
  744. if (File.Exists(updatePath))
  745. {
  746. FileStream file = new FileStream(updatePath, FileMode.Open, FileAccess.Read);
  747. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  748. return GetGameUpdateDataFromPartition(fileSystem, nsp, titleIdBase.ToString("x16"), programIndex);
  749. }
  750. }
  751. }
  752. return (null, null);
  753. }
  754. }
  755. }