RequestHandler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. using CefSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Drawing;
  5. using System.Text.RegularExpressions;
  6. using System.Windows.Forms;
  7. namespace UAS_Web.tool
  8. {
  9. class RequestHandler : IRequestHandler
  10. {
  11. public event Action<byte[]> NotifyMsg;
  12. string PrinterName = "";
  13. string PrintType = "";
  14. PrinterList print;
  15. /// <summary>
  16. /// 拦截指定请求
  17. /// </summary>
  18. /// <param name="browserControl"></param>
  19. /// <param name="browser"></param>
  20. /// <param name="frame"></param>
  21. /// <param name="request"></param>
  22. /// <param name="response"></param>
  23. /// <returns></returns>
  24. IResponseFilter IRequestHandler.GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
  25. {
  26. MessageFilter filter;
  27. switch (request.Url.Substring(request.Url.LastIndexOf("/") + 1))
  28. {
  29. case "zplPrinter":
  30. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  31. return filter;
  32. case "zplPrint.action":
  33. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  34. return filter;
  35. case "getPrintType.action":
  36. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  37. return filter;
  38. default:
  39. break;
  40. }
  41. return null;
  42. }
  43. /// <summary>
  44. /// 完成响应后获取Js返回的数据
  45. /// </summary>
  46. /// <param name="browserControl"></param>
  47. /// <param name="browser"></param>
  48. /// <param name="frame"></param>
  49. /// <param name="request"></param>
  50. /// <param name="response"></param>
  51. /// <param name="status"></param>
  52. /// <param name="receivedContentLength"></param>
  53. void IRequestHandler.OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
  54. {
  55. MessageFilter filter;
  56. string str;
  57. Dictionary<string, object> data;
  58. switch (request.Url.Substring(request.Url.LastIndexOf("/") + 1))
  59. {
  60. case "zplPrinter":
  61. //弹出打印机选择列表
  62. print = new PrinterList(browser) { StartPosition = FormStartPosition.CenterScreen,TopMost=true };
  63. print.Controls["Confirm"].Click += RequestHandler_Click;
  64. print.ShowDialog();
  65. break;
  66. case "zplPrint.action":
  67. filter = FilterManager.GetFileter(request.Identifier.ToString()) as MessageFilter;
  68. str = System.Text.Encoding.UTF8.GetString(filter.dataAll.ToArray());
  69. data = ToDictionary(str);
  70. //获取所有的打印格式数据
  71. if (data.ContainsKey("data"))
  72. {
  73. string PrintCode = data["data"].ToString().Replace(" ", "").Replace("\"", "");
  74. List<string> PrintList = new List<string>();
  75. int PrintTime = Regex.Matches(PrintCode, "XA").Count;
  76. for (int i = 0; i < PrintTime; i++)
  77. {
  78. PrintList.Add(PrintCode.Substring(0, PrintCode.IndexOf("XZ") + 2));
  79. PrintCode = PrintCode.Substring(PrintCode.IndexOf("XZ") + 2);
  80. }
  81. for (int i = 0; i < PrintList.Count; i++)
  82. {
  83. PrintHelper.SendStringToPrinter(PrinterName, PrintList[i]);
  84. }
  85. data.Clear();
  86. }
  87. else if (data.ContainsKey("exceptionInfo"))
  88. {
  89. //string PrintCode = data["exceptionInfo"].ToString();
  90. //MessageBox.Show(PrintCode);
  91. }
  92. break;
  93. case "getPrintType.action":
  94. filter = FilterManager.GetFileter(request.Identifier.ToString()) as MessageFilter;
  95. str = System.Text.Encoding.UTF8.GetString(filter.dataAll.ToArray());
  96. data = ToDictionary(str);
  97. PrintType = data["data"].ToString().Replace("\"", "");
  98. break;
  99. default:
  100. break;
  101. }
  102. }
  103. private void RequestHandler_Click(object sender, EventArgs e)
  104. {
  105. //设置打印机名称
  106. print.PrintDoc.PrinterSettings.PrinterName = print.Controls["Printer"].Text;
  107. PrinterName = print.Controls["Printer"].Text;
  108. //获取矩阵图的分辨率
  109. Graphics gr = print.PrintDoc.PrinterSettings.CreateMeasurementGraphics();
  110. print.browser.FocusedFrame.ExecuteJavaScriptAsync("(function(value,value1){dpi=value,printType=value1})('" + gr.DpiX + "','" + PrintType + "')");
  111. print.browser.FocusedFrame.ExecuteJavaScriptAsync("document.getElementById('confirmZplPrint').click();");
  112. print.Close();
  113. }
  114. void filter_NotifyData(byte[] data)
  115. {
  116. if (NotifyMsg != null)
  117. {
  118. NotifyMsg(data);
  119. }
  120. }
  121. public bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
  122. {
  123. return false;
  124. }
  125. public bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool isRedirect)
  126. {
  127. return false;
  128. }
  129. public CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
  130. {
  131. return CefReturnValue.Continue;
  132. }
  133. public bool OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
  134. {
  135. return false;
  136. }
  137. public bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
  138. {
  139. return false;
  140. }
  141. public void OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath)
  142. {
  143. }
  144. public bool OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url)
  145. {
  146. return false;
  147. }
  148. public bool OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback)
  149. {
  150. return false;
  151. }
  152. public void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status)
  153. {
  154. }
  155. public void OnRenderViewReady(IWebBrowser browserControl, IBrowser browser)
  156. {
  157. }
  158. public void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
  159. {
  160. }
  161. public void OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, ref string newUrl)
  162. {
  163. }
  164. bool IRequestHandler.OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
  165. {
  166. return false;
  167. }
  168. public void GetData()
  169. {
  170. }
  171. public static Dictionary<string, object> ToDictionary(string JsonData)
  172. {
  173. object Data = null;
  174. Dictionary<string, object> Dic = new Dictionary<string, object>();
  175. if (JsonData.StartsWith("["))
  176. {
  177. //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
  178. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
  179. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  180. MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  181. foreach (Match ListItem in ListMatch)
  182. {
  183. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  184. }
  185. Data = List;
  186. Dic.Add("List", Data);
  187. }
  188. else
  189. {
  190. MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
  191. foreach (Match item in Match)
  192. {
  193. try
  194. {
  195. if (item.Groups[2].ToString().StartsWith("["))
  196. {
  197. //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
  198. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
  199. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  200. MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  201. foreach (Match ListItem in ListMatch)
  202. {
  203. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  204. }
  205. Data = List;
  206. }
  207. else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
  208. else Data = item.Groups[2].ToString(); //数据为数字、字符串中的一类,直接写入
  209. Dic.Add(item.Groups[1].ToString(), Data);
  210. }
  211. catch { }
  212. }
  213. }
  214. return Dic;
  215. }
  216. }
  217. }