You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DS7/DSWeb/Areas/MvcShipping/DAL/MsOpSeae/MsOpSeaeQDPortDataDAL.cs

709 lines
26 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using qingdaoport;
using DSWeb.MvcShipping.Models.MsOpSeae;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Web;
using System.Web.Script.Serialization;
using AjaxPro;
using DSWeb.MvcShipping.DAL.MsSysParamSet;
using DSWeb.MvcShipping.Models.MsOpSeaeYard;
namespace DSWeb.Areas.MvcShipping.DAL.MsOpSeaeQDPortDataDAL
{
public class MsOpSeaeQDPortDataDAL
{
public string _Cookies
{
get { return GetCookie(); }
set { SaveCookie(value); }
}
string username = MsSysParamSetDAL.GetData("PARAMNAME='QDPORTUSER'").PARAMVALUE;//读取用户名
string password = MsSysParamSetDAL.GetData("PARAMNAME='QDPORTPASS'").PARAMVALUE;//读取密码
string userid = "";
HttpHelper http = new HttpHelper();
public MsOpSeaeQDPortDataDAL(string uid)
{
userid = uid;
}
public bool settleQdportData(string mblno, out string message)
{
string modelMessage = "";
OpSeaeQDPortDataModel model = GetQdportModel(mblno, out modelMessage);
if (model == null)
{
message = modelMessage;
return false;
}
else
{
if (model.success)
{
//进行数据导入
string insertMessage = "";
bool insertResult = InsertQdportDataIntoDB(model, out insertMessage);
message = insertMessage;
return insertResult;
}
else
{
message = modelMessage;
return false;
}
}
}
private bool InsertQdportDataIntoDB(OpSeaeQDPortDataModel model, out string message)
{
message = "";
return false;
}
/// <summary>
///
/// </summary>
/// <param name="blno">提单号</param>
public OpSeaeQDPortDataModel GetQdportModel(string mblno, out string message)
{
string msg = "";
HttpItem item = new HttpItem()
{
URL = "http://track.qingdao-port.net/logistics/wmdp/queryWmdp?tdhType=ZTDH&jckType=NONE&value=" + mblno,
Method = "post",//URL 可选项 默认为Get
ContentType = "/*application/x-www-form-urlencoded*/",//返回类型 可选项有默认值
Postdata = "qtype=pc",//Post要发送的数据
Cookie = _Cookies
};
HttpResult result = http.GetHtml(item);
var obj = JsonConvert.DeserializeObject<OpSeaeQDPortDataModel>(result.Html);
if (obj != null)
{
//获取信息正常
msg = "获取信息正常!";
}
else
{
//未获取到信息
//进行登录操作
string loginState = doLogin();
if (loginState == "登录成功")
{
//重新获取
_Cookies = result.Cookie;
obj = GetQdportModel(mblno, out msg);
}
}
message = obj == null ? "获取失败,请稍后重试!" : (obj.success ? "获取成功" : msg);
return obj;
}
/// <summary>
/// 青岛港单票查询
/// </summary>
/// <param name="tdhType"></param>
/// <param name="jckType"></param>
/// <param name="value"></param>
/// <returns></returns>
public Dictionary<string, OpSeaeQDPortDataModel> GetQdportHttpInfo(string tdhType, string jckType, string value)
{
//SetQdportAccount();
Dictionary<string, OpSeaeQDPortDataModel> dict = new Dictionary<string, OpSeaeQDPortDataModel>();
HttpItem item = new HttpItem
{
URL = "http://track.qingdao-port.net/logistics/wmdp/queryWmdp?tdhType=" + tdhType + "&jckType=" + jckType + "&value=" + value,
Method = "post",//URL
ContentType = "/*application/x-www-form-urlencoded*/",//返回类型
Postdata = "qtype=pc",//Post要发送的数据
Cookie = _Cookies
};
HttpResult result = http.GetHtml(item);
if (result.Html == "")
{
//登陆
string loginState = doLogin();
if (loginState == "登录成功")
{
//_Cookies = result.Cookie;
return GetQdportHttpInfo(tdhType, jckType, value);
}
//登陆失败
dict.Add(loginState, new OpSeaeQDPortDataModel());
return dict;
}
dict.Add("success", JsonConvert.DeserializeObject<OpSeaeQDPortDataModel>(result.Html));
return dict;
}
/// <summary>
/// 单船查询
/// </summary>
/// <param name="vessel"></param>
/// <param name="voyno"></param>
/// <returns></returns>
public Dictionary<string, OpSeaeQdvDataModel> GetQdvHttpInfo(string vessel, string voyno)
{
// SetQdportAccount();
Dictionary<string, OpSeaeQdvDataModel> dict = new Dictionary<string, OpSeaeQdvDataModel>();
HttpItem item = new HttpItem
{
URL = "http://track.qingdao-port.net/logistics/singleship/querySingleShip?YWCM=" + vessel + "&CKHC=" + voyno,
Method = "post",//URL
ContentType = "/*application/x-www-form-urlencoded*/",//返回类型
Postdata = "qtype=pc",//Post要发送的数据
Cookie = _Cookies
};
HttpResult result = http.GetHtml(item);
if (result.Html == "")
{
//登陆
string loginState = doLogin();
if (loginState == "登录成功")
{
//_Cookies = result.Cookie;
return GetQdvHttpInfo(vessel, voyno);
}
//登陆失败
dict.Add(loginState, new OpSeaeQdvDataModel());
return dict;
}
dict.Add("success", JsonConvert.DeserializeObject<OpSeaeQdvDataModel>(result.Html));
return dict;
}
private string doLogin()
{
string message = "";
int cnt = 0;
Boolean ok = false;
Boolean stop = false;
Dictionary<string, bool> dict = new Dictionary<string, bool>();
while (!ok && !stop)
{
if (cnt > 20)
{
message = "登录出现异常:失败次数过多,请稍后再试。";
break;
}
cnt++;
dict = getVerificationCode();
if (!dict.Values.First()) return dict.Keys.First();
HttpItem item = new HttpItem()
{
//URL = "http://www.qingdao-port.net/market/login.do",//URL 必需项
URL = "https://www.qingdao-port.net/ygt/api/sso/login.do",
Method = "post",//URL 可选项 默认为Get
ContentType = "application/x-www-form-urlencoded",//返回类型 可选项有默认值
Postdata = "userName=" + username + "&passWord=" + password + "&code=" + dict.Keys.First(),//Post要发送的数据
Cookie = _Cookies
};
HttpResult result = http.GetHtml(item);
string html = result.Html;
JObject jo = (JObject)JsonConvert.DeserializeObject(html);
if (jo["success"].ToString().ToLower() == "true")
{
message = "登录成功";
//_Cookies = result.Cookie;
ok = true;
}
else
{
if (!jo["msg"].ToString().Contains("图片验证码输入错误,请重新输入"))
{
stop = true;
}
message = jo["msg"].ToString();
}
}
return message;
}
public Dictionary<string, bool> getVerificationCode()
{
Dictionary<string, bool> dict = new Dictionary<string, bool>();
HttpItem item = new HttpItem()
{
//URL = "http://www.qingdao-port.net/market/getKaptchaImage.do?timestamp=" + ConvertDateTimeInt(DateTime.Now),
URL = "https://www.qingdao-port.net/ygt/api/safe/captcha.do?" + ConvertDateTimeInt(DateTime.Now),
Method = "get",//URL 可选项 默认为Get
ResultType = ResultType.Byte
};
HttpResult result = http.GetHtml(item);
_Cookies = result.Cookie;
Bitmap bitmap = BytesToBitmap(result.ResultByte);
//bitmap = unNoise(bitmap, 0);
Bitmap bm2 = new Bitmap(bitmap.Width, bitmap.Height);
Graphics g = Graphics.FromImage(bm2);
g.DrawImageUnscaled(bitmap, 0, 0);
string guid = Guid.NewGuid().ToString();
string path = HttpRuntime.AppDomainAppPath.ToString() + "qdporttemp\\";
string filename = path + guid + ".png";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
bm2.Save(filename);
//调用百度云文字识别
OcrDemo ocr = new OcrDemo();
JToken o = ocr.GeneralBasic(filename);
var errorMsg = o.Value<string>("error_msg");
var wordsNum = o.Value<int>("words_result_num");
if (String.IsNullOrEmpty(errorMsg))
{
if (wordsNum > 0)
{
var txts = from p in (JArray)o.Root["words_result"] select (string)p["words"];
//Regex r = new Regex(@"^\d{1,3}\s*[\+-×÷X]\s*\d{1,3}$");//匹配 计算表达式
string words = txts.First();
//if (r.IsMatch(words))
if (words.Length == 4)
{
//Regex aReg = new Regex(@"\d{1,3}(?=\s*[\+-×÷X])");
//Regex bReg = new Regex(@"(?<=[\+-×÷X]\s*)\d{1,3}");
//Regex opReg = new Regex(@"(?<=\d{1,3}\s*)[\+-×÷X](?=\s*\d{1,3})");
//var a = Convert.ToInt32(aReg.Match(words).Value);//第一个参数
//var b = Convert.ToInt32(bReg.Match(words).Value);//第二个参数
//var op = opReg.Match(words).Value;//操作符
//int c;
//switch (op)
//{
// case "+"://加法运算
// c = a + b;
// break;
// case "-"://减法运算
// c = a - b;
// break;
// case "÷"://除法运算
// if (b == 0) return getVerificationCode();
// c = a / b;
// break;
// default: //乘法运算
// c = a * b;
// break;
//}
//dict.Add(c.ToString(), true);
dict.Add(words.ToString(), true);
File.Delete(filename);
return dict;
}
else
{
File.Delete(filename);
return getVerificationCode();
}
}
return getVerificationCode();
}
dict.Add(errorMsg, false);
return dict;
}
/// <summary>
/// 珉钧场站验证码破解
/// </summary>
public Dictionary<string, string> getVerificationCodebygdv(int times, string url)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
HttpItem item = new HttpItem
{
URL = url + "?t=" + ConvertDateTimeInt(DateTime.Now),
Method = "get",//URL 可选项 默认为Get
ResultType = ResultType.Byte
};
HttpResult result = http.GetHtml(item);
Bitmap bitmap = BytesToBitmap(result.ResultByte);
bitmap = unNoise(bitmap, 1);
Bitmap bm2 = new Bitmap(bitmap.Width, bitmap.Height);
Graphics g = Graphics.FromImage(bm2);
g.DrawImageUnscaled(bitmap, 0, 0);
string guid = Guid.NewGuid().ToString();
string path = HttpRuntime.AppDomainAppPath.ToString() + "qdporttemp\\";
string filename = path + guid + ".png";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
bm2.Save(filename);
OcrDemo ocr = new OcrDemo();
JToken obj = ocr.GeneralBasicDemo(filename);
File.Delete(filename);//删除本地文件
var errorCode = obj.Value<int?>("error_code");//请求错误返回错误码17每日请求量超限额
if (errorCode == null)
{
var wordsNum = obj.Value<int>("words_result_num");
if (wordsNum > 0)
{
var txts = from o in (JArray)obj.Root["words_result"] select (string)o["words"];
Regex r = new Regex(@"^[a-zA-Z0-9]{4}$");
if (r.IsMatch(txts.First()))
{
dict.Add(txts.First(), result.Cookie);
return dict;
}
}
if (times < 7)
return getVerificationCodebygdv(times++, url);
return dict;
}
dict.Add(errorCode.ToString(), result.Cookie);
return dict;
}
#region 图像处理部分
public static long ConvertDateTimeInt(System.DateTime time)
{
//double intResult = 0;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
//intResult = (time- startTime).TotalMilliseconds;
long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
return t;
}
public static Bitmap BytesToBitmap(byte[] Bytes)
{
MemoryStream stream = null;
try
{
stream = new MemoryStream(Bytes);
return new Bitmap((Image)new Bitmap(stream));
}
catch (ArgumentNullException ex)
{
throw ex;
}
catch (ArgumentException ex)
{
throw ex;
}
finally
{
stream.Close();
}
}
public Bitmap unNoise(Bitmap bmpOut, int type)
{
UnCodebase imageNoise = new UnCodebase(bmpOut);
//灰度处理
bmpOut = imageNoise.ToGray();
imageNoise = new UnCodebase(bmpOut);
//得到阈值
int grayvalue = imageNoise.GetDgGrayValue();
//降噪
if (type == 0)
bmpOut = imageNoise.ClearNoise(grayvalue);
else
bmpOut = imageNoise.ClearNoise(grayvalue, 3);
imageNoise = new UnCodebase(bmpOut);
bmpOut = imageNoise.ConvertTo1Bpp1();
imageNoise = new UnCodebase(bmpOut);
bmpOut = imageNoise.Sharpen(1);
return bmpOut;
}
#endregion
private void SaveCookie(string cookie)
{
//更新
string sql = @"update Op_QdPortCookies set cookie = '" + cookie + "'";
Database db = DatabaseFactory.CreateDatabase();
int flag = db.ExecuteNonQuery(CommandType.Text, sql);
if (flag == 0)
{
//添加
string sql2 = @"insert into Op_QdPortCookies (cookie) values ('" + cookie + "')";
db.ExecuteNonQuery(CommandType.Text, sql2);
}
}
private static string GetCookie()
{
string sql = @"select top 1 cookie from Op_QdPortCookies order by updatetime desc";
Database db = DatabaseFactory.CreateDatabase();
if (db.ExecuteScalar(CommandType.Text, sql) == null) return "";
return db.ExecuteScalar(CommandType.Text, sql).ToString();
}
public static bool CheckQdAccountSetting(string userid)
{
//string sql = "select QdPortUserName,QdPortPassword from user_baseinfo where userid='" + userid + "'";
//Database db = DatabaseFactory.CreateDatabase();
string qduname = MsSysParamSetDAL.GetData("PARAMNAME='QDPORTUSER'").PARAMVALUE; ;
string qdpwd = MsSysParamSetDAL.GetData("PARAMNAME='QDPORTPASS'").PARAMVALUE; ;
//using (IDataReader reader = db.ExecuteReader(CommandType.Text, sql))
//{
// while (reader.Read())
// {
// qduname = reader["QdPortUserName"].ToString();
// qdpwd = reader["QdPortPassword"].ToString();
// }
//}
if (qduname == "" || qdpwd == "")
{
return false;
}
else
{
return true;
}
}
private void SetQdportAccount()
{
/*
string sql = "select * from user_baseinfo where userid= '" + userid + "'";
Database db = DatabaseFactory.CreateDatabase();
string qduname = "";
string qdpwd = "";
using (IDataReader reader = db.ExecuteReader(CommandType.Text, sql))
{
while (reader.Read())
{
username = reader["QdPortUserName"].ToString();
password = reader["QdPortPassword"].ToString();
}
}
*/
username = MsSysParamSetDAL.GetData("PARAMNAME='QDPORTUSER'").PARAMVALUE;//读取用户名
password = MsSysParamSetDAL.GetData("PARAMNAME='QDPORTPASS'").PARAMVALUE;//读取密码
}
/// <summary>
/// 青岛港--长荣出口提单查询
/// </summary>
/// <param name="mblno"></param>
/// <returns></returns>
public List<string> GetCRYard(string mblno)
{
//SetQdportAccount();
List<string> result = new List<string>();
HttpItem itemJgxx = new HttpItem
{
URL = "http://track.qingdao-port.net/logistics/crstation/queryJgxx?tdh=" + mblno,
Method = "post",//URL
ContentType = "/*application/x-www-form-urlencoded*/",//返回类型
//Postdata = "tdh" + mblno,//Post要发送的数据
Postdata = "qtype=pc",
Cookie = _Cookies
};
HttpResult resultJgxx = http.GetHtml(itemJgxx);
HttpItem itemZhxx = new HttpItem
{
URL = "http://track.qingdao-port.net/logistics/crstation/querySjzh?tdh=" + mblno,
Method = "post",//URL
ContentType = "/*application/x-www-form-urlencoded*/",//返回类型
//Postdata = "tdh" + mblno,//Post要发送的数据
Postdata = "qtype=pc",
Cookie = _Cookies
};
HttpResult resultZhxx = http.GetHtml(itemZhxx);
HttpItem itemXhdt = new HttpItem
{
URL = "http://track.qingdao-port.net/logistics/crstation/queryXhdt?tdh=" + mblno,
Method = "post",//URL
ContentType = "/*application/x-www-form-urlencoded*/",//返回类型
//Postdata = "tdh" + mblno,//Post要发送的数据
Postdata = "qtype=pc",
Cookie = _Cookies
};
HttpResult resultXhdt = http.GetHtml(itemXhdt);
//if ((resultJgxx.Html == "") || (resultXhdt.Html == "") || (resultZhxx.Html == ""))
if (resultJgxx.Html == "")
{
//登陆
string loginState = doLogin();
if (loginState == "登录成功")
{
//_Cookies = result.Cookie;
return GetCRYard(mblno);
}
//登陆失败
return (result);
}
result.Add(resultJgxx.Html);
result.Add(resultXhdt.Html);
result.Add(resultZhxx.Html);
return result;
}
/// <summary>
/// 青岛港--长荣出口提单查询--集港信息
/// </summary>
/// <param name="mblno"></param>
/// <returns></returns>
public OpSeaeJGXX_CRModel GetCRYardJgxx(string mblno)
{
SetQdportAccount();
HttpItem item = new HttpItem
{
URL = "http://track.qingdao-port.net/logistics/crstation/queryJgxx?tdh=" + mblno,
Method = "post",//URL
ContentType = "/*application/x-www-form-urlencoded*/",//返回类型
//Postdata = "tdh" + mblno,//Post要发送的数据
Postdata = "qtype=pc",
Cookie = _Cookies
};
HttpResult result = http.GetHtml(item);
if (result.Html == "")
{
//登陆
string loginState = doLogin();
if (loginState == "登录成功")
{
//_Cookies = result.Cookie;
return GetCRYardJgxx(mblno);
}
//登陆失败
return (new OpSeaeJGXX_CRModel());
}
return JsonConvert.DeserializeObject<OpSeaeJGXX_CRModel>(result.Html);
}
/// <summary>
/// 青岛港--长荣出口提单查询--实际装货
/// </summary>
/// <param name="mblno"></param>
/// <returns></returns>
public OpSeaeZHXX_CRModel GetCRYardZhxx(string mblno)
{
SetQdportAccount();
HttpItem item = new HttpItem
{
URL = "http://track.qingdao-port.net/logistics/crstation/querySjzh?tdh=" + mblno,
Method = "post",//URL
ContentType = "/*application/x-www-form-urlencoded*/",//返回类型
//Postdata = "tdh" + mblno,//Post要发送的数据
Postdata = "qtype=pc",
Cookie = _Cookies
};
HttpResult result = http.GetHtml(item);
if (result.Html == "")
{
//登陆
string loginState = doLogin();
if (loginState == "登录成功")
{
//_Cookies = result.Cookie;
return GetCRYardZhxx(mblno);
}
//登陆失败
return (new OpSeaeZHXX_CRModel());
}
return JsonConvert.DeserializeObject<OpSeaeZHXX_CRModel>(result.Html);
}
/// <summary>
/// 青岛港--长荣出口提单查询--箱货动态
/// </summary>
/// <param name="mblno"></param>
/// <returns></returns>
public OpSeaeXHDT_CRModel GetCRYardXhdt(string mblno)
{
SetQdportAccount();
HttpItem item = new HttpItem
{
URL = "http://track.qingdao-port.net/logistics/crstation/queryXhdt?tdh=" + mblno,
Method = "post",//URL
ContentType = "/*application/x-www-form-urlencoded*/",//返回类型
//Postdata = "tdh" + mblno,//Post要发送的数据
Postdata = "qtype=pc",
Cookie = _Cookies
};
HttpResult result = http.GetHtml(item);
if (result.Html == "")
{
//登陆
string loginState = doLogin();
if (loginState == "登录成功")
{
//_Cookies = result.Cookie;
return GetCRYardXhdt(mblno);
}
//登陆失败
return (new OpSeaeXHDT_CRModel());
}
return JsonConvert.DeserializeObject<OpSeaeXHDT_CRModel>(result.Html);
}
/// <summary>
/// 青岛港--港联荣提单查询
/// </summary>
/// <param name="mblno"></param>
/// <returns></returns>
public OpSeaeGLRModel GetGLRYardXhdt(string mblno)
{
//SetQdportAccount();
HttpItem item = new HttpItem
{
URL = "http://track.qingdao-port.net/logistics/mtsearch/glrcz?searchval=" + mblno,
Method = "post",//URL
ContentType = "/*application/x-www-form-urlencoded*/",//返回类型
Postdata = "qtype=pc",
Cookie = _Cookies
};
HttpResult result = http.GetHtml(item);
if (result.Html == "")
{
//登陆
string loginState = doLogin();
if (loginState == "登录成功")
{
//_Cookies = result.Cookie;
return GetGLRYardXhdt(mblno);
}
//登陆失败
return (new OpSeaeGLRModel());
}
return JsonConvert.DeserializeObject<OpSeaeGLRModel>(result.Html);
}
}
}