RequestHandler.cs 9.7 KB

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