ApplicationLibrary.cs 26 KB

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