ApplicationLibrary.cs 34 KB

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