HUB11X5Job.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Quartz;
  6. using SCC.Common;
  7. using SCC.Models;
  8. using SCC.Interface;
  9. using HtmlAgilityPack;
  10. using Newtonsoft.Json;
  11. using Newtonsoft.Json.Linq;
  12. namespace SCC.Crawler.GP
  13. {
  14. /// <summary>
  15. /// 数据爬取类
  16. /// 湖北11选5
  17. /// </summary>
  18. [DisallowConcurrentExecution]
  19. [PersistJobDataAfterExecution]
  20. public class HUB11X5Job : IJob
  21. {
  22. /// <summary>
  23. /// 构造函数
  24. /// </summary>
  25. public HUB11X5Job()
  26. {
  27. log = new LogHelper();
  28. services = IOC.Resolve<IOpen5Code>();
  29. email = IOC.Resolve<IEmail>();
  30. }
  31. /// <summary>
  32. /// 作业执行入口
  33. /// </summary>
  34. /// <param name="context">作业执行上下文</param>
  35. public void Execute(IJobExecutionContext context)
  36. {
  37. Config = CommonHelper.GetConfigFromDataMap(context.JobDetail.JobDataMap);
  38. //预设节假日不开奖
  39. if (Config.SkipDate.Contains(CommonHelper.SCCSysDateTime.ToString("yyyyMMdd"))) return;
  40. LatestQiHao = context.JobDetail.JobDataMap.GetString("LatestQiHao");
  41. try
  42. {
  43. //服务启动时配置初始数据
  44. if (string.IsNullOrEmpty(LatestQiHao))
  45. {
  46. var lastItem = services.GetLastItem(currentLottery);
  47. if (lastItem != null)
  48. {
  49. LatestQiHao = lastItem.Term.ToString();
  50. }
  51. }
  52. //第一次启动服务或最新期号为昨天的开奖期号,则自检昨天开奖数据是否抓取完毕(否则插入邮件数据),并重置当天期号和失败列表
  53. if (string.IsNullOrEmpty(LatestQiHao) || !LatestQiHao.StartsWith(CommonHelper.SCCSysDateTime.ToString("yyMMdd")))
  54. {
  55. CheckingYesterdayTheLotteryData();
  56. LatestQiHao = CommonHelper.GenerateTodayQiHaoYYMMDDQQ(0);
  57. }
  58. //当最新期号不符合当天总期数,执行当天作业
  59. if (Convert.ToInt32(LatestQiHao.Substring(6)) != Config.TimesPerDay)
  60. {
  61. DoTodayJobByDB();
  62. DoTodayJobByMainUrl();
  63. DoTodayJobByBackUrl();
  64. }
  65. }
  66. catch (Exception ex)
  67. {
  68. log.Error(typeof(HUB11X5Job), string.Format("【{0}】抓取时发生错误,错误信息【{1}】", Config.Area + Config.LotteryName, ex.Message));
  69. }
  70. //保存最新期号和失败期号列表
  71. context.JobDetail.JobDataMap["LatestQiHao"] = LatestQiHao;
  72. }
  73. /// <summary>
  74. /// 通过数据库获取开奖数据
  75. /// </summary>
  76. private void DoTodayJobByDB()
  77. {
  78. var OpenList = services.GetYesterdayFailQQListDB5_toDay(currentLottery, Config.TimesPerDay);
  79. if (OpenList.Count == 0) return;//无抓取数据
  80. var newestQiHao = OpenList.OrderBy(a => a.Key).Last().Key;
  81. var startQiNum = Convert.ToInt32(LatestQiHao.Substring(6)) + 1;
  82. var newestQiNum = Convert.ToInt32(newestQiHao.Substring(6));
  83. if (startQiNum > newestQiNum) return;//无最新数据
  84. //处理最新开奖数据
  85. string getQiHao = string.Empty;
  86. for (var i = startQiNum; i <= newestQiNum; i++)
  87. {
  88. getQiHao = CommonHelper.GenerateTodayQiHaoYYMMDDQQ(i);
  89. var matchItem = OpenList.Where(R => R.Key == getQiHao).FirstOrDefault();
  90. if (matchItem.Key != null && SaveRecord(getQiHao, matchItem.Value, false))
  91. {
  92. //处理成功写入日志
  93. log.Info(typeof(ZJ11X5Job), CommonHelper.GetJobMainLogInfo(Config, getQiHao));
  94. LatestQiHao = getQiHao;
  95. }
  96. }
  97. }
  98. /// <summary>
  99. /// 自检昨天开奖数据
  100. /// </summary>
  101. private void CheckingYesterdayTheLotteryData()
  102. {
  103. if (Config.SkipDate.Contains(CommonHelper.SCCSysDateTime.AddDays(-1).ToString("yyyyMMdd"))) return;//如果昨日设定不开奖则不自检昨日开奖数据
  104. //从数据库中获取昨天数据抓取失败列表
  105. FailedQiHaoList = services.GetYesterdayFailQQList(currentLottery, Config.TimesPerDay);
  106. if (FailedQiHaoList.Count > 0)
  107. {
  108. DoYesterdayFailedListByMainUrl();
  109. DoYesterdayFailedListByBackUrl();
  110. foreach (var fQiHao in FailedQiHaoList)
  111. {
  112. //将抓取失败数据推送至邮件列表,待邮件服务发送至配置管理员的邮箱中
  113. if (email.AddEmail(Config.Area + Config.LotteryName, fQiHao, CommonHelper.GenerateYesterdayOpenTime(Config, fQiHao)))
  114. log.Error(typeof(HUB11X5Job), CommonHelper.GetJobLogError(Config, fQiHao));
  115. }
  116. }
  117. }
  118. /// <summary>
  119. /// 通过主站点抓取开奖数据
  120. /// (湖北体彩官网)
  121. /// </summary>
  122. private void DoTodayJobByMainUrl()
  123. {
  124. if (!string.IsNullOrEmpty(Config.MainUrl))
  125. {
  126. var OpenList = GetOpenListFromMainUrl();
  127. if (OpenList.Count == 0) return;//无抓取数据
  128. var newestQiHao = OpenList.First().Key;
  129. var startQiNum = Convert.ToInt32(LatestQiHao.Substring(6)) + 1;
  130. var newestQiNum = Convert.ToInt32(newestQiHao.Substring(6));
  131. if (startQiNum > newestQiNum) return;//无最新数据
  132. //处理最新开奖数据
  133. string getQiHao = string.Empty;
  134. for (var i = startQiNum; i <= newestQiNum; i++)
  135. {
  136. getQiHao = CommonHelper.GenerateTodayQiHaoYYMMDDQQ(i);
  137. var matchItem = OpenList.Where(R => R.Key == getQiHao).FirstOrDefault();
  138. if (matchItem.Key != null && SaveRecord(getQiHao, matchItem.Value, false))
  139. {
  140. //处理成功写入日志
  141. log.Info(typeof(HUB11X5Job), CommonHelper.GetJobMainLogInfo(Config, getQiHao));
  142. LatestQiHao = getQiHao;
  143. }
  144. }
  145. //foreach (KeyValuePair<string, string> pair in OpenList)
  146. //{
  147. // if (pair.Key != null && SaveRecord(pair.Key, pair.Value, false))
  148. // {
  149. // 处理成功写入日志
  150. // log.Info(typeof(HUB11X5Job), CommonHelper.GetJobMainLogInfo(Config, getQiHao));
  151. // LatestQiHao = pair.Key;
  152. // }
  153. //}
  154. }
  155. }
  156. /// <summary>
  157. /// 通过主站抓取错误期号列表中每一个期号
  158. /// (湖北体彩官网)
  159. /// </summary>
  160. private void DoYesterdayFailedListByMainUrl()
  161. {
  162. if (!string.IsNullOrEmpty(Config.MainUrl) && FailedQiHaoList.Count > 0)
  163. {
  164. var OpenList = GetOpenListFromMainUrl(false);
  165. if (OpenList.Count == 0) return;//无抓取数据
  166. var SuccessList = new List<string>();
  167. foreach (string failedQiHao in FailedQiHaoList)
  168. {
  169. var matchItem = OpenList.Where(R => R.Key == failedQiHao).FirstOrDefault();
  170. if (matchItem.Key != null && SaveRecord(failedQiHao, matchItem.Value, true))
  171. {
  172. //处理成功写入日志
  173. log.Info(typeof(HUB11X5Job), CommonHelper.GetJobMainLogInfo(Config, failedQiHao));
  174. SuccessList.Add(failedQiHao);
  175. continue;
  176. }
  177. }
  178. foreach (var successQiHao in SuccessList)
  179. {
  180. FailedQiHaoList.Remove(successQiHao);
  181. }
  182. }
  183. }
  184. /// <summary>
  185. /// 抓取主站点开奖数据
  186. /// </summary>
  187. /// <returns></returns>
  188. private Dictionary<string, string> GetOpenListFromMainUrl(bool isToday = true)
  189. {
  190. Dictionary<string, string> result = new Dictionary<string, string>();
  191. try
  192. {
  193. #region 废弃代码 BY 大师兄
  194. //string requestUrl = string.Empty;
  195. //for (var k = 1; k <= 2; k++)
  196. //{
  197. // requestUrl = string.Format("{0}&startIssue=&endIssue=&pageNo={1}&pageNum=81&format=jsonp&callback=?", Config.MainUrl, k);
  198. // var HtmlResource = NetHelper.GetHUB11X5UrlResponse(requestUrl);
  199. // if (!string.IsNullOrWhiteSpace(HtmlResource))
  200. // {
  201. // var obj = JsonConvert.DeserializeObject<JObject>(HtmlResource.Replace("?", string.Empty).Replace("(", string.Empty).Replace(")", string.Empty));
  202. // if (obj != null && obj["data"] != null && obj["data"]["numberList"] != null)
  203. // {
  204. // var matchQiHao = string.Empty;
  205. // var matchKJHaoMa = string.Empty;
  206. // foreach (JObject objchild in obj["data"]["numberList"])
  207. // {
  208. // if (objchild["issueNum"] == null || string.IsNullOrWhiteSpace(objchild["issueNum"].ToString()) || objchild["baseCode"] == null || string.IsNullOrWhiteSpace(objchild["baseCode"].ToString())) continue;
  209. // matchQiHao = objchild["issueNum"].ToString().Trim();
  210. // matchKJHaoMa = objchild["baseCode"].ToString().Trim();
  211. // if (!result.ContainsKey(matchQiHao))
  212. // result.Add(matchQiHao, matchKJHaoMa);
  213. // }
  214. // }
  215. // }
  216. //}
  217. #endregion
  218. var HtmlResource = NetHelper.GetUrlResponse(string.Format(Config.MainUrl, !isToday ? "/day/2" : "/num/50")); //Config.MainUrl
  219. if (HtmlResource == null) return null;
  220. var doc = new HtmlDocument();
  221. doc.LoadHtml(HtmlResource);
  222. var rootnode = doc.DocumentNode;
  223. var xpath = "//*[@id=\"ZstTable\"]/tbody/[@class=\"datainfo\"]";
  224. var xpath2 = "//*[@id=\"ZstTable\"]";
  225. var collection = rootnode.SelectNodes(xpath2);
  226. var data = collection[0].ChildNodes;
  227. for (var i = 0; i < data.Count; i++)
  228. {
  229. if (data[i].GetAttributeValue("class", " ") == "datainfo")
  230. {
  231. var periodnum = data[i].ChildNodes[0].InnerText.Trim();
  232. var code1 = data[i].ChildNodes[1].InnerText.Trim();
  233. var code2 = data[i].ChildNodes[2].InnerText.Trim();
  234. var code3 = data[i].ChildNodes[3].InnerText.Trim();
  235. var code4 = data[i].ChildNodes[4].InnerText.Trim();
  236. var code5 = data[i].ChildNodes[5].InnerText.Trim();
  237. result.Add(periodnum, string.Format("{0},{1},{2},{3},{4}", code1, code2,
  238. code3, code4, code5));
  239. }
  240. }
  241. }
  242. catch (Exception ex)
  243. {
  244. log.Error(typeof(HUB11X5Job), string.Format("【{0}】通过主站点抓取开奖列表时发生错误,错误信息【{1}】", Config.Area + Config.LotteryName, ex.Message));
  245. }
  246. return result;
  247. }
  248. /// <summary>
  249. /// 通过备用站点抓取开奖数据
  250. /// (爱彩乐)
  251. /// </summary>
  252. private void DoTodayJobByBackUrl()
  253. {
  254. if (!string.IsNullOrEmpty(Config.BackUrl))
  255. {
  256. var OpenList = GetTodayOpenListFromBackUrl();
  257. if (OpenList.Count == 0) return;//无抓取数据
  258. var newestQiHao = OpenList.Last().Key;
  259. var startQiNum = Convert.ToInt32(LatestQiHao.Substring(6)) + 1;
  260. var newestQiNum = Convert.ToInt32(newestQiHao.Substring(6));
  261. if (startQiNum > newestQiNum) return;//无最新数据
  262. //处理最新开奖数据
  263. var getQiHao = string.Empty;
  264. for (var i = startQiNum; i <= newestQiNum; i++)
  265. {
  266. getQiHao = CommonHelper.GenerateTodayQiHaoYYMMDDQQ(i);
  267. var matchItem = OpenList.Where(R => R.Key == getQiHao).FirstOrDefault();
  268. if (matchItem.Key != null && SaveRecord(getQiHao, matchItem.Value, false))
  269. {
  270. //处理成功写入日志
  271. log.Info(typeof(HUB11X5Job), CommonHelper.GetJobBackLogInfo(Config, getQiHao));
  272. LatestQiHao = getQiHao;
  273. }
  274. }
  275. }
  276. }
  277. /// <summary>
  278. /// 通过备用地址抓取错误期号列表中每一个期号
  279. /// (爱彩乐)
  280. /// </summary>
  281. private void DoYesterdayFailedListByBackUrl()
  282. {
  283. if (!string.IsNullOrEmpty(Config.BackUrl) && FailedQiHaoList.Count > 0)
  284. {
  285. var OpenList = GetYesterdayOpenListFromBackUrl();
  286. if (OpenList.Count == 0) return;//无抓取数据
  287. var SuccessList = new List<string>();
  288. foreach (var failedQiHao in FailedQiHaoList)
  289. {
  290. var matchItem = OpenList.Where(R => R.Key == failedQiHao).FirstOrDefault();
  291. if (matchItem.Key != null && SaveRecord(failedQiHao, matchItem.Value, true))
  292. {
  293. //处理成功写入日志
  294. log.Info(typeof(HUB11X5Job), CommonHelper.GetJobBackLogInfo(Config, failedQiHao));
  295. SuccessList.Add(failedQiHao);
  296. continue;
  297. }
  298. }
  299. foreach (var successQiHao in SuccessList)
  300. {
  301. FailedQiHaoList.Remove(successQiHao);
  302. }
  303. }
  304. }
  305. /// <summary>
  306. /// 通过备用站点抓取今日最新开奖列表
  307. /// </summary>
  308. /// <returns></returns>
  309. private Dictionary<string, string> GetTodayOpenListFromBackUrl()
  310. {
  311. Dictionary<string, string> result = new Dictionary<string, string>();
  312. try
  313. {
  314. var HtmlResource = NetHelper.GetUrlResponse(Config.BackUrl);
  315. if (!string.IsNullOrWhiteSpace(HtmlResource))
  316. {
  317. HtmlDocument doc = new HtmlDocument();
  318. doc.LoadHtml(HtmlResource);
  319. var table = doc.DocumentNode.SelectSingleNode("//table");
  320. if (table == null) return result;
  321. var trs = table.ChildNodes.Where(R => R.Name.ToLower() == "tr").ToList();
  322. List<HtmlNode> tds = null, ems = null;
  323. var matchQiHao = string.Empty;
  324. var matchKJHaoMa = string.Empty;
  325. for (var i = 1; i < trs.Count; i++)//第一行为表头
  326. {
  327. tds = trs[i].ChildNodes.Where(R => R.Name.ToLower() == "td").ToList();
  328. if (tds.Count < 3) continue;
  329. matchQiHao = tds[0].InnerText.Trim();
  330. ems = tds[2].ChildNodes.Where(R => R.Name.ToLower() == "em").ToList();
  331. if (ems.Count < 5) continue;
  332. matchKJHaoMa = string.Format("{0},{1},{2},{3},{4}", ems[0].InnerText.Trim(), ems[1].InnerText.Trim(), ems[2].InnerText.Trim(), ems[3].InnerText.Trim(), ems[4].InnerText.Trim());
  333. if (!result.ContainsKey(matchQiHao))
  334. result.Add(matchQiHao, matchKJHaoMa);
  335. }
  336. }
  337. }
  338. catch (Exception ex)
  339. {
  340. log.Error(typeof(HUB11X5Job), string.Format("【{0}】通过备用站点抓取今日最新开奖列表时发生错误,错误信息【{1}】", Config.Area + Config.LotteryName, ex.Message));
  341. }
  342. return result;
  343. }
  344. /// <summary>
  345. /// 通过备用站点抓取昨日开奖列表
  346. /// </summary>
  347. /// <returns></returns>
  348. private Dictionary<string, string> GetYesterdayOpenListFromBackUrl()
  349. {
  350. Dictionary<string, string> result = new Dictionary<string, string>();
  351. try
  352. {
  353. var HtmlResource = NetHelper.GetUrlResponse(Config.BackUrl + "?action=chart&date=yesterday&id=520&async=true");
  354. if (!string.IsNullOrWhiteSpace(HtmlResource))
  355. {
  356. var obj = JsonConvert.DeserializeObject<JObject>(HtmlResource);
  357. if (obj != null && obj["data"] != null)
  358. {
  359. var matchQiHao = string.Empty;
  360. var matchKJHaoMa = string.Empty;
  361. JArray openCodeList = null;
  362. foreach (var item in obj["data"])
  363. {
  364. matchQiHao = item["dateNumber"].ToString();
  365. openCodeList = (JArray)item["list"];
  366. matchKJHaoMa = string.Format("{0},{1},{2},{3},{4}", openCodeList[0].ToString(), openCodeList[1].ToString(), openCodeList[2].ToString(), openCodeList[3].ToString(), openCodeList[4].ToString());
  367. if (!result.ContainsKey(matchQiHao))
  368. result.Add(matchQiHao, matchKJHaoMa);
  369. }
  370. }
  371. }
  372. }
  373. catch (Exception ex)
  374. {
  375. log.Error(typeof(HUB11X5Job), string.Format("【{0}】通过备用站点抓取昨日开奖列表时发生错误,错误信息【{1}】", Config.Area + Config.LotteryName, ex.Message));
  376. }
  377. return result;
  378. }
  379. /// <summary>
  380. /// 将此彩种指定期号和开奖号码保存至数据库
  381. /// </summary>
  382. /// <param name="QiHao">期号</param>
  383. /// <param name="OpenCode">开奖号码(形如01,02,03,04,05)</param>
  384. /// <param name="IsYesterdayRecord">是否是保存昨天的记录</param>
  385. /// <returns></returns>
  386. private bool SaveRecord(string QiHao, string OpenCode, bool IsYesterdayRecord)
  387. {
  388. if (!string.IsNullOrWhiteSpace(QiHao) && !string.IsNullOrWhiteSpace(OpenCode))
  389. {
  390. OpenCode5Model model = new OpenCode5Model();
  391. model.Term = Convert.ToInt64(QiHao);
  392. var haoMaArray = OpenCode.Split(new char[] { ',' });
  393. model.OpenCode1 = Convert.ToInt32(haoMaArray[0]);
  394. model.OpenCode2 = Convert.ToInt32(haoMaArray[1]);
  395. model.OpenCode3 = Convert.ToInt32(haoMaArray[2]);
  396. model.OpenCode4 = Convert.ToInt32(haoMaArray[3]);
  397. model.OpenCode5 = Convert.ToInt32(haoMaArray[4]);
  398. if (IsYesterdayRecord)
  399. model.OpenTime = CommonHelper.GenerateYesterdayOpenTime(Config, QiHao);
  400. else
  401. model.OpenTime = CommonHelper.GenerateTodayOpenTime(Config, QiHao);
  402. return services.AddOpen5Code(currentLottery, model);
  403. }
  404. return false;
  405. }
  406. #region Attribute
  407. /// <summary>
  408. /// 配置信息
  409. /// </summary>
  410. private SCCConfig Config = null;
  411. /// <summary>
  412. /// 当天抓取的最新一期期号
  413. /// </summary>
  414. private string LatestQiHao = null;
  415. /// <summary>
  416. /// 当天抓取失败列表
  417. /// </summary>
  418. private List<string> FailedQiHaoList = null;
  419. /// <summary>
  420. /// 日志对象
  421. /// </summary>
  422. private LogHelper log = null;
  423. /// <summary>
  424. /// 数据服务
  425. /// </summary>
  426. private IOpen5Code services = null;
  427. /// <summary>
  428. /// 当前彩种
  429. /// </summary>
  430. private SCCLottery currentLottery
  431. {
  432. get
  433. {
  434. return SCCLottery.HuBei11x5;
  435. }
  436. }
  437. /// <summary>
  438. /// 邮件接口
  439. /// </summary>
  440. private IEmail email = null;
  441. #endregion
  442. }
  443. }