ApplicationLibrary.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. using LibHac;
  2. using LibHac.Fs;
  3. using LibHac.Fs.NcaUtils;
  4. using Ryujinx.Common.Logging;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Text;
  11. using SystemState = Ryujinx.HLE.HOS.SystemState;
  12. namespace Ryujinx.UI
  13. {
  14. public class ApplicationLibrary
  15. {
  16. private static Keyset KeySet;
  17. private static SystemState.TitleLanguage DesiredTitleLanguage;
  18. private const double SecondsPerMinute = 60.0;
  19. private const double SecondsPerHour = SecondsPerMinute * 60;
  20. private const double SecondsPerDay = SecondsPerHour * 24;
  21. public static byte[] RyujinxNspIcon { get; private set; }
  22. public static byte[] RyujinxXciIcon { get; private set; }
  23. public static byte[] RyujinxNcaIcon { get; private set; }
  24. public static byte[] RyujinxNroIcon { get; private set; }
  25. public static byte[] RyujinxNsoIcon { get; private set; }
  26. public static List<ApplicationData> ApplicationLibraryData { get; private set; }
  27. public struct ApplicationData
  28. {
  29. public byte[] Icon;
  30. public string TitleName;
  31. public string TitleId;
  32. public string Developer;
  33. public string Version;
  34. public string TimePlayed;
  35. public string LastPlayed;
  36. public string FileExt;
  37. public string FileSize;
  38. public string Path;
  39. }
  40. public static void Init(List<string> AppDirs, Keyset keySet, SystemState.TitleLanguage desiredTitleLanguage)
  41. {
  42. KeySet = keySet;
  43. DesiredTitleLanguage = desiredTitleLanguage;
  44. // Loads the default application Icons
  45. RyujinxNspIcon = GetResourceBytes("Ryujinx.Ui.assets.ryujinxNSPIcon.png");
  46. RyujinxXciIcon = GetResourceBytes("Ryujinx.Ui.assets.ryujinxXCIIcon.png");
  47. RyujinxNcaIcon = GetResourceBytes("Ryujinx.Ui.assets.ryujinxNCAIcon.png");
  48. RyujinxNroIcon = GetResourceBytes("Ryujinx.Ui.assets.ryujinxNROIcon.png");
  49. RyujinxNsoIcon = GetResourceBytes("Ryujinx.Ui.assets.ryujinxNSOIcon.png");
  50. // Builds the applications list with paths to found applications
  51. List<string> applications = new List<string>();
  52. foreach (string appDir in AppDirs)
  53. {
  54. if (Directory.Exists(appDir) == false)
  55. {
  56. Logger.PrintWarning(LogClass.Application, $"The \"game_dirs\" section in \"Config.json\" contains an invalid directory: \"{appDir}\"");
  57. continue;
  58. }
  59. DirectoryInfo AppDirInfo = new DirectoryInfo(appDir);
  60. foreach (FileInfo App in AppDirInfo.GetFiles())
  61. {
  62. if ((Path.GetExtension(App.ToString()) == ".xci") ||
  63. (Path.GetExtension(App.ToString()) == ".nca") ||
  64. (Path.GetExtension(App.ToString()) == ".nsp") ||
  65. (Path.GetExtension(App.ToString()) == ".pfs0") ||
  66. (Path.GetExtension(App.ToString()) == ".nro") ||
  67. (Path.GetExtension(App.ToString()) == ".nso"))
  68. {
  69. applications.Add(App.ToString());
  70. }
  71. }
  72. }
  73. // Loops through applications list, creating a struct for each application and then adding the struct to a list of structs
  74. ApplicationLibraryData = new List<ApplicationData>();
  75. foreach (string applicationPath in applications)
  76. {
  77. double filesize = new FileInfo(applicationPath).Length * 0.000000000931;
  78. string titleName = null;
  79. string titleId = null;
  80. string developer = null;
  81. string version = null;
  82. byte[] applicationIcon = null;
  83. using (FileStream file = new FileStream(applicationPath, FileMode.Open, FileAccess.Read))
  84. {
  85. if ((Path.GetExtension(applicationPath) == ".nsp") ||
  86. (Path.GetExtension(applicationPath) == ".pfs0") ||
  87. (Path.GetExtension(applicationPath) == ".xci"))
  88. {
  89. try
  90. {
  91. IFileSystem controlFs = null;
  92. // Store the ControlFS in variable called controlFs
  93. if (Path.GetExtension(applicationPath) == ".xci")
  94. {
  95. Xci xci = new Xci(KeySet, file.AsStorage());
  96. controlFs = GetControlFs(xci.OpenPartition(XciPartitionType.Secure));
  97. }
  98. else
  99. {
  100. controlFs = GetControlFs(new PartitionFileSystem(file.AsStorage()));
  101. }
  102. // Creates NACP class from the NACP file
  103. IFile controlNacp = controlFs.OpenFile("/control.nacp", OpenMode.Read);
  104. Nacp controlData = new Nacp(controlNacp.AsStream());
  105. // Get the title name, title ID, developer name and version number from the NACP
  106. version = controlData.DisplayVersion;
  107. titleName = controlData.Descriptions[(int)DesiredTitleLanguage].Title;
  108. if (string.IsNullOrWhiteSpace(titleName))
  109. {
  110. titleName = controlData.Descriptions.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title;
  111. }
  112. titleId = controlData.PresenceGroupId.ToString("x16");
  113. if (string.IsNullOrWhiteSpace(titleId))
  114. {
  115. titleId = controlData.SaveDataOwnerId.ToString("x16");
  116. }
  117. if (string.IsNullOrWhiteSpace(titleId))
  118. {
  119. titleId = (controlData.AddOnContentBaseId - 0x1000).ToString("x16");
  120. }
  121. developer = controlData.Descriptions[(int)DesiredTitleLanguage].Developer;
  122. if (string.IsNullOrWhiteSpace(developer))
  123. {
  124. developer = controlData.Descriptions.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Developer)).Developer;
  125. }
  126. // Read the icon from the ControlFS and store it as a byte array
  127. try
  128. {
  129. IFile icon = controlFs.OpenFile($"/icon_{DesiredTitleLanguage}.dat", OpenMode.Read);
  130. using (MemoryStream stream = new MemoryStream())
  131. {
  132. icon.AsStream().CopyTo(stream);
  133. applicationIcon = stream.ToArray();
  134. }
  135. }
  136. catch (HorizonResultException)
  137. {
  138. IDirectory controlDir = controlFs.OpenDirectory("./", OpenDirectoryMode.All);
  139. foreach (DirectoryEntry entry in controlDir.Read())
  140. {
  141. if (entry.Name == "control.nacp")
  142. {
  143. continue;
  144. }
  145. IFile icon = controlFs.OpenFile(entry.FullPath, OpenMode.Read);
  146. using (MemoryStream stream = new MemoryStream())
  147. {
  148. icon.AsStream().CopyTo(stream);
  149. applicationIcon = stream.ToArray();
  150. }
  151. if (applicationIcon != null)
  152. {
  153. break;
  154. }
  155. }
  156. if (applicationIcon == null)
  157. {
  158. applicationIcon = NspOrXciIcon(applicationPath);
  159. }
  160. }
  161. }
  162. catch (MissingKeyException exception)
  163. {
  164. titleName = "Unknown";
  165. titleId = "Unknown";
  166. developer = "Unknown";
  167. version = "?";
  168. applicationIcon = NspOrXciIcon(applicationPath);
  169. Logger.PrintWarning(LogClass.Application, $"Your key set is missing a key with the name: {exception.Name}");
  170. }
  171. catch (InvalidDataException)
  172. {
  173. titleName = "Unknown";
  174. titleId = "Unknown";
  175. developer = "Unknown";
  176. version = "?";
  177. applicationIcon = NspOrXciIcon(applicationPath);
  178. Logger.PrintWarning(LogClass.Application, $"The file is not an NCA file or the header key is incorrect. Errored File: {applicationPath}");
  179. }
  180. catch (Exception exception)
  181. {
  182. Logger.PrintWarning(LogClass.Application, $"This warning usualy means that you have a DLC in one of you game directories\n{exception}");
  183. continue;
  184. }
  185. }
  186. else if (Path.GetExtension(applicationPath) == ".nro")
  187. {
  188. BinaryReader reader = new BinaryReader(file);
  189. byte[] Read(long Position, int Size)
  190. {
  191. file.Seek(Position, SeekOrigin.Begin);
  192. return reader.ReadBytes(Size);
  193. }
  194. file.Seek(24, SeekOrigin.Begin);
  195. int AssetOffset = reader.ReadInt32();
  196. if (Encoding.ASCII.GetString(Read(AssetOffset, 4)) == "ASET")
  197. {
  198. byte[] IconSectionInfo = Read(AssetOffset + 8, 0x10);
  199. long iconOffset = BitConverter.ToInt64(IconSectionInfo, 0);
  200. long iconSize = BitConverter.ToInt64(IconSectionInfo, 8);
  201. ulong nacpOffset = reader.ReadUInt64();
  202. ulong nacpSize = reader.ReadUInt64();
  203. // Reads and stores game icon as byte array
  204. applicationIcon = Read(AssetOffset + iconOffset, (int)iconSize);
  205. // Creates memory stream out of byte array which is the NACP
  206. using (MemoryStream stream = new MemoryStream(Read(AssetOffset + (int)nacpOffset, (int)nacpSize)))
  207. {
  208. // Creates NACP class from the memory stream
  209. Nacp controlData = new Nacp(stream);
  210. // Get the title name, title ID, developer name and version number from the NACP
  211. version = controlData.DisplayVersion;
  212. titleName = controlData.Descriptions[(int)DesiredTitleLanguage].Title;
  213. if (string.IsNullOrWhiteSpace(titleName))
  214. {
  215. titleName = controlData.Descriptions.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title;
  216. }
  217. titleId = controlData.PresenceGroupId.ToString("x16");
  218. if (string.IsNullOrWhiteSpace(titleId))
  219. {
  220. titleId = controlData.SaveDataOwnerId.ToString("x16");
  221. }
  222. if (string.IsNullOrWhiteSpace(titleId))
  223. {
  224. titleId = (controlData.AddOnContentBaseId - 0x1000).ToString("x16");
  225. }
  226. developer = controlData.Descriptions[(int)DesiredTitleLanguage].Developer;
  227. if (string.IsNullOrWhiteSpace(developer))
  228. {
  229. developer = controlData.Descriptions.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Developer)).Developer;
  230. }
  231. }
  232. }
  233. else
  234. {
  235. applicationIcon = RyujinxNroIcon;
  236. titleName = "Application";
  237. titleId = "0000000000000000";
  238. developer = "Unknown";
  239. version = "?";
  240. }
  241. }
  242. // If its an NCA or NSO we just set defaults
  243. else if ((Path.GetExtension(applicationPath) == ".nca") || (Path.GetExtension(applicationPath) == ".nso"))
  244. {
  245. if (Path.GetExtension(applicationPath) == ".nca")
  246. {
  247. applicationIcon = RyujinxNcaIcon;
  248. }
  249. else if (Path.GetExtension(applicationPath) == ".nso")
  250. {
  251. applicationIcon = RyujinxNsoIcon;
  252. }
  253. string fileName = Path.GetFileName(applicationPath);
  254. string fileExt = Path.GetExtension(applicationPath);
  255. StringBuilder titlename = new StringBuilder();
  256. titlename.Append(fileName);
  257. titlename.Remove(fileName.Length - fileExt.Length, fileExt.Length);
  258. titleName = titlename.ToString();
  259. titleId = "0000000000000000";
  260. version = "?";
  261. developer = "Unknown";
  262. }
  263. }
  264. string[] playedData = GetPlayedData(titleId, "00000000000000000000000000000001");
  265. ApplicationData data = new ApplicationData()
  266. {
  267. Icon = applicationIcon,
  268. TitleName = titleName,
  269. TitleId = titleId,
  270. Developer = developer,
  271. Version = version,
  272. TimePlayed = playedData[0],
  273. LastPlayed = playedData[1],
  274. FileExt = Path.GetExtension(applicationPath).ToUpper().Remove(0 ,1),
  275. FileSize = (filesize < 1) ? (filesize * 1024).ToString("0.##") + "MB" : filesize.ToString("0.##") + "GB",
  276. Path = applicationPath,
  277. };
  278. ApplicationLibraryData.Add(data);
  279. }
  280. }
  281. private static byte[] GetResourceBytes(string resourceName)
  282. {
  283. Stream resourceStream = Assembly.GetCallingAssembly().GetManifestResourceStream(resourceName);
  284. byte[] resourceByteArray = new byte[resourceStream.Length];
  285. resourceStream.Read(resourceByteArray);
  286. return resourceByteArray;
  287. }
  288. private static IFileSystem GetControlFs(PartitionFileSystem Pfs)
  289. {
  290. Nca controlNca = null;
  291. // Add keys to keyset if needed
  292. foreach (DirectoryEntry ticketEntry in Pfs.EnumerateEntries("*.tik"))
  293. {
  294. Ticket ticket = new Ticket(Pfs.OpenFile(ticketEntry.FullPath, OpenMode.Read).AsStream());
  295. if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId))
  296. {
  297. KeySet.TitleKeys.Add(ticket.RightsId, ticket.GetTitleKey(KeySet));
  298. }
  299. }
  300. // Find the Control NCA and store it in variable called controlNca
  301. foreach (DirectoryEntry fileEntry in Pfs.EnumerateEntries("*.nca"))
  302. {
  303. Nca nca = new Nca(KeySet, Pfs.OpenFile(fileEntry.FullPath, OpenMode.Read).AsStorage());
  304. if (nca.Header.ContentType == ContentType.Control)
  305. {
  306. controlNca = nca;
  307. }
  308. }
  309. // Return the ControlFS
  310. return controlNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
  311. }
  312. private static string[] GetPlayedData(string TitleId, string UserId)
  313. {
  314. try
  315. {
  316. string[] playedData = new string[2];
  317. string savePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RyuFS", "nand", "user", "save", "0000000000000000", UserId, TitleId);
  318. if (File.Exists(Path.Combine(savePath, "TimePlayed.dat")) == false)
  319. {
  320. Directory.CreateDirectory(savePath);
  321. using (FileStream file = File.OpenWrite(Path.Combine(savePath, "TimePlayed.dat")))
  322. {
  323. file.Write(Encoding.ASCII.GetBytes("0"));
  324. }
  325. }
  326. using (FileStream fs = File.OpenRead(Path.Combine(savePath, "TimePlayed.dat")))
  327. {
  328. using (StreamReader sr = new StreamReader(fs))
  329. {
  330. float timePlayed = float.Parse(sr.ReadLine());
  331. if (timePlayed < SecondsPerMinute)
  332. {
  333. playedData[0] = $"{timePlayed}s";
  334. }
  335. else if (timePlayed < SecondsPerHour)
  336. {
  337. playedData[0] = $"{Math.Round(timePlayed / SecondsPerMinute, 2, MidpointRounding.AwayFromZero)} mins";
  338. }
  339. else if (timePlayed < SecondsPerDay)
  340. {
  341. playedData[0] = $"{Math.Round(timePlayed / SecondsPerHour , 2, MidpointRounding.AwayFromZero)} hrs";
  342. }
  343. else
  344. {
  345. playedData[0] = $"{Math.Round(timePlayed / SecondsPerDay , 2, MidpointRounding.AwayFromZero)} days";
  346. }
  347. }
  348. }
  349. if (File.Exists(Path.Combine(savePath, "LastPlayed.dat")) == false)
  350. {
  351. Directory.CreateDirectory(savePath);
  352. using (FileStream file = File.OpenWrite(Path.Combine(savePath, "LastPlayed.dat")))
  353. {
  354. file.Write(Encoding.ASCII.GetBytes("Never"));
  355. }
  356. }
  357. using (FileStream fs = File.OpenRead(Path.Combine(savePath, "LastPlayed.dat")))
  358. {
  359. using (StreamReader sr = new StreamReader(fs))
  360. {
  361. playedData[1] = sr.ReadLine();
  362. }
  363. }
  364. return playedData;
  365. }
  366. catch
  367. {
  368. return new string[] { "Unknown", "Unknown" };
  369. }
  370. }
  371. private static byte[] NspOrXciIcon(string applicationPath)
  372. {
  373. if (Path.GetExtension(applicationPath) == ".xci")
  374. {
  375. return RyujinxXciIcon;
  376. }
  377. else
  378. {
  379. return RyujinxNspIcon;
  380. }
  381. }
  382. }
  383. }