ApplicationLibrary.cs 34 KB

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