ApplicationLibrary.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. using JsonPrettyPrinterPlus;
  2. using LibHac;
  3. using LibHac.Common;
  4. using LibHac.Fs;
  5. using LibHac.Fs.Shim;
  6. using LibHac.FsSystem;
  7. using LibHac.FsSystem.NcaUtils;
  8. using LibHac.Ncm;
  9. using LibHac.Spl;
  10. using Ryujinx.Common.Logging;
  11. using Ryujinx.Configuration.System;
  12. using Ryujinx.HLE.FileSystem;
  13. using Ryujinx.HLE.Loaders.Npdm;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Globalization;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Reflection;
  20. using System.Text;
  21. using Utf8Json;
  22. using Utf8Json.Resolvers;
  23. using RightsId = LibHac.Fs.RightsId;
  24. namespace Ryujinx.Ui
  25. {
  26. public class ApplicationLibrary
  27. {
  28. public static event EventHandler<ApplicationAddedEventArgs> ApplicationAdded;
  29. public static event EventHandler<ApplicationCountUpdatedEventArgs> ApplicationCountUpdated;
  30. private static readonly byte[] _nspIcon = GetResourceBytes("Ryujinx.Ui.assets.NSPIcon.png");
  31. private static readonly byte[] _xciIcon = GetResourceBytes("Ryujinx.Ui.assets.XCIIcon.png");
  32. private static readonly byte[] _ncaIcon = GetResourceBytes("Ryujinx.Ui.assets.NCAIcon.png");
  33. private static readonly byte[] _nroIcon = GetResourceBytes("Ryujinx.Ui.assets.NROIcon.png");
  34. private static readonly byte[] _nsoIcon = GetResourceBytes("Ryujinx.Ui.assets.NSOIcon.png");
  35. private static VirtualFileSystem _virtualFileSystem;
  36. private static Language _desiredTitleLanguage;
  37. private static bool _loadingError;
  38. public static IEnumerable<string> GetFilesInDirectory(string directory)
  39. {
  40. Stack<string> stack = new Stack<string>();
  41. stack.Push(directory);
  42. while (stack.Count > 0)
  43. {
  44. string dir = stack.Pop();
  45. string[] content = { };
  46. try
  47. {
  48. content = Directory.GetFiles(dir, "*");
  49. }
  50. catch (UnauthorizedAccessException)
  51. {
  52. Logger.PrintWarning(LogClass.Application, $"Failed to get access to directory: \"{dir}\"");
  53. }
  54. if (content.Length > 0)
  55. {
  56. foreach (string file in content)
  57. yield return file;
  58. }
  59. try
  60. {
  61. content = Directory.GetDirectories(dir);
  62. }
  63. catch (UnauthorizedAccessException)
  64. {
  65. Logger.PrintWarning(LogClass.Application, $"Failed to get access to directory: \"{dir}\"");
  66. }
  67. if (content.Length > 0)
  68. {
  69. foreach (string subdir in content)
  70. stack.Push(subdir);
  71. }
  72. }
  73. }
  74. public static void LoadApplications(List<string> appDirs, VirtualFileSystem virtualFileSystem, Language desiredTitleLanguage)
  75. {
  76. int numApplicationsFound = 0;
  77. int numApplicationsLoaded = 0;
  78. _loadingError = false;
  79. _virtualFileSystem = virtualFileSystem;
  80. _desiredTitleLanguage = desiredTitleLanguage;
  81. // Builds the applications list with paths to found applications
  82. List<string> applications = new List<string>();
  83. foreach (string appDir in appDirs)
  84. {
  85. if (!Directory.Exists(appDir))
  86. {
  87. Logger.PrintWarning(LogClass.Application, $"The \"game_dirs\" section in \"Config.json\" contains an invalid directory: \"{appDir}\"");
  88. continue;
  89. }
  90. foreach (string app in GetFilesInDirectory(appDir))
  91. {
  92. if ((Path.GetExtension(app).ToLower() == ".nsp") ||
  93. (Path.GetExtension(app).ToLower() == ".pfs0") ||
  94. (Path.GetExtension(app).ToLower() == ".xci") ||
  95. (Path.GetExtension(app).ToLower() == ".nca") ||
  96. (Path.GetExtension(app).ToLower() == ".nro") ||
  97. (Path.GetExtension(app).ToLower() == ".nso"))
  98. {
  99. applications.Add(app);
  100. numApplicationsFound++;
  101. }
  102. }
  103. }
  104. // Loops through applications list, creating a struct and then firing an event containing the struct for each application
  105. foreach (string applicationPath in applications)
  106. {
  107. double fileSize = new FileInfo(applicationPath).Length * 0.000000000931;
  108. string titleName = "Unknown";
  109. string titleId = "0000000000000000";
  110. string developer = "Unknown";
  111. string version = "0";
  112. string saveDataPath = null;
  113. byte[] applicationIcon = null;
  114. try
  115. {
  116. using (FileStream file = new FileStream(applicationPath, FileMode.Open, FileAccess.Read))
  117. {
  118. if ((Path.GetExtension(applicationPath).ToLower() == ".nsp") ||
  119. (Path.GetExtension(applicationPath).ToLower() == ".pfs0") ||
  120. (Path.GetExtension(applicationPath).ToLower() == ".xci"))
  121. {
  122. try
  123. {
  124. PartitionFileSystem pfs;
  125. bool isExeFs = false;
  126. if (Path.GetExtension(applicationPath).ToLower() == ".xci")
  127. {
  128. Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage());
  129. pfs = xci.OpenPartition(XciPartitionType.Secure);
  130. }
  131. else
  132. {
  133. pfs = new PartitionFileSystem(file.AsStorage());
  134. // If the NSP doesn't have a main NCA, decrement the number of applications found and then continue to the next application.
  135. bool hasMainNca = false;
  136. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*"))
  137. {
  138. if (Path.GetExtension(fileEntry.FullPath).ToLower() == ".nca")
  139. {
  140. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  141. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  142. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  143. if (nca.Header.ContentType == NcaContentType.Program && !nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  144. {
  145. hasMainNca = true;
  146. break;
  147. }
  148. }
  149. else if (Path.GetFileNameWithoutExtension(fileEntry.FullPath) == "main")
  150. {
  151. isExeFs = true;
  152. }
  153. }
  154. if (!hasMainNca && !isExeFs)
  155. {
  156. numApplicationsFound--;
  157. continue;
  158. }
  159. }
  160. if (isExeFs)
  161. {
  162. applicationIcon = _nspIcon;
  163. Result result = pfs.OpenFile(out IFile npdmFile, "/main.npdm".ToU8Span(), OpenMode.Read);
  164. if (ResultFs.PathNotFound.Includes(result))
  165. {
  166. Npdm npdm = new Npdm(npdmFile.AsStream());
  167. titleName = npdm.TitleName;
  168. titleId = npdm.Aci0.TitleId.ToString("x16");
  169. }
  170. }
  171. else
  172. {
  173. // Store the ControlFS in variable called controlFs
  174. GetControlFsAndTitleId(pfs, out IFileSystem controlFs, out titleId);
  175. // Creates NACP class from the NACP file
  176. controlFs.OpenFile(out IFile controlNacpFile, "/control.nacp".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  177. Nacp controlData = new Nacp(controlNacpFile.AsStream());
  178. // Get the title name, title ID, developer name and version number from the NACP
  179. version = controlData.DisplayVersion;
  180. GetNameIdDeveloper(controlData, out titleName, out _, out developer);
  181. // Read the icon from the ControlFS and store it as a byte array
  182. try
  183. {
  184. controlFs.OpenFile(out IFile icon, $"/icon_{_desiredTitleLanguage}.dat".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  185. using (MemoryStream stream = new MemoryStream())
  186. {
  187. icon.AsStream().CopyTo(stream);
  188. applicationIcon = stream.ToArray();
  189. }
  190. }
  191. catch (HorizonResultException)
  192. {
  193. foreach (DirectoryEntryEx entry in controlFs.EnumerateEntries("/", "*"))
  194. {
  195. if (entry.Name == "control.nacp")
  196. {
  197. continue;
  198. }
  199. controlFs.OpenFile(out IFile icon, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  200. using (MemoryStream stream = new MemoryStream())
  201. {
  202. icon.AsStream().CopyTo(stream);
  203. applicationIcon = stream.ToArray();
  204. }
  205. if (applicationIcon != null)
  206. {
  207. break;
  208. }
  209. }
  210. if (applicationIcon == null)
  211. {
  212. applicationIcon = Path.GetExtension(applicationPath).ToLower() == ".xci" ? _xciIcon : _nspIcon;
  213. }
  214. }
  215. }
  216. }
  217. catch (MissingKeyException exception)
  218. {
  219. applicationIcon = Path.GetExtension(applicationPath).ToLower() == ".xci" ? _xciIcon : _nspIcon;
  220. Logger.PrintWarning(LogClass.Application, $"Your key set is missing a key with the name: {exception.Name}");
  221. }
  222. catch (InvalidDataException)
  223. {
  224. applicationIcon = Path.GetExtension(applicationPath).ToLower() == ".xci" ? _xciIcon : _nspIcon;
  225. Logger.PrintWarning(LogClass.Application, $"The header key is incorrect or missing and therefore the NCA header content type check has failed. Errored File: {applicationPath}");
  226. }
  227. catch (Exception exception)
  228. {
  229. Logger.PrintWarning(LogClass.Application, $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  230. Logger.PrintDebug(LogClass.Application, exception.ToString());
  231. numApplicationsFound--;
  232. _loadingError = true;
  233. continue;
  234. }
  235. }
  236. else if (Path.GetExtension(applicationPath).ToLower() == ".nro")
  237. {
  238. BinaryReader reader = new BinaryReader(file);
  239. byte[] Read(long position, int size)
  240. {
  241. file.Seek(position, SeekOrigin.Begin);
  242. return reader.ReadBytes(size);
  243. }
  244. try
  245. {
  246. file.Seek(24, SeekOrigin.Begin);
  247. int assetOffset = reader.ReadInt32();
  248. if (Encoding.ASCII.GetString(Read(assetOffset, 4)) == "ASET")
  249. {
  250. byte[] iconSectionInfo = Read(assetOffset + 8, 0x10);
  251. long iconOffset = BitConverter.ToInt64(iconSectionInfo, 0);
  252. long iconSize = BitConverter.ToInt64(iconSectionInfo, 8);
  253. ulong nacpOffset = reader.ReadUInt64();
  254. ulong nacpSize = reader.ReadUInt64();
  255. // Reads and stores game icon as byte array
  256. applicationIcon = Read(assetOffset + iconOffset, (int) iconSize);
  257. // Creates memory stream out of byte array which is the NACP
  258. using (MemoryStream stream = new MemoryStream(Read(assetOffset + (int) nacpOffset, (int) nacpSize)))
  259. {
  260. // Creates NACP class from the memory stream
  261. Nacp controlData = new Nacp(stream);
  262. // Get the title name, title ID, developer name and version number from the NACP
  263. version = controlData.DisplayVersion;
  264. GetNameIdDeveloper(controlData, out titleName, out titleId, out developer);
  265. }
  266. }
  267. else
  268. {
  269. applicationIcon = _nroIcon;
  270. titleName = Path.GetFileNameWithoutExtension(applicationPath);
  271. }
  272. }
  273. catch
  274. {
  275. Logger.PrintWarning(LogClass.Application, $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  276. numApplicationsFound--;
  277. continue;
  278. }
  279. }
  280. else if (Path.GetExtension(applicationPath).ToLower() == ".nca")
  281. {
  282. try
  283. {
  284. Nca nca = new Nca(_virtualFileSystem.KeySet, new FileStream(applicationPath, FileMode.Open, FileAccess.Read).AsStorage());
  285. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  286. if (nca.Header.ContentType != NcaContentType.Program || nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  287. {
  288. numApplicationsFound--;
  289. continue;
  290. }
  291. }
  292. catch (InvalidDataException)
  293. {
  294. Logger.PrintWarning(LogClass.Application, $"The NCA header content type check has failed. This is usually because the header key is incorrect or missing. Errored File: {applicationPath}");
  295. }
  296. catch
  297. {
  298. Logger.PrintWarning(LogClass.Application, $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  299. numApplicationsFound--;
  300. _loadingError = true;
  301. continue;
  302. }
  303. applicationIcon = _ncaIcon;
  304. titleName = Path.GetFileNameWithoutExtension(applicationPath);
  305. }
  306. // If its an NSO we just set defaults
  307. else if (Path.GetExtension(applicationPath).ToLower() == ".nso")
  308. {
  309. applicationIcon = _nsoIcon;
  310. titleName = Path.GetFileNameWithoutExtension(applicationPath);
  311. }
  312. }
  313. }
  314. catch (IOException exception)
  315. {
  316. Logger.PrintWarning(LogClass.Application, exception.Message);
  317. numApplicationsFound--;
  318. _loadingError = true;
  319. continue;
  320. }
  321. ApplicationMetadata appMetadata = LoadAndSaveMetaData(titleId);
  322. if (ulong.TryParse(titleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdNum))
  323. {
  324. SaveDataFilter filter = new SaveDataFilter();
  325. filter.SetUserId(new UserId(1, 0));
  326. filter.SetProgramId(new TitleId(titleIdNum));
  327. Result result = virtualFileSystem.FsClient.FindSaveDataWithFilter(out SaveDataInfo saveDataInfo, SaveDataSpaceId.User, ref filter);
  328. if (result.IsSuccess())
  329. {
  330. saveDataPath = Path.Combine(virtualFileSystem.GetNandPath(), $"user/save/{saveDataInfo.SaveDataId:x16}");
  331. }
  332. }
  333. ApplicationData data = new ApplicationData()
  334. {
  335. Favorite = appMetadata.Favorite,
  336. Icon = applicationIcon,
  337. TitleName = titleName,
  338. TitleId = titleId,
  339. Developer = developer,
  340. Version = version,
  341. TimePlayed = ConvertSecondsToReadableString(appMetadata.TimePlayed),
  342. LastPlayed = appMetadata.LastPlayed,
  343. FileExtension = Path.GetExtension(applicationPath).ToUpper().Remove(0 ,1),
  344. FileSize = (fileSize < 1) ? (fileSize * 1024).ToString("0.##") + "MB" : fileSize.ToString("0.##") + "GB",
  345. Path = applicationPath,
  346. SaveDataPath = saveDataPath
  347. };
  348. numApplicationsLoaded++;
  349. OnApplicationAdded(new ApplicationAddedEventArgs()
  350. {
  351. AppData = data
  352. });
  353. OnApplicationCountUpdated(new ApplicationCountUpdatedEventArgs()
  354. {
  355. NumAppsFound = numApplicationsFound,
  356. NumAppsLoaded = numApplicationsLoaded
  357. });
  358. }
  359. OnApplicationCountUpdated(new ApplicationCountUpdatedEventArgs()
  360. {
  361. NumAppsFound = numApplicationsFound,
  362. NumAppsLoaded = numApplicationsLoaded
  363. });
  364. if (_loadingError)
  365. {
  366. Gtk.Application.Invoke(delegate
  367. {
  368. GtkDialog.CreateErrorDialog("One or more files encountered could not be loaded, check logs for more info.");
  369. });
  370. }
  371. }
  372. protected static void OnApplicationAdded(ApplicationAddedEventArgs e)
  373. {
  374. ApplicationAdded?.Invoke(null, e);
  375. }
  376. protected static void OnApplicationCountUpdated(ApplicationCountUpdatedEventArgs e)
  377. {
  378. ApplicationCountUpdated?.Invoke(null, e);
  379. }
  380. private static byte[] GetResourceBytes(string resourceName)
  381. {
  382. Stream resourceStream = Assembly.GetCallingAssembly().GetManifestResourceStream(resourceName);
  383. byte[] resourceByteArray = new byte[resourceStream.Length];
  384. resourceStream.Read(resourceByteArray);
  385. return resourceByteArray;
  386. }
  387. private static void GetControlFsAndTitleId(PartitionFileSystem pfs, out IFileSystem controlFs, out string titleId)
  388. {
  389. Nca controlNca = null;
  390. // Add keys to key set if needed
  391. foreach (DirectoryEntryEx ticketEntry in pfs.EnumerateEntries("/", "*.tik"))
  392. {
  393. Result result = pfs.OpenFile(out IFile ticketFile, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
  394. if (result.IsSuccess())
  395. {
  396. Ticket ticket = new Ticket(ticketFile.AsStream());
  397. _virtualFileSystem.KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(_virtualFileSystem.KeySet)));
  398. }
  399. }
  400. // Find the Control NCA and store it in variable called controlNca
  401. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  402. {
  403. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  404. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  405. if (nca.Header.ContentType == NcaContentType.Control)
  406. {
  407. controlNca = nca;
  408. }
  409. }
  410. // Return the ControlFS
  411. controlFs = controlNca?.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
  412. titleId = controlNca?.Header.TitleId.ToString("x16");
  413. }
  414. internal static ApplicationMetadata LoadAndSaveMetaData(string titleId, Action<ApplicationMetadata> modifyFunction = null)
  415. {
  416. string metadataFolder = Path.Combine(_virtualFileSystem.GetBasePath(), "games", titleId, "gui");
  417. string metadataFile = Path.Combine(metadataFolder, "metadata.json");
  418. IJsonFormatterResolver resolver = CompositeResolver.Create(new[] { StandardResolver.AllowPrivateSnakeCase });
  419. ApplicationMetadata appMetadata;
  420. if (!File.Exists(metadataFile))
  421. {
  422. Directory.CreateDirectory(metadataFolder);
  423. appMetadata = new ApplicationMetadata
  424. {
  425. Favorite = false,
  426. TimePlayed = 0,
  427. LastPlayed = "Never"
  428. };
  429. byte[] data = JsonSerializer.Serialize(appMetadata, resolver);
  430. File.WriteAllText(metadataFile, Encoding.UTF8.GetString(data, 0, data.Length).PrettyPrintJson());
  431. }
  432. using (Stream stream = File.OpenRead(metadataFile))
  433. {
  434. appMetadata = JsonSerializer.Deserialize<ApplicationMetadata>(stream, resolver);
  435. }
  436. if (modifyFunction != null)
  437. {
  438. modifyFunction(appMetadata);
  439. byte[] saveData = JsonSerializer.Serialize(appMetadata, resolver);
  440. File.WriteAllText(metadataFile, Encoding.UTF8.GetString(saveData, 0, saveData.Length).PrettyPrintJson());
  441. }
  442. return appMetadata;
  443. }
  444. private static string ConvertSecondsToReadableString(double seconds)
  445. {
  446. const int secondsPerMinute = 60;
  447. const int secondsPerHour = secondsPerMinute * 60;
  448. const int secondsPerDay = secondsPerHour * 24;
  449. string readableString;
  450. if (seconds < secondsPerMinute)
  451. {
  452. readableString = $"{seconds}s";
  453. }
  454. else if (seconds < secondsPerHour)
  455. {
  456. readableString = $"{Math.Round(seconds / secondsPerMinute, 2, MidpointRounding.AwayFromZero)} mins";
  457. }
  458. else if (seconds < secondsPerDay)
  459. {
  460. readableString = $"{Math.Round(seconds / secondsPerHour, 2, MidpointRounding.AwayFromZero)} hrs";
  461. }
  462. else
  463. {
  464. readableString = $"{Math.Round(seconds / secondsPerDay, 2, MidpointRounding.AwayFromZero)} days";
  465. }
  466. return readableString;
  467. }
  468. private static void GetNameIdDeveloper(Nacp controlData, out string titleName, out string titleId, out string developer)
  469. {
  470. Enum.TryParse(_desiredTitleLanguage.ToString(), out TitleLanguage desiredTitleLanguage);
  471. NacpDescription nacpDescription = controlData.Descriptions.ToList().Find(x => x.Language == desiredTitleLanguage);
  472. if (nacpDescription != null)
  473. {
  474. titleName = nacpDescription.Title;
  475. developer = nacpDescription.Developer;
  476. }
  477. else
  478. {
  479. titleName = null;
  480. developer = null;
  481. }
  482. if (string.IsNullOrWhiteSpace(titleName))
  483. {
  484. titleName = controlData.Descriptions.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title;
  485. }
  486. if (string.IsNullOrWhiteSpace(developer))
  487. {
  488. developer = controlData.Descriptions.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Developer)).Developer;
  489. }
  490. if (controlData.PresenceGroupId != 0)
  491. {
  492. titleId = controlData.PresenceGroupId.ToString("x16");
  493. }
  494. else if (controlData.SaveDataOwnerId != 0)
  495. {
  496. titleId = controlData.SaveDataOwnerId.ToString("x16");
  497. }
  498. else if (controlData.AddOnContentBaseId != 0)
  499. {
  500. titleId = (controlData.AddOnContentBaseId - 0x1000).ToString("x16");
  501. }
  502. else
  503. {
  504. titleId = "0000000000000000";
  505. }
  506. }
  507. }
  508. }