GamesPs.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. const axios = require('axios');
  2. const Logs = require('../libs/logs');
  3. const Setting = require('./Setting');
  4. const childOptions = process.env.NODE_ENV == 'development' ? {
  5. execArgv: ['--inspect=9228']
  6. } : {};
  7. const { fork } = require('child_process');
  8. const events_child = fork('./triangle/eventsMatch.js', [], childOptions);
  9. const PS_IOR_KEYS = [
  10. ['0', 'ior_mh', 'ior_mn', 'ior_mc'],
  11. // ['0', 'ior_rh_05', 'ior_mn', 'ior_rc_05'],
  12. ['-1', 'ior_rh_15', 'ior_wmh_1', 'ior_rac_05'],
  13. ['-2', 'ior_rh_25', 'ior_wmh_2', 'ior_rac_15'],
  14. ['+1', 'ior_rah_05', 'ior_wmc_1', 'ior_rc_15'],
  15. ['+2', 'ior_rah_15', 'ior_wmc_2', 'ior_rc_25'],
  16. ];
  17. const BASE_URL = 'https://api.isthe.me/api/p';
  18. const IS_DEV = process.env.NODE_ENV == 'development';
  19. const GAMES = {
  20. Leagues: {},
  21. List: {},
  22. Baselist: {},
  23. Relations: {},
  24. Solutions: {},
  25. };
  26. const Request = {
  27. callbacks: {},
  28. count: 0,
  29. }
  30. /**
  31. * 精确浮点数字
  32. * @param {number} number
  33. * @param {number} x
  34. * @returns {number}
  35. */
  36. const fixFloat = (number, x=2) => {
  37. return parseFloat(number.toFixed(x));
  38. }
  39. /**
  40. * 获取市场类型
  41. */
  42. const getMarketType = (mk) => {
  43. return mk == 0 ? 'early' : 'today';
  44. }
  45. /**
  46. * 同步联赛列表
  47. */
  48. const syncLeaguesList = ({ mk, leagues }) => {
  49. if (IS_DEV) {
  50. return Logs.out('syncLeaguesList', { mk, leagues });
  51. }
  52. axios.post(`${BASE_URL}/syncLeague`, { mk, leagues })
  53. .then(res => {
  54. Logs.out('syncLeaguesList', res.data);
  55. })
  56. .catch(err => {
  57. Logs.out('syncLeaguesList', err.message);
  58. });
  59. }
  60. /**
  61. * 更新联赛列表
  62. */
  63. const updateLeaguesList = ({ mk, leagues }) => {
  64. const leaguesList = GAMES.Leagues;
  65. if (JSON.stringify(leaguesList[mk]) != JSON.stringify(leagues)) {
  66. leaguesList[mk] = leagues;
  67. syncLeaguesList({ mk, leagues });
  68. return leagues.length;
  69. }
  70. return 0;
  71. }
  72. /**
  73. * 获取筛选过的联赛
  74. */
  75. const getFilteredLeagues = async (mk) => {
  76. return axios.get(`${BASE_URL}/getLeagueTast?mk=${mk}`)
  77. .then(res => {
  78. if (res.data.code == 0) {
  79. return res.data.data;
  80. }
  81. return Promise.reject(new Error(res.data.message));
  82. });
  83. }
  84. /**
  85. * 同步比赛列表到服务器
  86. */
  87. const syncGamesList = ({ platform, mk, games }) => {
  88. if (IS_DEV) {
  89. return Logs.out('syncGamesList', { platform, mk, games });
  90. }
  91. axios.post(`${BASE_URL}/syncGames`, { platform, mk, games })
  92. .then(res => {
  93. Logs.out('syncGamesList', { platform, mk, count: games.length }, res.data);
  94. })
  95. .catch(err => {
  96. Logs.out('syncGamesList', { platform, mk }, err.message);
  97. });
  98. }
  99. /**
  100. * 同步基准比赛列表
  101. */
  102. const syncBaseList = ({ marketType, games }) => {
  103. const baseList = GAMES.Baselist;
  104. if (!baseList[marketType]) {
  105. baseList[marketType] = games;
  106. }
  107. const newMap = new Map(games.map(item => [item.eventId, item]));
  108. // 删除不存在的项
  109. for (let i = baseList[marketType].length - 1; i >= 0; i--) {
  110. if (!newMap.has(baseList[marketType][i].eventId)) {
  111. baseList[marketType].splice(i, 1);
  112. }
  113. }
  114. // 添加或更新
  115. const oldIds = new Set(baseList[marketType].map(item => item.eventId));
  116. games.forEach(game => {
  117. if (!oldIds.has(game.eventId)) {
  118. // 添加新项
  119. baseList[marketType].push(game);
  120. }
  121. });
  122. }
  123. /**
  124. * 更新比赛列表
  125. */
  126. const updateGamesList = (({ platform, mk, games } = {}) => {
  127. return new Promise((resolve, reject) => {
  128. if (!platform || !games) {
  129. return reject(new Error('PLATFORM_GAMES_INVALID'));
  130. }
  131. const marketType = getMarketType(mk);
  132. syncGamesList({ platform, mk, games });
  133. if (platform == 'ps') {
  134. syncBaseList({ marketType, games });
  135. }
  136. resolve();
  137. });
  138. });
  139. /**
  140. * 提交盘口数据
  141. */
  142. const submitOdds = ({ platform, mk, games }) => {
  143. if (IS_DEV) {
  144. return Logs.out('syncOdds', { platform, mk, games });
  145. }
  146. axios.post(`${BASE_URL}/syncOdds`, { platform, mk, games})
  147. .then(res => {
  148. Logs.out('syncOdds', { platform, mk, count: games.length }, res.data);
  149. })
  150. .catch(err => {
  151. Logs.out('syncOdds', { platform, mk }, err.message);
  152. });
  153. }
  154. /**
  155. * 同步基准盘口
  156. */
  157. const syncBaseEvents = ({ mk, games, outrights }) => {
  158. const marketType = getMarketType(mk);
  159. const baseList = GAMES.Baselist;
  160. if (!baseList[marketType]) {
  161. return;
  162. }
  163. const baseMap = new Map(baseList[marketType].map(item => [item.eventId, item]));
  164. games?.forEach(game => {
  165. const { eventId, evtime, events } = game;
  166. const baseGame = baseMap.get(eventId);
  167. if (baseGame) {
  168. baseGame.evtime = evtime;
  169. baseGame.events = events;
  170. }
  171. });
  172. outrights?.forEach(outright => {
  173. const { parentId, sptime, special } = outright;
  174. const baseGame = baseMap.get(parentId);
  175. if (baseGame) {
  176. baseGame.sptime = sptime;
  177. baseGame.special = special;
  178. }
  179. });
  180. if (games?.length) {
  181. const gamesList = baseList[marketType]?.map(game => {
  182. const { evtime, events, sptime, special, ...gameInfo } = game;
  183. const expireTime = Date.now() - 15000;
  184. let odds = {};
  185. if (evtime > expireTime) {
  186. odds = { ...odds, ...events };
  187. }
  188. if (sptime > expireTime) {
  189. odds = { ...odds, ...special };
  190. }
  191. const matches = PS_IOR_KEYS.map(([label, ...keys]) => {
  192. const match = keys.map(key => ({
  193. key,
  194. value: odds[key] ?? 0
  195. }));
  196. return {
  197. label,
  198. match
  199. };
  200. }).filter(item => item.match.every(entry => entry.value !== 0));
  201. return { ...gameInfo, matches };
  202. });
  203. // Logs.out('baseList', baseList[marketType]);
  204. submitOdds({ platform: 'ps', mk, games: gamesList });
  205. }
  206. }
  207. /**
  208. * 更新比赛盘口
  209. */
  210. const updateGamesEvents = ({ platform, mk, games, outrights }) => {
  211. return new Promise((resolve, reject) => {
  212. if (!platform || (!games && !outrights)) {
  213. return reject(new Error('PLATFORM_GAMES_INVALID'));
  214. }
  215. if (platform == 'ps') {
  216. syncBaseEvents({ mk, games, outrights });
  217. }
  218. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.[platform] ?? {});
  219. if (!relatedGames.length) {
  220. return resolve({ update: 0 });
  221. }
  222. const updateCount = {
  223. update: 0
  224. };
  225. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  226. games?.forEach(game => {
  227. const { eventId, evtime, events } = game;
  228. const relatedGame = relatedMap.get(eventId);
  229. if (relatedGame) {
  230. relatedGame.evtime = evtime;
  231. relatedGame.events = events;
  232. updateCount.update ++;
  233. }
  234. });
  235. outrights?.forEach(outright => {
  236. const { parentId, sptime, special } = outright;
  237. const relatedGame = relatedMap.get(parentId);
  238. if (relatedGame) {
  239. relatedGame.sptime = sptime;
  240. relatedGame.special = special;
  241. updateCount.update ++;
  242. }
  243. });
  244. resolve(updateCount);
  245. });
  246. }
  247. /**
  248. * 获取关联比赛
  249. */
  250. const fetchGamesRelation = async (mk='') => {
  251. return axios.get(`${BASE_URL}/getGameTast?mk=${mk}`)
  252. .then(res => {
  253. if (res.data.code == 0) {
  254. const now = Date.now();
  255. const gamesRelation = res.data.data?.filter(item => {
  256. const timestamp = new Date(item.timestamp).getTime();
  257. item.timestamp = timestamp;
  258. return timestamp > now;
  259. }).map(item => {
  260. const {
  261. id, mk, league_name,
  262. event_id: ps_event_id,
  263. league_id: ps_league_id,
  264. team_home_name: ps_team_home_name,
  265. team_away_name: ps_team_away_name,
  266. ob_event_id, ob_league_id,
  267. ob_team_home_name,
  268. ob_team_away_name,
  269. hg_event_id, hg_league_id,
  270. hg_team_home_name,
  271. hg_team_away_name,
  272. timestamp,
  273. } = item;
  274. const rel = {
  275. ps: {
  276. eventId: +ps_event_id,
  277. leagueId: +ps_league_id,
  278. leagueName: league_name,
  279. teamHomeName: ps_team_home_name,
  280. teamAwayName: ps_team_away_name,
  281. timestamp
  282. },
  283. ob: ob_event_id ? {
  284. eventId: +ob_event_id,
  285. leagueId: +ob_league_id,
  286. leagueName: league_name,
  287. teamHomeName: ob_team_home_name,
  288. teamAwayName: ob_team_away_name,
  289. timestamp
  290. } : null,
  291. hg: hg_event_id ? {
  292. eventId: +hg_event_id,
  293. leagueId: +hg_league_id,
  294. leagueName: league_name,
  295. teamHomeName: hg_team_home_name,
  296. teamAwayName: hg_team_away_name,
  297. timestamp
  298. } : null
  299. };
  300. return { id, mk, rel };
  301. }) ?? [];
  302. return gamesRelation;
  303. }
  304. return Promise.reject(new Error(res.data.message));
  305. });
  306. }
  307. const getGamesRelation = ({ mk, listEvents }) => {
  308. const relations = Object.values(GAMES.Relations).filter(item => {
  309. if (typeof(mk) == 'undefined') {
  310. return true;
  311. }
  312. return item.mk == mk;
  313. });
  314. if (listEvents) {
  315. return relations;
  316. }
  317. return relations.map(item => {
  318. const { rel, ...relationInfo } = item;
  319. const tempRel = { ...rel };
  320. Object.keys(tempRel).forEach(platform => {
  321. const { events, evtime, sptime, special, ...gameInfo } = tempRel[platform];
  322. tempRel[platform] = gameInfo;
  323. });
  324. return { ...relationInfo, rel: tempRel };
  325. });
  326. }
  327. /**
  328. * 定时更新关联比赛列表
  329. */
  330. const updateGamesRelation = () => {
  331. fetchGamesRelation()
  332. .then(res => {
  333. const gamesRelation = res.flat();
  334. const updateCount = {
  335. add: 0,
  336. delete: 0
  337. };
  338. gamesRelation.forEach(item => {
  339. const { id } = item;
  340. if (!GAMES.Relations[id]) {
  341. GAMES.Relations[id] = item;
  342. updateCount.add ++;
  343. }
  344. });
  345. const relations = new Set(gamesRelation.map(item => +item.id));
  346. Object.keys(GAMES.Relations).forEach(id => {
  347. if (!relations.has(+id)) {
  348. delete GAMES.Relations[id];
  349. updateCount.delete ++;
  350. }
  351. });
  352. Logs.out('updateGamesRelation', updateCount);
  353. })
  354. .catch(err => {
  355. Logs.out('updateGamesRelation', err.message);
  356. })
  357. .finally(() => {
  358. setTimeout(updateGamesRelation, 60000);
  359. });
  360. }
  361. updateGamesRelation();
  362. /**
  363. * 同步比赛结果
  364. */
  365. const syncGamesResult = async (result) => {
  366. if (IS_DEV) {
  367. return Logs.out('updateGamesResult', result);
  368. }
  369. axios.post(`${BASE_URL}/syncMatchResult`, result)
  370. .then(res => {
  371. Logs.out('syncMatchResult', res.data);
  372. })
  373. .catch(err => {
  374. Logs.out('syncMatchResult', err.message);
  375. });
  376. }
  377. /**
  378. * 更新比赛结果
  379. */
  380. const updateGamesResult = (result) => {
  381. syncGamesResult(result);
  382. return Promise.resolve();
  383. }
  384. /**
  385. * 同步中单方案
  386. */
  387. const syncSolutions = (solutions) => {
  388. if (IS_DEV) {
  389. return Logs.out('syncSolutions', solutions);
  390. }
  391. axios.post(`${BASE_URL}/syncDsOpportunity`, solutions)
  392. .then(res => {
  393. Logs.out('syncSolutions', res.data);
  394. })
  395. .catch(err => {
  396. Logs.out('syncSolutions', err.message);
  397. });
  398. }
  399. /**
  400. * 更新中单方案
  401. */
  402. const getCprKey = (cpr) => {
  403. const { k, p, v } = cpr;
  404. return `${k}_${p}_${v}`;
  405. }
  406. const compareCpr = (cpr1, cpr2) => {
  407. const key1 = getCprKey(cpr1);
  408. const key2 = getCprKey(cpr2);
  409. return key1 === key2;
  410. }
  411. const updateSolutions = (solutions) => {
  412. if (solutions?.length) {
  413. const solutionsHistory = GAMES.Solutions;
  414. const updateIds = { add: [], update: [] }
  415. solutions.forEach(item => {
  416. const { sid, cpr, sol: { win_average } } = item;
  417. if (!solutionsHistory[sid]) {
  418. solutionsHistory[sid] = item;
  419. updateIds.add.push(sid);
  420. return;
  421. }
  422. const historySolution = solutionsHistory[sid];
  423. if (historySolution.sol.win_average !== win_average || !compareCpr(historySolution.cpr, cpr)) {
  424. solutionsHistory[sid] = item;
  425. updateIds.update.push(sid);
  426. return;
  427. }
  428. const { timestamp } = item;
  429. solutionsHistory[sid].timestamp = timestamp;
  430. });
  431. if (updateIds.add.length || updateIds.update.length) {
  432. const solutionUpdate = {};
  433. Object.keys(updateIds).forEach(key => {
  434. solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  435. });
  436. syncSolutions(solutionUpdate);
  437. // Logs.outDev('solutions history update', solutionUpdate);
  438. }
  439. }
  440. }
  441. /**
  442. * 清理中单方案
  443. */
  444. const solutionsCleanup = () => {
  445. const solutionsHistory = GAMES.Solutions;
  446. const updateIds = { remove: [] }
  447. Object.keys(solutionsHistory).forEach(sid => {
  448. const { timestamp } = solutionsHistory[sid];
  449. const nowTime = Date.now();
  450. if (nowTime - timestamp > 1000*60) {
  451. delete solutionsHistory[sid];
  452. updateIds.remove.push(sid);
  453. return;
  454. }
  455. const solution = solutionsHistory[sid];
  456. const eventTime = solution.info.timestamp;
  457. if (nowTime > eventTime) {
  458. delete solutionsHistory[sid];
  459. updateIds.remove.push(sid);
  460. }
  461. });
  462. if (updateIds.remove.length) {
  463. syncSolutions(updateIds);
  464. // Logs.outDev('solutions history cleanup', updateIds);
  465. }
  466. }
  467. /**
  468. * 定时清理中单方案
  469. */
  470. setInterval(() => {
  471. solutionsCleanup();
  472. }, 1000*30);
  473. /**
  474. * 获取后台设置
  475. */
  476. const getSetting = async () => {
  477. return Setting.get();
  478. }
  479. /**
  480. * 从子进程获取数据
  481. */
  482. const getDataFromChild = (type, callback) => {
  483. const id = ++Request.count;
  484. Request.callbacks[id] = callback;
  485. events_child.send({ method: 'get', id, type });
  486. }
  487. /**
  488. * 处理子进程消息
  489. */
  490. events_child.on('message', async (message) => {
  491. const { callbacks } = Request;
  492. const { method, id, type, data } = message;
  493. if (method == 'get' && id) {
  494. let responseData = null;
  495. if (type == 'getGamesRelation') {
  496. responseData = getGamesRelation({ listEvents: true });
  497. }
  498. else if (type == 'getSetting') {
  499. responseData = await getSetting();
  500. }
  501. // else if (type == 'getSolutionHistory') {
  502. // responseData = getSolutionHistory();
  503. // }
  504. events_child.send({ type: 'response', id, data: responseData });
  505. }
  506. else if (method == 'post') {
  507. if (type == 'updateSolutions') {
  508. updateSolutions(data);
  509. }
  510. }
  511. else if (method == 'response' && id && callbacks[id]) {
  512. callbacks[id](data);
  513. delete callbacks[id];
  514. }
  515. });
  516. module.exports = {
  517. updateLeaguesList, getFilteredLeagues,
  518. updateGamesList, updateGamesEvents,
  519. getGamesRelation,
  520. updateGamesResult,
  521. }