ViewEngine.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using MiniWebApi.Utilities;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.IO.Compression;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using Vinno.IUS.Common.Log;
  11. namespace Vinno.vCloud.Disk
  12. {
  13. internal class ViewEngine
  14. {
  15. public DateTime LastModifiedTime { get; set; }
  16. private Dictionary<string, string> _fileSourceDic;
  17. private string _namespace;
  18. /// <summary>
  19. /// 是否为局域网内部署
  20. /// </summary>
  21. public bool IsLocalServer { get; set; } = false;
  22. public ViewEngine()
  23. {
  24. _namespace = GetType().Namespace;
  25. _fileSourceDic = new Dictionary<string, string>();
  26. var fileList = GetType().Assembly.GetManifestResourceNames();
  27. foreach (string fileName in fileList)
  28. {
  29. if (string.IsNullOrWhiteSpace(fileName)) continue;
  30. if (!fileName.ToLower().StartsWith(_namespace.ToLower())) continue;
  31. string key = fileName.Substring(_namespace.Length).ToLower();
  32. _fileSourceDic.Add(key, fileName);
  33. _fileSourceDic.Add($".{key}", fileName);
  34. }
  35. }
  36. /// <summary>
  37. /// 获取资源文件
  38. /// </summary>
  39. /// <param name="filePath"></param>
  40. /// <returns></returns>
  41. public Stream GetResourceFile(string filePath)
  42. {
  43. filePath = filePath?.Replace("/", ".").ToLower();
  44. if (!filePath.StartsWith(".")) filePath = "." + filePath;
  45. if (!_fileSourceDic.ContainsKey(filePath)) return Stream.Null;
  46. return GetType().Assembly.GetManifestResourceStream(_fileSourceDic[filePath]);
  47. }
  48. /// <summary>
  49. /// 读取文件
  50. /// </summary>
  51. /// <param name="extType"></param>
  52. /// <param name="model"></param>
  53. /// <param name="fileStream"></param>
  54. /// <returns></returns>
  55. private List<byte> GetFileSource(string extType, object model, Stream fileStream)
  56. {
  57. List<byte> byteList = new List<byte>();
  58. if (fileStream != null)
  59. {
  60. using (fileStream)
  61. {
  62. byte[] bytes = new byte[8192];
  63. int readCount = 0;
  64. do
  65. {
  66. readCount = fileStream.Read(bytes, 0, bytes.Length);
  67. byteList.AddRange(bytes.Take(readCount));
  68. }
  69. while (readCount > 0);
  70. bytes = null;
  71. }
  72. }
  73. return byteList;
  74. }
  75. /// <summary>
  76. /// 获取资源文件
  77. /// </summary>
  78. /// <param name="filePath"></param>
  79. /// <returns></returns>
  80. private List<byte> GetResourceFile(string filePath, string extType, object model = null)
  81. {
  82. filePath = filePath?.Replace("/", ".").ToLower();
  83. if (!_fileSourceDic.ContainsKey(filePath)) return new List<byte>();
  84. using (var fileStream = GetType().Assembly.GetManifestResourceStream(_fileSourceDic[filePath]))
  85. {
  86. return GetFileSource(extType, model, fileStream);
  87. }
  88. }
  89. /// <summary>
  90. /// 读取某个路径下的文件
  91. /// </summary>
  92. /// <param name="filePath"></param>
  93. /// <returns></returns>
  94. private List<byte> GetPathFile(string filePath, string extType, object model = null)
  95. {
  96. if (!string.IsNullOrWhiteSpace(filePath))
  97. {
  98. var currentDir = AppDomain.CurrentDomain.BaseDirectory;
  99. filePath = Path.Combine(currentDir, filePath.Replace("/", "\\"));
  100. if (File.Exists(filePath))
  101. {
  102. using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
  103. {
  104. return GetFileSource(extType, model, fileStream);
  105. }
  106. }
  107. }
  108. return new List<byte>();
  109. }
  110. /// <summary>
  111. /// 获取资源文件文本内容
  112. /// </summary>
  113. /// <param name="filePath"></param>
  114. /// <param name="extType"></param>
  115. /// <returns></returns>
  116. public string GetResourceFileStr(string filePath, string extType)
  117. {
  118. return Encoding.UTF8.GetString(GetResourceFile(filePath, extType).ToArray());
  119. }
  120. /// <summary>
  121. /// 指定路径得到文件
  122. /// </summary>
  123. /// <param name="filePath"></param>
  124. /// <param name="mineType"></param>
  125. /// <param name="model"></param>
  126. /// <returns></returns>
  127. public List<byte> GetSource(string filePath, string mineType, object model = null)
  128. {
  129. var filePathWordLower = filePath.ToLower();
  130. //如果时内网部署则使用内网的easyEchartLocal.js
  131. if (IsLocalServer && filePathWordLower.IndexOf("/modules/easyEchart.js", StringComparison.CurrentCultureIgnoreCase) > -1)
  132. {
  133. filePath = Regex.Replace(filePath, ".*(/modules/easyEchart[.]js).*", EasyEchartReplace, RegexOptions.IgnoreCase);
  134. }
  135. var buffer = GetResourceFile(filePath, mineType, model);
  136. if (buffer.Count == 0)
  137. {
  138. buffer = GetPathFile(filePath, mineType, model);
  139. }
  140. return buffer;
  141. }
  142. /// <summary>
  143. /// 替换Echart文件路径
  144. /// </summary>
  145. /// <param name="match"></param>
  146. /// <returns></returns>
  147. private string EasyEchartReplace(Match match)
  148. {
  149. string newJSPath = match.Value;
  150. if (match.Success && match.Groups.Count > 1)
  151. {
  152. newJSPath = match.Value.Replace(match.Groups[1].Value, "/modules/easyEchartLocal.js");
  153. }
  154. return newJSPath;
  155. }
  156. /// <summary>
  157. /// 查找资源文件
  158. /// </summary>
  159. /// <param name="context"></param>
  160. /// <returns></returns>
  161. public bool FindSourceNoModel(HttpListenerContext context)
  162. {
  163. bool userCache = true;
  164. var lastModifiedTime = LastModifiedTime;
  165. var mineType = "html/text";
  166. if (context.Request.RawUrl == "/")
  167. {
  168. context.Response.Headers.Add("Location", "/index.html");
  169. context.Response.StatusCode = 302;
  170. context.Response.Close();
  171. return true;
  172. }
  173. var match = Regex.Match(context.Request.RawUrl, "\\S*[\\.](css|gif|html|json|js|eot|svg|ttf|woff|woff2|jpg|png|ico)");
  174. if (match.Success && match.Groups.Count > 1)
  175. {
  176. //服务器启动版本是否更改
  177. if (context.Request.Headers["If-Modified-Since"].ToStringEx() == lastModifiedTime.ToUniversalTime().ToString("r"))
  178. {
  179. context.Response.StatusCode = 304;
  180. context.Response.OutputStream.Close();
  181. return true;
  182. }
  183. var buffer = GetSource(match.Value, match.Groups[1].Value, null).ToArray();
  184. var content = Encoding.UTF8.GetString(buffer);
  185. if (buffer.Length > 0)
  186. {
  187. mineType = MineTypeJsonHelper.GetJsonRoot().GetJPropertyString($"$.{match.Groups[1].Value}");
  188. if (userCache && match.Groups[0].Value.IndexOf("/index.html", StringComparison.CurrentCultureIgnoreCase) == -1)
  189. {
  190. //设置Last-Modified标识最后的文件版本
  191. context.Response.AddHeader("Last-Modified", lastModifiedTime.ToUniversalTime().ToString("r"));
  192. //设置缓存超时时间
  193. context.Response.AddHeader("Cache-Control", "max-age=300");
  194. }
  195. //context.Response.ContentEncoding = Encoding.UTF8;
  196. context.Response.ContentType = mineType + (match.Groups[1].Value == "html" ? ";charset=utf-8" : "");
  197. if (context.Request.QueryString.Get("IsDownloadType") == "1")
  198. {
  199. context.Response.ContentType = "application/octet-stream";
  200. }
  201. context.Response.ProtocolVersion = new Version("1.1");
  202. if (!Regex.IsMatch(context.Request.RawUrl, "\\S*[\\.](gif|eot|svg|ttf|woff|woff2|jpg|png|ico)"))
  203. {
  204. ChooseCompress(context, buffer);
  205. }
  206. else
  207. {
  208. context.Response.ContentLength64 = buffer.Length;
  209. if (context.Response.OutputStream.CanWrite && context.Request.HttpMethod.ToUpper() != "HEAD")
  210. {
  211. context.Response.OutputStream.Write(buffer, 0, buffer.Length);
  212. }
  213. else
  214. {
  215. Logger.WriteLineWarn($"vcloud disk - http method err, url:{context?.Request?.Url}");
  216. }
  217. }
  218. context.Response.OutputStream.Close();
  219. buffer = null;
  220. return true;
  221. }
  222. }
  223. return false;
  224. }
  225. private void ChooseCompress(HttpListenerContext context, byte[] data)
  226. {
  227. context.Response.AddHeader("Content-Encoding", "deflate");
  228. CompressDeflate(context, data);
  229. return;
  230. }
  231. private void CompressDeflate(HttpListenerContext context, byte[] data)
  232. {
  233. using (MemoryStream memory = new MemoryStream())
  234. {
  235. using (var zipStream = new DeflateStream(memory, CompressionMode.Compress, true))
  236. {
  237. zipStream.Write(data, 0, data.Length);
  238. zipStream.Close();
  239. byte[] buffers = memory.ToArray();
  240. context.Response.ContentLength64 = buffers.Length;
  241. if (context.Response.OutputStream.CanWrite && context.Request.HttpMethod.ToUpper() != "HEAD")
  242. {
  243. context.Response.OutputStream.Write(buffers, 0, buffers.Length);
  244. }
  245. else
  246. {
  247. Logger.WriteLineWarn($"vcloud disk - http method err, url:{context?.Request?.Url}");
  248. }
  249. }
  250. }
  251. }
  252. }
  253. }