using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ICSSoft.Frame.Common { public class KodboxHelper { public string Name { get; set; } private readonly string kodboxUrl = "http://127.0.0.1:88/kodbox122"; public string accessToken { get; set; } private readonly HttpClient hClient; public KodboxHelper(string url) { this.kodboxUrl = url; var handler = new HttpClientHandler() { UseCookies = true }; this.hClient = new HttpClient(handler); //hClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0"); //hClient.DefaultRequestHeaders.Add("Keep-Alive", "timeout=600"); } public void Dispose() { if (this.hClient != null) { this.hClient.Dispose(); } } /// /// GET请求可道云,返回json字符串 /// /// 请求地址 /// json internal string GetKodApiAsync(string apiUrl) { var res = hClient.GetStringAsync(apiUrl); return res.Result; } //internal async Task AwaitKodApiAsync(string apiUrl) //{ // try // { // var res = await hClient.GetStringAsync(apiUrl); // return res; // } // catch (HttpRequestException ex) // { // throw new Exception(ex.Message + "\r\n" + ex.InnerException?.Message ?? ""); // } // catch (Exception ex) // { // throw ex; // } //} /// /// POST请求可道云,返回json字符串 /// /// 请求地址 /// 参数字典 /// internal string PostKodApi(string apiUrl, Dictionary dic) { dic.Add("accessToken", this.accessToken); HttpContent content = new FormUrlEncodedContent(dic); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); //content.Headers.Add("X-CSRF-TOKEN",this.accessToken); //hClient.DefaultRequestHeaders.Accept.Clear(); //hClient.DefaultRequestHeaders.Add("X-CSRF-Token",this.accessToken); HttpResponseMessage response = hClient.PostAsync(apiUrl, content).Result; //response.Headers.Add("Cookie", "session_id=7258abbd1544b6c530a9f406d3e600239bd788fb"); string res = response.Content.ReadAsStringAsync().Result; return res; } /// /// 请求方式:GET; /// 请求地址:http://server/?user/index/loginSubmit&name=[用户名]&password=[密码] /// 返回结果: /// { /// "code": true, /// "use_time": 0.009, /// "data": "ok", /// "info": "ad947n9kDU6nr1V22j7MewCHNWCrZ0GgMDnNyzjv2y58YImivhggVsZ4Xg" //accessToken; /// } /// /// public string Login(string kodboxUser, string kodboxrPwd) { var requestUrl = "{0}/?user/index/loginSubmit&name={1}&password={2}"; requestUrl = string.Format(requestUrl, this.kodboxUrl, kodboxUser, kodboxrPwd); string res = GetKodApiAsync(requestUrl).ToString(); JObject o = (JObject)JToken.Parse(res); this.accessToken = o.Last.Last.ToString(); //var authenticationHeaderValue = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", this.accessToken); //Client.DefaultRequestHeaders.Authorization = authenticationHeaderValue; return res; } //public async Task AwaitLoginAsync(string kodboxUser, string kodboxrPwd) //{ // var requestUrl = $"{kodboxUrl}/?user/index/loginSubmit&name={kodboxUser}&password={kodboxrPwd}"; // string res = await AwaitKodApiAsync(requestUrl); // if (res.StartsWith("")&& res.Contains("出错")) // { // throw new Exception(res); // } // JObject o = (JObject)JToken.Parse(res); // this.accessToken = o.Last.Last.ToString(); // return res; //} /// /// 请求方式:GET 请求地址:http://server/index.php?user/index/logout /// 如果是浏览器: 则用js请求一下退出接口或跳转到改地址即可; 如果纯接口访问: 上述地址追加 &accessToken=xxxx; 则该accessToken失效; /// /// public string Logout(bool @throw) { if (this.accessToken == "" && @throw) { throw new Exception("未登录!"); } var requestUrl = this.kodboxUrl + "/index.php?user/index/logout&accessToken={this.accessToken}"; return GetKodApiAsync(requestUrl).ToString(); } // 获取文件列表 public string GetList(string path) { Dictionary dic = new Dictionary(); dic.Add("path", path); string requestUrl = this.kodboxUrl + "/index.php?explorer/list/path"; return PostKodApi(requestUrl, dic); } /// /// 在指定目录下查找指定类型文件,返回displayPath相符文件的source路径 /// /// 搜索起始目录 /// 文件类型 /// 匹配路径 /// public List GetSourcePath(string rootPath, string fileType, string matchingPath1, string matchingPath2, string matchingPath3, out string searchRes) { List listReturn = new List(); string displaypath = ""; searchRes = ""; string respath = ""; string path = "{search}/"; List list = new List() { "parentPath="+rootPath, "fileType="+fileType //"accessToken="+this.accessToken }; path += String.Join("@", list); Dictionary dic = new Dictionary(); dic.Add("path", path); string requestUrl = this.kodboxUrl + "/index.php?explorer/list/path"; searchRes = PostKodApi(requestUrl, dic); KodboxReturn item = JsonConvert.DeserializeObject(searchRes); if (!item.code) { throw new Exception(item.data.ToString()); } SearchDataIntity data = JsonConvert.DeserializeObject(item.data.ToString()); if (data.fileList.Count == 0) { throw new Exception("目录" + rootPath + "没有类型" + fileType + "文件"); } SearchParentIntity parent = data.searchParent; displaypath = Path.Combine(parent.pathDisplay, matchingPath1); List filelist = data.fileList; foreach (FileIntity info in filelist) { if (info.pathDisplay.StartsWith(displaypath) && info.pathDisplay.Contains(matchingPath2) && info.pathDisplay.Contains(matchingPath3)) { respath = info.path + "|" + info.name + "|" + info.pathDisplay;// displaypath; listReturn.Add(respath); } } if (listReturn.Count == 0) { throw new Exception("文件夹不存在:" + displaypath); } return listReturn; } //public KodSearch GetSourcePath(string rootPath, string fileType, string displaypath) //{ // string path = "{search}/"; // List list = new List() // { // "parentPath="+rootPath, // "fileType="+fileType // }; // path += String.Join("@", list); // Dictionary dic = new Dictionary(); // dic.Add("path", path); // string requestUrl =this.kodboxUrl+"/index.php?explorer/list/path"; // string searchRes = PostKodApi(requestUrl, dic); // KodSearch s = JsonConvert.DeserializeObject(searchRes); // return s; //} //public KodIntity GetSourcePath(string rootPath, string fileType, string displaypath,int i=0) //{ // string path = "{search}/"; // List list = new List() // { // "parentPath="+rootPath, // "fileType="+fileType // }; // path += String.Join("@", list); // Dictionary dic = new Dictionary(); // dic.Add("path", path); // string requestUrl = $"{kodboxUrl}/index.php?explorer/list/path"; // string searchRes = PostKodApi(requestUrl, dic); // KodIntity s = JsonConvert.DeserializeObject(searchRes); // return s; //} //搜索 //path: '{search}/' + param.join('@'); //// 搜索条件参数: //var param = [ //'parentPath', // 选择全部文件夹时为空 //'words', // 搜索关键字 //'sizeFrom', // 大小,单位B //'sizeTo', //'timeFrom', // 时间,格式:2020/02/21 //'timeTo', //'fileType', // 文件类型,根据文件列表获取,参数:path={block:fileType} //'createUser' // userID //] /// /// 下载 /// /// 如{source:255642}/ /// 保存路径,如D:/myDoc/abc /// 123.pdf /// public string DownFile(string source, string savePath, string saveName) { string requestUrl = this.kodboxUrl + "/index.php?explorer/index/fileOut&path={0}&download=1"; requestUrl = string.Format(requestUrl, source); //string requestUrl = $"{kodboxUrl}/index.php?explorer/fileDownload&path={source}"; string msg = ""; bool succ = GetFileFromKod(requestUrl, savePath, saveName, out msg); if (succ) { return "OK"; } return msg; } //16. 文件下载 //请求方式:GET //请求地址:http://server/index.php?explorer/index/fileOut //请求参数:&path={source:1031}/&download=1 internal bool GetFileFromKod(string apiUrl, string filePath, string filename, out string msg) { msg = "OK"; bool suc = false; // FileStream fs; try { Uri uri = new Uri(apiUrl); HttpResponseMessage responseMessage = hClient.GetAsync(uri).Result; if (responseMessage.IsSuccessStatusCode) { if (responseMessage.Content.Headers.ContentType.ToString().Contains("application/json")) { suc = false; var res = responseMessage.Content.ReadAsStringAsync().Result; DownFailInfo dfi = JsonConvert.DeserializeObject(res); msg = "下载文件:" + dfi.data; } else { if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } //如果文件被本地程序占用,无法下载 using (var fs = File.Create(Path.Combine(filePath, filename))) { var streamFromService = responseMessage.Content.ReadAsStreamAsync().Result; streamFromService.CopyTo(fs); } suc = true; } } else { suc = false; msg = responseMessage.StatusCode.ToString(); } //byte[] bytes = XXX.Result; //string res = System.Text.Encoding.UTF8.GetString(bytes); //JObject o = (JObject)JToken.Parse(res); //if (o == null) //{ // throw new Exception("错误请求"); //} //if (o["code"].ToString() == "10001" || o["code"].ToString().ToLower() == "false") //{ // throw new Exception(o["data"].ToString()); //} //using (fs = new FileStream(Path.Combine(filePath, filename), FileMode.Create)) //{ // fs.Write(bytes, 0, bytes.Length); //} } catch (Exception ex) { suc = false; msg = ex.Message; } return suc; } //16. 文件下载 //请求方式:GET //请求地址:http://server/index.php?explorer/index/fileOut //请求参数:&path={source:1031}/&download=1 } public class KodboxReturn { public bool code { get; set; } public string timeUse { get; set; } public string timeNow { get; set; } public object data { get; set; } } public class SearchDataIntity { public object pageInfo { get; set; } public object folderList { get; set; } public List fileList { get; set; } public SearchParentIntity searchParent { get; set; } } public class SearchParentIntity { public string name { get; set; } public string path { get; set; } public string type { get; set; } public string pathDisplay { get; set; } } public class FileIntity { public string name { get; set; } public string path { get; set; } public string type { get; set; } public string ext { get; set; } public string pathDisplay { get; set; } public string parentLevel { get; set; } } public class DownFailInfo { public string code { get; set; } public string timeUse { get; set; } public string timeNow { get; set; } public string data { get; set; } public string info { get; set; } } }