锐腾搅拌上料功能
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

383 lines
15 KiB

5 months ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Net.Http.Headers;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using Newtonsoft.Json;
  11. using Newtonsoft.Json.Linq;
  12. namespace ICSSoft.Frame.Common
  13. {
  14. public class KodboxHelper
  15. {
  16. public string Name { get; set; }
  17. private readonly string kodboxUrl = "http://127.0.0.1:88/kodbox122";
  18. public string accessToken { get; set; }
  19. private readonly HttpClient hClient;
  20. public KodboxHelper(string url)
  21. {
  22. this.kodboxUrl = url;
  23. var handler = new HttpClientHandler() { UseCookies = true };
  24. this.hClient = new HttpClient(handler);
  25. //hClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
  26. //hClient.DefaultRequestHeaders.Add("Keep-Alive", "timeout=600");
  27. }
  28. public void Dispose()
  29. {
  30. if (this.hClient != null)
  31. {
  32. this.hClient.Dispose();
  33. }
  34. }
  35. /// <summary>
  36. /// GET请求可道云,返回json字符串
  37. /// </summary>
  38. /// <param name="apiUrl">请求地址</param>
  39. /// <returns>json</returns>
  40. internal string GetKodApiAsync(string apiUrl)
  41. {
  42. var res = hClient.GetStringAsync(apiUrl);
  43. return res.Result;
  44. }
  45. //internal async Task<string> AwaitKodApiAsync(string apiUrl)
  46. //{
  47. // try
  48. // {
  49. // var res = await hClient.GetStringAsync(apiUrl);
  50. // return res;
  51. // }
  52. // catch (HttpRequestException ex)
  53. // {
  54. // throw new Exception(ex.Message + "\r\n" + ex.InnerException?.Message ?? "");
  55. // }
  56. // catch (Exception ex)
  57. // {
  58. // throw ex;
  59. // }
  60. //}
  61. /// <summary>
  62. /// POST请求可道云,返回json字符串
  63. /// </summary>
  64. /// <param name="apiUrl">请求地址</param>
  65. /// <param name="dic">参数字典</param>
  66. /// <returns></returns>
  67. internal string PostKodApi(string apiUrl, Dictionary<string, string> dic)
  68. {
  69. dic.Add("accessToken", this.accessToken);
  70. HttpContent content = new FormUrlEncodedContent(dic);
  71. content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
  72. //content.Headers.Add("X-CSRF-TOKEN",this.accessToken);
  73. //hClient.DefaultRequestHeaders.Accept.Clear();
  74. //hClient.DefaultRequestHeaders.Add("X-CSRF-Token",this.accessToken);
  75. HttpResponseMessage response = hClient.PostAsync(apiUrl, content).Result;
  76. //response.Headers.Add("Cookie", "session_id=7258abbd1544b6c530a9f406d3e600239bd788fb");
  77. string res = response.Content.ReadAsStringAsync().Result;
  78. return res;
  79. }
  80. /// <summary>
  81. /// 请求方式:GET;
  82. /// 请求地址:http://server/?user/index/loginSubmit&name=[用户名]&password=[密码]
  83. /// 返回结果:
  84. /// {
  85. /// "code": true,
  86. /// "use_time": 0.009,
  87. /// "data": "ok",
  88. /// "info": "ad947n9kDU6nr1V22j7MewCHNWCrZ0GgMDnNyzjv2y58YImivhggVsZ4Xg" //accessToken;
  89. /// }
  90. /// </summary>
  91. /// <returns></returns>
  92. public string Login(string kodboxUser, string kodboxrPwd)
  93. {
  94. var requestUrl = "{0}/?user/index/loginSubmit&name={1}&password={2}";
  95. requestUrl = string.Format(requestUrl, this.kodboxUrl, kodboxUser, kodboxrPwd);
  96. string res = GetKodApiAsync(requestUrl).ToString();
  97. JObject o = (JObject)JToken.Parse(res);
  98. this.accessToken = o.Last.Last.ToString();
  99. //var authenticationHeaderValue = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", this.accessToken);
  100. //Client.DefaultRequestHeaders.Authorization = authenticationHeaderValue;
  101. return res;
  102. }
  103. //public async Task<string> AwaitLoginAsync(string kodboxUser, string kodboxrPwd)
  104. //{
  105. // var requestUrl = $"{kodboxUrl}/?user/index/loginSubmit&name={kodboxUser}&password={kodboxrPwd}";
  106. // string res = await AwaitKodApiAsync(requestUrl);
  107. // if (res.StartsWith("<html>")&& res.Contains("出错"))
  108. // {
  109. // throw new Exception(res);
  110. // }
  111. // JObject o = (JObject)JToken.Parse(res);
  112. // this.accessToken = o.Last.Last.ToString();
  113. // return res;
  114. //}
  115. /// <summary>
  116. /// 请求方式:GET 请求地址:http://server/index.php?user/index/logout
  117. /// 如果是浏览器: 则用js请求一下退出接口或跳转到改地址即可; 如果纯接口访问: 上述地址追加 &accessToken=xxxx; 则该accessToken失效;
  118. /// </summary>
  119. /// <returns></returns>
  120. public string Logout(bool @throw)
  121. {
  122. if (this.accessToken == "" && @throw)
  123. {
  124. throw new Exception("未登录!");
  125. }
  126. var requestUrl = this.kodboxUrl + "/index.php?user/index/logout&accessToken={this.accessToken}";
  127. return GetKodApiAsync(requestUrl).ToString();
  128. }
  129. // 获取文件列表
  130. public string GetList(string path)
  131. {
  132. Dictionary<string, string> dic = new Dictionary<string, string>();
  133. dic.Add("path", path);
  134. string requestUrl = this.kodboxUrl + "/index.php?explorer/list/path";
  135. return PostKodApi(requestUrl, dic);
  136. }
  137. /// <summary>
  138. /// 在指定目录下查找指定类型文件,返回displayPath相符文件的source路径
  139. /// </summary>
  140. /// <param name="rootPath">搜索起始目录</param>
  141. /// <param name="fileType">文件类型</param>
  142. /// <param name="matchingPath1">匹配路径</param>
  143. /// <returns></returns>
  144. public List<string> GetSourcePath(string rootPath, string fileType, string matchingPath1, string matchingPath2, string matchingPath3, out string searchRes)
  145. {
  146. List<string> listReturn = new List<string>();
  147. string displaypath = "";
  148. searchRes = "";
  149. string respath = "";
  150. string path = "{search}/";
  151. List<string> list = new List<string>()
  152. {
  153. "parentPath="+rootPath,
  154. "fileType="+fileType
  155. //"accessToken="+this.accessToken
  156. };
  157. path += String.Join("@", list);
  158. Dictionary<string, string> dic = new Dictionary<string, string>();
  159. dic.Add("path", path);
  160. string requestUrl = this.kodboxUrl + "/index.php?explorer/list/path";
  161. searchRes = PostKodApi(requestUrl, dic);
  162. KodboxReturn item = JsonConvert.DeserializeObject<KodboxReturn>(searchRes);
  163. if (!item.code)
  164. {
  165. throw new Exception(item.data.ToString());
  166. }
  167. SearchDataIntity data = JsonConvert.DeserializeObject<SearchDataIntity>(item.data.ToString());
  168. if (data.fileList.Count == 0)
  169. {
  170. throw new Exception("目录" + rootPath + "没有类型" + fileType + "文件");
  171. }
  172. SearchParentIntity parent = data.searchParent;
  173. displaypath = Path.Combine(parent.pathDisplay, matchingPath1);
  174. List<FileIntity> filelist = data.fileList;
  175. foreach (FileIntity info in filelist)
  176. {
  177. if (info.pathDisplay.StartsWith(displaypath) && info.pathDisplay.Contains(matchingPath2) && info.pathDisplay.Contains(matchingPath3))
  178. {
  179. respath = info.path + "|" + info.name + "|" + info.pathDisplay;// displaypath;
  180. listReturn.Add(respath);
  181. }
  182. }
  183. if (listReturn.Count == 0)
  184. {
  185. throw new Exception("文件夹不存在:" + displaypath);
  186. }
  187. return listReturn;
  188. }
  189. //public KodSearch GetSourcePath(string rootPath, string fileType, string displaypath)
  190. //{
  191. // string path = "{search}/";
  192. // List<string> list = new List<string>()
  193. // {
  194. // "parentPath="+rootPath,
  195. // "fileType="+fileType
  196. // };
  197. // path += String.Join("@", list);
  198. // Dictionary<string, string> dic = new Dictionary<string, string>();
  199. // dic.Add("path", path);
  200. // string requestUrl =this.kodboxUrl+"/index.php?explorer/list/path";
  201. // string searchRes = PostKodApi(requestUrl, dic);
  202. // KodSearch s = JsonConvert.DeserializeObject<KodSearch>(searchRes);
  203. // return s;
  204. //}
  205. //public KodIntity GetSourcePath(string rootPath, string fileType, string displaypath,int i=0)
  206. //{
  207. // string path = "{search}/";
  208. // List<string> list = new List<string>()
  209. // {
  210. // "parentPath="+rootPath,
  211. // "fileType="+fileType
  212. // };
  213. // path += String.Join("@", list);
  214. // Dictionary<string, string> dic = new Dictionary<string, string>();
  215. // dic.Add("path", path);
  216. // string requestUrl = $"{kodboxUrl}/index.php?explorer/list/path";
  217. // string searchRes = PostKodApi(requestUrl, dic);
  218. // KodIntity s = JsonConvert.DeserializeObject<KodIntity>(searchRes);
  219. // return s;
  220. //}
  221. //搜索
  222. //path: '{search}/' + param.join('@');
  223. //// 搜索条件参数:
  224. //var param = [
  225. //'parentPath', // 选择全部文件夹时为空
  226. //'words', // 搜索关键字
  227. //'sizeFrom', // 大小,单位B
  228. //'sizeTo',
  229. //'timeFrom', // 时间,格式:2020/02/21
  230. //'timeTo',
  231. //'fileType', // 文件类型,根据文件列表获取,参数:path={block:fileType}
  232. //'createUser' // userID
  233. //]
  234. /// <summary>
  235. /// 下载
  236. /// </summary>
  237. /// <param name="source">如{source:255642}/</param>
  238. /// <param name="savePath">保存路径,如D:/myDoc/abc</param>
  239. /// <param name="saveName">123.pdf</param>
  240. /// <returns></returns>
  241. public string DownFile(string source, string savePath, string saveName)
  242. {
  243. string requestUrl = this.kodboxUrl + "/index.php?explorer/index/fileOut&path={0}&download=1";
  244. requestUrl = string.Format(requestUrl, source);
  245. //string requestUrl = $"{kodboxUrl}/index.php?explorer/fileDownload&path={source}";
  246. string msg = "";
  247. bool succ = GetFileFromKod(requestUrl, savePath, saveName, out msg);
  248. if (succ)
  249. {
  250. return "OK";
  251. }
  252. return msg;
  253. }
  254. //16. 文件下载
  255. //请求方式:GET
  256. //请求地址:http://server/index.php?explorer/index/fileOut
  257. //请求参数:&path={source:1031}/&download=1
  258. internal bool GetFileFromKod(string apiUrl, string filePath, string filename, out string msg)
  259. {
  260. msg = "OK";
  261. bool suc = false;
  262. // FileStream fs;
  263. try
  264. {
  265. Uri uri = new Uri(apiUrl);
  266. HttpResponseMessage responseMessage = hClient.GetAsync(uri).Result;
  267. if (responseMessage.IsSuccessStatusCode)
  268. {
  269. if (responseMessage.Content.Headers.ContentType.ToString().Contains("application/json"))
  270. {
  271. suc = false;
  272. var res = responseMessage.Content.ReadAsStringAsync().Result;
  273. DownFailInfo dfi = JsonConvert.DeserializeObject<DownFailInfo>(res);
  274. msg = "下载文件:" + dfi.data;
  275. }
  276. else
  277. {
  278. if (!Directory.Exists(filePath))
  279. {
  280. Directory.CreateDirectory(filePath);
  281. }
  282. //如果文件被本地程序占用,无法下载
  283. using (var fs = File.Create(Path.Combine(filePath, filename)))
  284. {
  285. var streamFromService = responseMessage.Content.ReadAsStreamAsync().Result;
  286. streamFromService.CopyTo(fs);
  287. }
  288. suc = true;
  289. }
  290. }
  291. else
  292. {
  293. suc = false;
  294. msg = responseMessage.StatusCode.ToString();
  295. }
  296. //byte[] bytes = XXX.Result;
  297. //string res = System.Text.Encoding.UTF8.GetString(bytes);
  298. //JObject o = (JObject)JToken.Parse(res);
  299. //if (o == null)
  300. //{
  301. // throw new Exception("错误请求");
  302. //}
  303. //if (o["code"].ToString() == "10001" || o["code"].ToString().ToLower() == "false")
  304. //{
  305. // throw new Exception(o["data"].ToString());
  306. //}
  307. //using (fs = new FileStream(Path.Combine(filePath, filename), FileMode.Create))
  308. //{
  309. // fs.Write(bytes, 0, bytes.Length);
  310. //}
  311. }
  312. catch (Exception ex)
  313. {
  314. suc = false;
  315. msg = ex.Message;
  316. }
  317. return suc;
  318. }
  319. //16. 文件下载
  320. //请求方式:GET
  321. //请求地址:http://server/index.php?explorer/index/fileOut
  322. //请求参数:&path={source:1031}/&download=1
  323. }
  324. public class KodboxReturn
  325. {
  326. public bool code { get; set; }
  327. public string timeUse { get; set; }
  328. public string timeNow { get; set; }
  329. public object data { get; set; }
  330. }
  331. public class SearchDataIntity
  332. {
  333. public object pageInfo { get; set; }
  334. public object folderList { get; set; }
  335. public List<FileIntity> fileList { get; set; }
  336. public SearchParentIntity searchParent { get; set; }
  337. }
  338. public class SearchParentIntity
  339. {
  340. public string name { get; set; }
  341. public string path { get; set; }
  342. public string type { get; set; }
  343. public string pathDisplay { get; set; }
  344. }
  345. public class FileIntity
  346. {
  347. public string name { get; set; }
  348. public string path { get; set; }
  349. public string type { get; set; }
  350. public string ext { get; set; }
  351. public string pathDisplay { get; set; }
  352. public string parentLevel { get; set; }
  353. }
  354. public class DownFailInfo
  355. {
  356. public string code { get; set; }
  357. public string timeUse { get; set; }
  358. public string timeNow { get; set; }
  359. public string data { get; set; }
  360. public string info { get; set; }
  361. }
  362. }