ApplicationLibrary.cs 26 KB

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