ApplicationLibrary.cs 22 KB

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