ArchiveWorker.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. namespace OpenVIII
  8. {
  9. public class ArchiveWorker : ArchiveBase
  10. {
  11. #region Fields
  12. public Memory.Archive _path;
  13. /// <summary>
  14. /// Generated File List
  15. /// </summary>
  16. public string[] FileList;
  17. private static ConcurrentDictionary<Memory.Archive, ConcurrentDictionary<string, byte[]>> ArchiveCache =
  18. new ConcurrentDictionary<Memory.Archive, ConcurrentDictionary<string, byte[]>>
  19. (new Dictionary<Memory.Archive, ConcurrentDictionary<string, byte[]>> {
  20. { Memory.Archives.A_BATTLE, new ConcurrentDictionary<string, byte[]>() },
  21. { Memory.Archives.A_FIELD, new ConcurrentDictionary<string, byte[]>() },
  22. { Memory.Archives.A_MAGIC, new ConcurrentDictionary<string, byte[]>() },
  23. { Memory.Archives.A_MAIN, new ConcurrentDictionary<string, byte[]>() },
  24. { Memory.Archives.A_MENU, new ConcurrentDictionary<string, byte[]>() },
  25. { Memory.Archives.A_WORLD, new ConcurrentDictionary<string, byte[]>() }
  26. });
  27. /// <summary>
  28. /// prevent two threads from writing to cache at the same time.
  29. /// </summary>
  30. private static object cachelock = new object();
  31. private bool _compressed;
  32. private uint _locationInFs;
  33. private uint _unpackedFileSize;
  34. private byte[] FI, FS, FL;
  35. private bool isDir = false;
  36. #endregion Fields
  37. #region Constructors
  38. /// <summary>
  39. /// Saves the active archive and file list.
  40. /// </summary>
  41. /// <param name="path">Memory.Archive</param>
  42. /// <param name="skiplist">If list generation is unneeded you can skip it by setting true</param>
  43. public ArchiveWorker(Memory.Archive path, bool skiplist = false)
  44. {
  45. if (Directory.Exists(path))
  46. {
  47. isDir = true;
  48. }
  49. _path = path;
  50. if (!skiplist)
  51. FileList = ProduceFileLists();
  52. }
  53. public ArchiveWorker(byte[] fI, byte[] fS, byte[] fL, bool skiplist = false)
  54. {
  55. FI = fI;
  56. FS = fS;
  57. FL = fL;
  58. if (!skiplist)
  59. FileList = ProduceFileLists();
  60. }
  61. #endregion Constructors
  62. #region Methods
  63. /// <summary>
  64. /// Generate archive worker and get file
  65. /// </summary>
  66. /// <param name="archive">which archive you want to read from</param>
  67. /// <param name="fileName">name of file you want to recieve</param>
  68. /// <returns>Uncompressed binary file data</returns>
  69. public static byte[] GetBinaryFile(Memory.Archive archive, string fileName, bool cache = false)
  70. {
  71. ArchiveWorker tmp = new ArchiveWorker(archive, true);
  72. return tmp.GetBinaryFile(fileName, cache);
  73. }
  74. public override ArchiveBase GetArchive(Memory.Archive archive) => new ArchiveWorker(GetBinaryFile(archive.FI), GetBinaryFile(archive.FS), GetBinaryFile(archive.FL)) { _path = archive };
  75. /// <summary>
  76. /// GetBinary
  77. /// </summary>
  78. /// <param name="fileName"></param>
  79. /// <returns></returns>
  80. public override byte[] GetBinaryFile(string fileName, bool cache = false)
  81. {
  82. if (string.IsNullOrWhiteSpace(fileName))
  83. throw new FileNotFoundException("NO FILENAME");
  84. if (FL != null && FL.Length > 0 && FI != null && FL.Length > 0 && FI != null && FL.Length > 0)
  85. return FileInTwoArchives(fileName);
  86. else
  87. if (!isDir)
  88. {
  89. int loc = FindFile(ref fileName, new FileStream(_path.FL, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); //File.OpenRead(_path.FL));
  90. // read file list
  91. if (loc == -1)
  92. {
  93. Debug.WriteLine("ArchiveWorker: NO SUCH FILE!");
  94. //throw new Exception("ArchiveWorker: No such file!");
  95. }
  96. else
  97. return GetBinaryFile(fileName, loc, cache);
  98. }
  99. else
  100. return GetBinaryFile(fileName, 0, cache);
  101. throw new FileNotFoundException($"Searched {_path} and could not find {fileName}.", fileName);
  102. }
  103. //public Stream GetBinaryFileStream(string fileName, bool cache = false) => throw new NotImplementedException();
  104. /// <summary>
  105. /// Get current file list for loaded archive.
  106. /// </summary>
  107. public override string[] GetListOfFiles() => FileList;
  108. public override Memory.Archive GetPath() => _path;
  109. private static bool GetLine(TextReader tr, out string line)
  110. {
  111. line = tr.ReadLine();
  112. if (!string.IsNullOrWhiteSpace(line))
  113. {
  114. line.TrimEnd('\0');
  115. return true;
  116. }
  117. return false;
  118. }
  119. /// <summary>
  120. /// Give me three archives as bytes uncompressed please!
  121. /// </summary>
  122. /// <param name="FI">FileIndex</param>
  123. /// <param name="FS">FileSystem</param>
  124. /// <param name="FL">FileList</param>
  125. /// <param name="filename">Filename of the file to get</param>
  126. /// <returns></returns>
  127. /// <remarks>
  128. /// Does the same thing as Get Binary file, but it reads from byte arrays in ram because the
  129. /// data was already pulled from a file earlier.
  130. /// </remarks>
  131. private byte[] FileInTwoArchives(string filename)
  132. {
  133. int loc = FindFile(ref filename, new MemoryStream(FL, false));
  134. if (loc == -1)
  135. {
  136. Debug.WriteLine("ArchiveWorker: NO SUCH FILE!");
  137. return null;
  138. //throw new Exception("ArchiveWorker: No such file!");
  139. }
  140. // get params from index
  141. uint fsLen = BitConverter.ToUInt32(FI, loc * 12);
  142. uint fSpos = BitConverter.ToUInt32(FI, (loc * 12) + 4);
  143. bool compe = BitConverter.ToUInt32(FI, (loc * 12) + 8) != 0;
  144. // copy binary data
  145. byte[] file = new byte[fsLen];
  146. Array.Copy(FS, fSpos, file, 0, file.Length);
  147. return compe ? LZSS.DecompressAllNew(file) : file;
  148. }
  149. /// <summary>
  150. /// Search file list for line filename is on.
  151. /// </summary>
  152. /// <param name="filename">filename or path to search for</param>
  153. /// <param name="stream">stream of text data to search in</param>
  154. /// <returns>-1 on error or &gt;=0 on success.</returns>
  155. private int FindFile(ref string filename, Stream stream)
  156. {
  157. filename = filename.TrimEnd('\0');
  158. using (TextReader tr = new StreamReader(stream))
  159. {
  160. for (int i = 0; GetLine(tr, out string line); i++)
  161. {
  162. if (string.IsNullOrWhiteSpace(line))
  163. {
  164. Debug.WriteLine("ArchiveWorker::File entry is null. Returning -1");
  165. break;
  166. }
  167. if (line.IndexOf(filename, StringComparison.OrdinalIgnoreCase) >= 0)
  168. {
  169. filename = line; //make sure the filename in dictionary is consistant.
  170. return i;
  171. }
  172. }
  173. }
  174. Debug.WriteLine($"ArchiveWorker:: Filename {filename}, not found. returning -1");
  175. return -1;
  176. }
  177. private byte[] GetBinaryFile(string fileName, int loc, bool cache)
  178. {
  179. if (ArchiveCache.TryGetValue(_path, out ConcurrentDictionary<string, byte[]> a) && a.TryGetValue(fileName, out byte[] b))
  180. return b;
  181. if (isDir)
  182. {
  183. if (FileList == null || FileList.Length == 0)
  184. ProduceFileLists();
  185. fileName = FileList.FirstOrDefault(x => x.IndexOf(fileName, StringComparison.OrdinalIgnoreCase) >= 0);
  186. if (!string.IsNullOrWhiteSpace(fileName))
  187. using (BinaryReader br = new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
  188. {
  189. return br.ReadBytes(checked((int)br.BaseStream.Length));
  190. }
  191. }
  192. byte[] temp = null;
  193. //read index data
  194. using (BinaryReader br = new BinaryReader(new FileStream(_path.FI, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))//File.OpenRead(_path.FI)))
  195. {
  196. br.BaseStream.Seek(loc * 12, SeekOrigin.Begin);
  197. _unpackedFileSize = br.ReadUInt32(); //fs.Seek(4, SeekOrigin.Current);
  198. _locationInFs = br.ReadUInt32();
  199. _compressed = br.ReadUInt32() != 0;
  200. }
  201. //read binary data.
  202. using (BinaryReader br = new BinaryReader(new FileStream(_path.FS, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))//File.OpenRead(_path.FS)))
  203. {
  204. br.BaseStream.Seek(_locationInFs, SeekOrigin.Begin);
  205. temp = br.ReadBytes(_compressed ? br.ReadInt32() : (int)_unpackedFileSize);
  206. }
  207. temp = temp == null ? null : _compressed ? LZSS.DecompressAllNew(temp) : temp;
  208. if (temp != null && cache && ArchiveCache.TryGetValue(_path, out a))
  209. a.TryAdd(fileName, temp);
  210. return temp;
  211. }
  212. /// <summary>
  213. /// Generate a file list from binary data.
  214. /// </summary>
  215. /// <param name="fl">raw File List</param>
  216. private string[] GetListOfFiles(byte[] fl) => ProduceFileLists(new MemoryStream(fl));
  217. /// <summary>
  218. /// Generate a file list from raw text file.
  219. /// </summary>
  220. /// <see cref="https://stackoverflow.com/questions/12744725/how-do-i-perform-file-readalllines-on-a-file-that-is-also-open-in-excel"/>
  221. private string[] ProduceFileLists()
  222. {
  223. if (isDir)
  224. return Directory.GetFiles(_path, "*", SearchOption.AllDirectories).OrderBy(x => x.Length).ThenBy(x => x, StringComparer.OrdinalIgnoreCase).ToArray();
  225. if (FL != null && FL.Length > 0)
  226. return GetListOfFiles(FL);
  227. return ProduceFileLists(new FileStream(_path.FL, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)).OrderBy(x => x.Length).ThenBy(x => x, StringComparer.OrdinalIgnoreCase).ToArray();
  228. }
  229. private string[] ProduceFileLists(Stream s)
  230. {
  231. using (StreamReader sr = new StreamReader(s, System.Text.Encoding.ASCII))
  232. {
  233. List<string> fl = new List<string>();
  234. while (!sr.EndOfStream)
  235. fl.Add(sr.ReadLine().Trim('\0', '\r', '\n'));
  236. return fl.ToArray();
  237. }
  238. }
  239. #endregion Methods
  240. }
  241. }