锐腾搅拌上料功能
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

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();
}
}
/// <summary>
/// GET请求可道云,返回json字符串
/// </summary>
/// <param name="apiUrl">请求地址</param>
/// <returns>json</returns>
internal string GetKodApiAsync(string apiUrl)
{
var res = hClient.GetStringAsync(apiUrl);
return res.Result;
}
//internal async Task<string> 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;
// }
//}
/// <summary>
/// POST请求可道云,返回json字符串
/// </summary>
/// <param name="apiUrl">请求地址</param>
/// <param name="dic">参数字典</param>
/// <returns></returns>
internal string PostKodApi(string apiUrl, Dictionary<string, string> 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;
}
/// <summary>
/// 请求方式:GET;
/// 请求地址:http://server/?user/index/loginSubmit&name=[用户名]&password=[密码]
/// 返回结果:
/// {
/// "code": true,
/// "use_time": 0.009,
/// "data": "ok",
/// "info": "ad947n9kDU6nr1V22j7MewCHNWCrZ0GgMDnNyzjv2y58YImivhggVsZ4Xg" //accessToken;
/// }
/// </summary>
/// <returns></returns>
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<string> AwaitLoginAsync(string kodboxUser, string kodboxrPwd)
//{
// var requestUrl = $"{kodboxUrl}/?user/index/loginSubmit&name={kodboxUser}&password={kodboxrPwd}";
// string res = await AwaitKodApiAsync(requestUrl);
// if (res.StartsWith("<html>")&& res.Contains("出错"))
// {
// throw new Exception(res);
// }
// JObject o = (JObject)JToken.Parse(res);
// this.accessToken = o.Last.Last.ToString();
// return res;
//}
/// <summary>
/// 请求方式:GET 请求地址:http://server/index.php?user/index/logout
/// 如果是浏览器: 则用js请求一下退出接口或跳转到改地址即可; 如果纯接口访问: 上述地址追加 &accessToken=xxxx; 则该accessToken失效;
/// </summary>
/// <returns></returns>
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<string, string> dic = new Dictionary<string, string>();
dic.Add("path", path);
string requestUrl = this.kodboxUrl + "/index.php?explorer/list/path";
return PostKodApi(requestUrl, dic);
}
/// <summary>
/// 在指定目录下查找指定类型文件,返回displayPath相符文件的source路径
/// </summary>
/// <param name="rootPath">搜索起始目录</param>
/// <param name="fileType">文件类型</param>
/// <param name="matchingPath1">匹配路径</param>
/// <returns></returns>
public List<string> GetSourcePath(string rootPath, string fileType, string matchingPath1, string matchingPath2, string matchingPath3, out string searchRes)
{
List<string> listReturn = new List<string>();
string displaypath = "";
searchRes = "";
string respath = "";
string path = "{search}/";
List<string> list = new List<string>()
{
"parentPath="+rootPath,
"fileType="+fileType
//"accessToken="+this.accessToken
};
path += String.Join("@", list);
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("path", path);
string requestUrl = this.kodboxUrl + "/index.php?explorer/list/path";
searchRes = PostKodApi(requestUrl, dic);
KodboxReturn item = JsonConvert.DeserializeObject<KodboxReturn>(searchRes);
if (!item.code)
{
throw new Exception(item.data.ToString());
}
SearchDataIntity data = JsonConvert.DeserializeObject<SearchDataIntity>(item.data.ToString());
if (data.fileList.Count == 0)
{
throw new Exception("目录" + rootPath + "没有类型" + fileType + "文件");
}
SearchParentIntity parent = data.searchParent;
displaypath = Path.Combine(parent.pathDisplay, matchingPath1);
List<FileIntity> 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<string> list = new List<string>()
// {
// "parentPath="+rootPath,
// "fileType="+fileType
// };
// path += String.Join("@", list);
// Dictionary<string, string> dic = new Dictionary<string, string>();
// dic.Add("path", path);
// string requestUrl =this.kodboxUrl+"/index.php?explorer/list/path";
// string searchRes = PostKodApi(requestUrl, dic);
// KodSearch s = JsonConvert.DeserializeObject<KodSearch>(searchRes);
// return s;
//}
//public KodIntity GetSourcePath(string rootPath, string fileType, string displaypath,int i=0)
//{
// string path = "{search}/";
// List<string> list = new List<string>()
// {
// "parentPath="+rootPath,
// "fileType="+fileType
// };
// path += String.Join("@", list);
// Dictionary<string, string> dic = new Dictionary<string, string>();
// dic.Add("path", path);
// string requestUrl = $"{kodboxUrl}/index.php?explorer/list/path";
// string searchRes = PostKodApi(requestUrl, dic);
// KodIntity s = JsonConvert.DeserializeObject<KodIntity>(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
//]
/// <summary>
/// 下载
/// </summary>
/// <param name="source">如{source:255642}/</param>
/// <param name="savePath">保存路径,如D:/myDoc/abc</param>
/// <param name="saveName">123.pdf</param>
/// <returns></returns>
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<DownFailInfo>(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<FileIntity> 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; }
}
}