ApplicationLibrary.cs 21 KB

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