GamesPs.js 17 KB

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