ApplicationLibrary.cs 23 KB

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