ApplicationLibrary.cs 25 KB

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