GamesPs.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. const axios = require('axios');
  2. const Logs = require('../libs/logs');
  3. const Cache = require('../libs/cache');
  4. const Setting = require('./Setting');
  5. const { eventSolutions } = require('../triangle/eventSolutions');
  6. const { calcTotalProfit, calcTotalProfitWithFixedFirst } = require('../triangle/totalProfitCalc');
  7. const fs = require('fs');
  8. const path = require('path');
  9. const GamesCacheFile = path.join(__dirname, '../data/games.cache');
  10. const DevGameTastFile = path.join(__dirname, '../data/gameTast.json');
  11. const childOptions = process.env.NODE_ENV == 'development' ? {
  12. execArgv: ['--inspect=9228'],
  13. stdio: ['pipe', 'pipe', 'pipe', 'ipc']
  14. } : {};
  15. const { fork } = require('child_process');
  16. const events_child = fork('./triangle/eventsMatch.js', [], childOptions);
  17. const PS_IOR_KEYS = [
  18. ['0', 'ior_mh', 'ior_mn', 'ior_mc'],
  19. ['-1', 'ior_rh_15', 'ior_wmh_1', 'ior_rac_05'],
  20. ['-2', 'ior_rh_25', 'ior_wmh_2', 'ior_rac_15'],
  21. ['+1', 'ior_rah_05', 'ior_wmc_1', 'ior_rc_15'],
  22. ['+2', 'ior_rah_15', 'ior_wmc_2', 'ior_rc_25'],
  23. ['0-1', 'ior_ot_0', 'ior_os_0-1', 'ior_ot_1'],
  24. ['2-3', 'ior_ot_2', 'ior_os_2-3', 'ior_ot_3'],
  25. ];
  26. // 测试环境
  27. // const BASE_URL = 'https://dev.api.czxd8.com/api/p';
  28. const IS_DEV = process.env.NODE_ENV == 'development';
  29. const BASE_URL = 'https://api.qboss.vip/api/p';
  30. const GAMES = {
  31. Leagues: {},
  32. Baselist: {},
  33. Relations: {},
  34. Solutions: {},
  35. };
  36. const Request = {
  37. callbacks: {},
  38. count: 0,
  39. }
  40. /**
  41. * 精确浮点数字
  42. * @param {number} number
  43. * @param {number} x
  44. * @returns {number}
  45. */
  46. const fixFloat = (number, x=2) => {
  47. return parseFloat(number.toFixed(x));
  48. }
  49. /**
  50. * 获取市场类型
  51. */
  52. const getMarketType = (mk) => {
  53. if (mk == 0) {
  54. return 'early';
  55. }
  56. else if (mk == 2) {
  57. return 'rollball';
  58. }
  59. return 'today';
  60. }
  61. /**
  62. * 同步联赛列表
  63. */
  64. const syncLeaguesList = ({ mk, leagues }) => {
  65. if (IS_DEV) {
  66. return Logs.out('syncLeaguesList', { mk, leagues });
  67. }
  68. axios.post(`${BASE_URL}/syncLeague`, { mk, leagues })
  69. .then(res => {
  70. // Logs.out('syncLeaguesList', res.data);
  71. })
  72. .catch(err => {
  73. Logs.out('syncLeaguesList', err.message);
  74. });
  75. }
  76. /**
  77. * 更新联赛列表
  78. */
  79. const updateLeaguesList = ({ mk, leagues }) => {
  80. const leaguesMap = GAMES.Leagues;
  81. const nowTime = Date.now();
  82. const expireTime = nowTime - 1000 * 60 * 5;
  83. if (!leaguesMap[mk]) {
  84. leaguesMap[mk] = {
  85. timestamp: 0,
  86. leagues: [],
  87. };
  88. }
  89. if (leaguesMap[mk].timestamp < expireTime ||
  90. JSON.stringify(leaguesMap[mk].leagues) != JSON.stringify(leagues)) {
  91. leaguesMap[mk].leagues = leagues;
  92. leaguesMap[mk].timestamp = nowTime;
  93. syncLeaguesList({ mk, leagues });
  94. return leagues.length;
  95. }
  96. return 0;
  97. }
  98. /**
  99. * 获取筛选过的联赛
  100. */
  101. const getFilteredLeagues = async (mk) => {
  102. return axios.get(`${BASE_URL}/getLeagueTast?mk=${mk}`)
  103. .then(res => {
  104. if (res.data.code == 0) {
  105. return res.data.data;
  106. }
  107. return Promise.reject(new Error(res.data.message));
  108. });
  109. }
  110. /**
  111. * 同步比赛列表到服务器
  112. */
  113. const syncGamesList = ({ platform, mk, games }) => {
  114. if (IS_DEV) {
  115. return Logs.out('syncGamesList', { platform, mk, games });
  116. }
  117. axios.post(`${BASE_URL}/syncGames`, { platform, mk, games })
  118. .then(res => {
  119. // Logs.out('syncGamesList', { platform, mk, count: games.length }, res.data);
  120. })
  121. .catch(err => {
  122. Logs.out('syncGamesList', { platform, mk }, err.message);
  123. });
  124. }
  125. /**
  126. * 同步基准比赛列表
  127. */
  128. const syncBaseList = ({ marketType, games }) => {
  129. const baseList = GAMES.Baselist;
  130. // 直接创建新列表
  131. if (!baseList[marketType]) {
  132. baseList[marketType] = games;
  133. return;
  134. }
  135. const newMap = new Map(games.map(item => [item.eventId, item]));
  136. // 删除不存在的项
  137. for (let i = baseList[marketType].length - 1; i >= 0; i--) {
  138. if (!newMap.has(baseList[marketType][i].eventId)) {
  139. baseList[marketType].splice(i, 1);
  140. }
  141. }
  142. // 添加或更新
  143. const oldIds = new Set(baseList[marketType].map(item => item.eventId));
  144. games.forEach(game => {
  145. if (!oldIds.has(game.eventId)) {
  146. // 添加新项
  147. baseList[marketType].push(game);
  148. }
  149. });
  150. }
  151. /**
  152. * 更新比赛列表
  153. */
  154. const updateGamesList = (({ platform, mk, games } = {}) => {
  155. return new Promise((resolve, reject) => {
  156. if (!platform || !games) {
  157. return reject(new Error('PLATFORM_GAMES_INVALID'));
  158. }
  159. syncGamesList({ platform, mk, games });
  160. resolve();
  161. });
  162. });
  163. /**
  164. * 提交盘口数据
  165. */
  166. const submitOdds = ({ platform, mk, games }) => {
  167. if (IS_DEV) {
  168. return Logs.out('syncOdds', { platform, mk, games });
  169. }
  170. axios.post(`${BASE_URL}/syncOdds`, { platform, mk, games})
  171. .then(res => {
  172. // Logs.out('syncOdds', { platform, mk, count: games.length }, res.data);
  173. })
  174. .catch(err => {
  175. Logs.out('syncOdds', { platform, mk }, err.message);
  176. Logs.out(JSON.stringify({ platform, mk, games }, null, 2));
  177. });
  178. }
  179. /**
  180. * 同步基准盘口
  181. */
  182. const syncBaseEvents = ({ mk, games, outrights }) => {
  183. const marketType = getMarketType(mk);
  184. const baseList = GAMES.Baselist;
  185. if (!baseList[marketType]) {
  186. return;
  187. }
  188. const baseMap = new Map(baseList[marketType].map(item => [item.eventId, item]));
  189. games?.forEach(game => {
  190. const { eventId, originId, stage, score, wm, evtime, events } = game;
  191. const baseGame = baseMap.get(eventId);
  192. if (baseGame) {
  193. baseGame.originId = originId;
  194. baseGame.stage = stage;
  195. baseGame.score = score;
  196. baseGame.wm = wm;
  197. baseGame.evtime = evtime;
  198. baseGame.events = events;
  199. }
  200. });
  201. outrights?.forEach(outright => {
  202. const { parentId, sptime, special } = outright;
  203. const baseGame = baseMap.get(parentId);
  204. if (baseGame) {
  205. baseGame.sptime = sptime;
  206. baseGame.special = special;
  207. }
  208. else {
  209. const originBaseMap = new Map(baseList[marketType].map(item => [item.originId, item]));
  210. const originBaseGame = originBaseMap.get(parentId);
  211. if (originBaseGame) {
  212. originBaseGame.sptime = sptime;
  213. originBaseGame.special = special;
  214. }
  215. }
  216. });
  217. if (games?.length) {
  218. const gamesList = baseList[marketType]?.map(game => {
  219. const { evtime, events, sptime, special, ...gameInfo } = game;
  220. const expireTimeEv = Date.now() - 30000;
  221. const expireTimeSP = Date.now() - 45000;
  222. let odds = {};
  223. if (evtime > expireTimeEv) {
  224. odds = { ...odds, ...events };
  225. }
  226. if (sptime > expireTimeSP) {
  227. odds = { ...odds, ...special };
  228. }
  229. const matches = PS_IOR_KEYS.map(([label, ...keys]) => {
  230. const match = keys.map(key => {
  231. if (key.includes('os') && !odds[key]) {
  232. return { key, value: 1 };
  233. }
  234. else {
  235. return {
  236. key,
  237. value: odds[key]?.v ?? 0,
  238. origin: odds[key]?.r
  239. }
  240. }
  241. });
  242. return {
  243. label,
  244. match
  245. };
  246. }).filter(item => item.match.every(entry => entry.value !== 0));
  247. let uptime = 0;
  248. if (evtime && sptime) {
  249. uptime = Math.min(evtime, sptime);
  250. }
  251. else if (!sptime) {
  252. uptime = evtime ?? 0;
  253. }
  254. return { ...gameInfo, matches, uptime };
  255. });
  256. if (gamesList.filter(item => item.uptime > 0).length) {
  257. submitOdds({ platform: 'ps', mk, games: gamesList });
  258. }
  259. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.['ps'] ?? {});
  260. if (!relatedGames.length) {
  261. return 0;
  262. }
  263. let update = 0;
  264. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  265. gamesList?.forEach(game => {
  266. const { eventId, matches, uptime, stage, score, wm } = game;
  267. const relatedGame = relatedMap.get(eventId);
  268. if (relatedGame) {
  269. const events = {};
  270. matches.forEach(({ label, match }) => {
  271. match.forEach(({ key, value, origin }) => {
  272. events[key] = {
  273. v: value,
  274. r: origin
  275. };
  276. });
  277. });
  278. relatedGame.evtime = uptime;
  279. relatedGame.events = events;
  280. relatedGame.stage = stage;
  281. relatedGame.score = score;
  282. relatedGame.wm = wm;
  283. update ++;
  284. }
  285. });
  286. return update;
  287. }
  288. }
  289. const updateGamesEvents = ({ platform, mk, games, outrights }) => {
  290. return new Promise((resolve, reject) => {
  291. if (!platform || (!games && !outrights)) {
  292. return reject(new Error('PLATFORM_GAMES_INVALID'));
  293. }
  294. if (platform == 'ps') {
  295. const update = syncBaseEvents({ mk, games, outrights });
  296. return resolve({ update });
  297. }
  298. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.[platform] ?? {});
  299. if (!relatedGames.length) {
  300. return resolve({ update: 0 });
  301. }
  302. const updateCount = {
  303. update: 0
  304. };
  305. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  306. games?.forEach(game => {
  307. const { eventId, evtime, events, stage, score, wm } = game;
  308. const relatedGame = relatedMap.get(eventId);
  309. if (relatedGame) {
  310. relatedGame.evtime = evtime;
  311. relatedGame.events = events;
  312. relatedGame.stage = stage;
  313. relatedGame.score = score;
  314. relatedGame.wm = wm;
  315. updateCount.update ++;
  316. }
  317. });
  318. outrights?.forEach(outright => {
  319. const { parentId, sptime, special } = outright;
  320. const relatedGame = relatedMap.get(parentId);
  321. if (relatedGame) {
  322. relatedGame.sptime = sptime;
  323. relatedGame.special = special;
  324. updateCount.update ++;
  325. }
  326. });
  327. resolve(updateCount);
  328. });
  329. }
  330. /**
  331. * 获取比赛盘口
  332. */
  333. const getGamesEvents = ({ platform, relIds = [] } = {}) => {
  334. if (!relIds.length) {
  335. return null;
  336. }
  337. const idSet = new Set(relIds);
  338. const relations = { ...GAMES.Relations };
  339. Object.keys(relations).forEach(id => {
  340. if (idSet.size && !idSet.has(+id)) {
  341. delete relations[id];
  342. }
  343. });
  344. if (platform) {
  345. return Object.values(relations).map(rel => rel[platform] ?? {});
  346. }
  347. const gamesEvents = {};
  348. Object.values(relations).forEach(({ rel }) => {
  349. Object.keys(rel).forEach(platform => {
  350. const game = rel[platform] ?? {};
  351. const { eventId, events, special } = game;
  352. if (!gamesEvents[platform]) {
  353. gamesEvents[platform] = {};
  354. }
  355. gamesEvents[platform][eventId] = { ...events, ...special };
  356. });
  357. });
  358. return gamesEvents;
  359. }
  360. /**
  361. * 获取关联比赛
  362. */
  363. const getDevGameTast = () => {
  364. return new Promise((resolve) => {
  365. const data = Cache.getData(DevGameTastFile, true);
  366. resolve({data});
  367. });
  368. }
  369. const fetchGamesRelation = async (mk='') => {
  370. const getGameTast = Promise.all([
  371. getDevGameTast(),
  372. axios.get(`${BASE_URL}/getGameTast?mk=${mk}`)
  373. ]);
  374. return getGameTast.then(([res1, res2]) => {
  375. const resData = res1.data ?? res2.data;
  376. if (resData.code == 0) {
  377. const nowTime = Date.now();
  378. const gamesRelation = resData.data?.filter(item => {
  379. const timestamp = new Date(item.timestamp).getTime();
  380. if (nowTime > timestamp) {
  381. item.mk = 2;
  382. }
  383. item.timestamp = timestamp;
  384. const expireTime = timestamp + 1000*60*60*2;
  385. return expireTime > nowTime;
  386. }).map(item => {
  387. const {
  388. id, mk, league_name,
  389. event_id: ps_event_id,
  390. league_id: ps_league_id,
  391. team_home_name: ps_team_home_name,
  392. team_away_name: ps_team_away_name,
  393. ob_event_id, ob_league_id,
  394. ob_team_home_name,
  395. ob_team_away_name,
  396. hg_event_id, hg_league_id,
  397. hg_team_home_name,
  398. hg_team_away_name,
  399. timestamp,
  400. } = item;
  401. const rel = {
  402. ps: {
  403. eventId: +ps_event_id,
  404. leagueId: +ps_league_id,
  405. leagueName: league_name,
  406. teamHomeName: ps_team_home_name,
  407. teamAwayName: ps_team_away_name,
  408. timestamp
  409. },
  410. ob: ob_event_id ? {
  411. eventId: +ob_event_id,
  412. leagueId: +ob_league_id,
  413. leagueName: league_name,
  414. teamHomeName: ob_team_home_name,
  415. teamAwayName: ob_team_away_name,
  416. timestamp
  417. } : null,
  418. hg: hg_event_id ? {
  419. eventId: +hg_event_id,
  420. leagueId: +hg_league_id,
  421. leagueName: league_name,
  422. teamHomeName: hg_team_home_name,
  423. teamAwayName: hg_team_away_name,
  424. timestamp
  425. } : null
  426. };
  427. return { id: ps_event_id, mk, rel, timestamp };
  428. }) ?? [];
  429. return gamesRelation;
  430. }
  431. return Promise.reject(new Error(resData.message));
  432. });
  433. }
  434. const getGamesRelation = ({ mk, listEvents } = {}) => {
  435. const relations = Object.values(GAMES.Relations).filter(item => {
  436. if (typeof(mk) === 'undefined' || mk === '') {
  437. return true;
  438. }
  439. return item.mk == mk;
  440. }).sort((a, b) => a.timestamp - b.timestamp);
  441. if (listEvents) {
  442. return relations;
  443. }
  444. const gamesRelation = relations.map(item => {
  445. const { rel, ...relationInfo } = item;
  446. const tempRel = { ...rel };
  447. Object.keys(tempRel).forEach(platform => {
  448. const { events, evtime, sptime, special, ...gameInfo } = tempRel[platform];
  449. tempRel[platform] = gameInfo;
  450. });
  451. return { ...relationInfo, rel: tempRel };
  452. });
  453. return gamesRelation;
  454. }
  455. /**
  456. * 定时更新关联比赛列表
  457. */
  458. const updateGamesRelation = () => {
  459. fetchGamesRelation()
  460. .then(gamesRelation => {
  461. const baseList = {};
  462. gamesRelation.map(item => {
  463. const baseGame = item.rel?.['ps'] ?? {};
  464. return { ...baseGame, mk: item.mk };
  465. }).forEach(item => {
  466. const marketType = getMarketType(item.mk);
  467. if (!baseList[marketType]) {
  468. baseList[marketType] = [];
  469. }
  470. baseList[marketType].push(item);
  471. });
  472. Object.keys(baseList).forEach(marketType => {
  473. syncBaseList({ marketType, games: baseList[marketType] });
  474. });
  475. const updateCount = {
  476. add: 0,
  477. update: 0,
  478. delete: 0
  479. };
  480. gamesRelation.forEach(item => {
  481. const { id, mk } = item;
  482. const oldItem = GAMES.Relations[id];
  483. if (!oldItem) {
  484. GAMES.Relations[id] = item;
  485. updateCount.add ++;
  486. }
  487. else if (oldItem.mk != mk) {
  488. GAMES.Relations[id] = item;
  489. updateCount.update ++;
  490. }
  491. });
  492. const relations = new Set(gamesRelation.map(item => +item.id));
  493. Object.keys(GAMES.Relations).forEach(id => {
  494. if (!relations.has(+id)) {
  495. delete GAMES.Relations[id];
  496. updateCount.delete ++;
  497. }
  498. else {
  499. const { timestamp } = GAMES.Relations[id];
  500. const expireTime = timestamp ? timestamp + 1000*60*60*2 : 0;
  501. if (expireTime && expireTime < Date.now()) {
  502. delete GAMES.Relations[id];
  503. updateCount.delete ++;
  504. }
  505. }
  506. });
  507. Logs.outDev('updateGamesRelation', updateCount);
  508. })
  509. .catch(err => {
  510. Logs.out('updateGamesRelation', err.message);
  511. })
  512. .finally(() => {
  513. setTimeout(updateGamesRelation, 60000);
  514. });
  515. }
  516. updateGamesRelation();
  517. const gamesRelationCleanup = () => {
  518. const relations = Object.values(GAMES.Relations);
  519. const expireTime = Date.now() - 1000*60;
  520. relations.forEach(item => {
  521. const { rel } = item;
  522. Object.keys(rel).forEach(platform => {
  523. const { evtime, sptime } = rel[platform];
  524. if (evtime && evtime < expireTime) {
  525. delete rel[platform].events;
  526. delete rel[platform].evtime;
  527. }
  528. if (sptime && sptime < expireTime) {
  529. delete rel[platform].special;
  530. delete rel[platform].sptime;
  531. }
  532. });
  533. });
  534. }
  535. /**
  536. * 同步比赛结果
  537. */
  538. const syncGamesResult = async (result) => {
  539. if (IS_DEV) {
  540. return Logs.out('updateGamesResult', result);
  541. }
  542. axios.post(`${BASE_URL}/syncMatchResult`, result)
  543. .then(res => {
  544. // Logs.out('syncMatchResult', res.data);
  545. })
  546. .catch(err => {
  547. Logs.out('syncMatchResult', err.message);
  548. });
  549. }
  550. /**
  551. * 更新比赛结果
  552. */
  553. const updateGamesResult = (result) => {
  554. syncGamesResult(result);
  555. return Promise.resolve();
  556. }
  557. /**
  558. * 同步中单方案
  559. */
  560. const syncSolutions = (solutions) => {
  561. if (IS_DEV) {
  562. return Logs.out('syncSolutions', solutions);
  563. }
  564. axios.post(`${BASE_URL}/syncDsOpportunity`, solutions)
  565. .then(res => {
  566. // Logs.out('syncSolutions', res.data);
  567. })
  568. .catch(err => {
  569. Logs.out('syncSolutions', err.message);
  570. });
  571. }
  572. /**
  573. * 更新中单方案
  574. */
  575. const getCprKey = (cpr) => {
  576. const { k, p, v } = cpr;
  577. return `${k}_${p}_${v}`;
  578. }
  579. const compareCpr = (cpr1, cpr2) => {
  580. const key1 = getCprKey(cpr1);
  581. const key2 = getCprKey(cpr2);
  582. return key1 === key2;
  583. }
  584. const updateSolutions = (solutions) => {
  585. if (solutions?.length) {
  586. const solutionsHistory = GAMES.Solutions;
  587. const updateIds = { add: [], update: [] }
  588. solutions.forEach(item => {
  589. const { sid, cpr, sol: { win_average } } = item;
  590. if (!solutionsHistory[sid]) {
  591. solutionsHistory[sid] = item;
  592. updateIds.add.push(sid);
  593. return;
  594. }
  595. const historySolution = solutionsHistory[sid];
  596. if (historySolution.sol.win_average !== win_average || !compareCpr(historySolution.cpr, cpr)) {
  597. solutionsHistory[sid] = item;
  598. updateIds.update.push(sid);
  599. return;
  600. }
  601. const { timestamp } = item;
  602. solutionsHistory[sid].timestamp = timestamp;
  603. });
  604. if (updateIds.add.length || updateIds.update.length) {
  605. const solutionUpdate = {};
  606. Object.keys(updateIds).forEach(key => {
  607. solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  608. });
  609. syncSolutions(solutionUpdate);
  610. // Logs.outDev('solutions history update', solutionUpdate);
  611. }
  612. }
  613. }
  614. /**
  615. * 获取中单方案
  616. */
  617. const getSolutions = async () => {
  618. const { minShowAmount } = await getSetting();
  619. const solutionsList = Object.values(GAMES.Solutions);
  620. const gamesRelation = getGamesRelation();
  621. const relationsMap = new Map(gamesRelation.map(item => [item.id, item.rel]));
  622. const solutions = solutionsList.sort((a, b) => b.sol.win_average - a.sol.win_average)
  623. .filter(item => {
  624. const { sol: { win_average } } = item;
  625. return win_average >= minShowAmount;
  626. })
  627. .map(item => {
  628. const { info: { id } } = item;
  629. const relation = relationsMap.get(id);
  630. return {
  631. ...item,
  632. info: { id, ...relation }
  633. }
  634. });
  635. const relIds = solutions.map(item => item.info.id);
  636. const gamesEvents = getGamesEvents({ relIds });
  637. return { solutions, gamesEvents };
  638. }
  639. /**
  640. * 清理中单方案
  641. */
  642. const solutionsCleanup = () => {
  643. const solutionsHistory = GAMES.Solutions;
  644. const updateIds = { remove: [] }
  645. Object.keys(solutionsHistory).forEach(sid => {
  646. const { timestamp } = solutionsHistory[sid];
  647. const nowTime = Date.now();
  648. if (nowTime - timestamp > 1000*60) {
  649. delete solutionsHistory[sid];
  650. updateIds.remove.push(sid);
  651. return;
  652. }
  653. const solution = solutionsHistory[sid];
  654. const eventTime = solution.info.timestamp;
  655. if (nowTime > eventTime) {
  656. delete solutionsHistory[sid];
  657. updateIds.remove.push(sid);
  658. }
  659. });
  660. if (updateIds.remove.length) {
  661. syncSolutions(updateIds);
  662. }
  663. }
  664. /**
  665. * 定时清理中单方案
  666. * 定时清理盘口信息
  667. */
  668. setInterval(() => {
  669. solutionsCleanup();
  670. gamesRelationCleanup();
  671. }, 1000*30);
  672. /**
  673. * 获取综合利润
  674. */
  675. const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
  676. const { innerDefaultAmount, innerRebateRatio } = await getSetting();
  677. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  678. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  679. const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
  680. return profit;
  681. }
  682. /**
  683. * 通过 sid 获取综合利润
  684. */
  685. const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
  686. const preSolution = GAMES.Solutions[sid1];
  687. const subSolution = GAMES.Solutions[sid2];
  688. const sol1 = preSolution?.sol;
  689. const sol2 = subSolution?.sol;
  690. if (!sol1) {
  691. return Promise.reject(new Error('sid1 已失效'));
  692. }
  693. if (!sol2) {
  694. return Promise.reject(new Error('sid2 已失效'));
  695. }
  696. const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  697. return { profit, solutions: [preSolution, subSolution] };
  698. }
  699. /**
  700. * 通过盘口信息获取综合利润
  701. */
  702. const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
  703. const { innerDefaultAmount, innerRebateRatio } = await getSetting();
  704. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  705. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  706. if (fixed) {
  707. return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
  708. }
  709. const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
  710. return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  711. }
  712. /**
  713. * 获取后台设置
  714. */
  715. const getSetting = async () => {
  716. return Setting.get();
  717. }
  718. /**
  719. * 从子进程获取数据
  720. */
  721. const getDataFromChild = (type, callback) => {
  722. const id = ++Request.count;
  723. Request.callbacks[id] = callback;
  724. events_child.send({ method: 'get', id, type });
  725. }
  726. /**
  727. * 向子进程发送数据
  728. */
  729. const postDataToChild = (type, data) => {
  730. events_child.send({ method: 'post', type, data });
  731. }
  732. /**
  733. * 处理子进程消息
  734. */
  735. events_child.on('message', async (message) => {
  736. const { callbacks } = Request;
  737. const { method, id, type, data } = message;
  738. if (method == 'get' && id) {
  739. let responseData = null;
  740. if (type == 'getGamesRelation') {
  741. responseData = getGamesRelation({ listEvents: true });
  742. }
  743. else if (type == 'getSetting') {
  744. responseData = await getSetting();
  745. }
  746. // else if (type == 'getSolutionHistory') {
  747. // responseData = getSolutionHistory();
  748. // }
  749. events_child.send({ type: 'response', id, data: responseData });
  750. }
  751. else if (method == 'post') {
  752. if (type == 'updateSolutions') {
  753. updateSolutions(data);
  754. }
  755. }
  756. else if (method == 'response' && id && callbacks[id]) {
  757. callbacks[id](data);
  758. delete callbacks[id];
  759. }
  760. });
  761. events_child.stderr?.on('data', data => {
  762. Logs.out('events_child stderr', data.toString());
  763. });
  764. Setting.onUpdate(fields => {
  765. postDataToChild('updateSetting', fields);
  766. });
  767. /**
  768. * 保存GAMES数据到缓存文件
  769. */
  770. const saveGamesToCache = () => {
  771. Cache.setData(GamesCacheFile, GAMES, err => {
  772. if (err) {
  773. Logs.out('Failed to save games cache:', err.message);
  774. }
  775. else {
  776. Logs.out('Games cache saved successfully');
  777. }
  778. });
  779. }
  780. /**
  781. * 从缓存文件加载GAMES数据
  782. */
  783. const loadGamesFromCache = () => {
  784. const gamesCacheData = Cache.getData(GamesCacheFile, true);
  785. Object.assign(GAMES, gamesCacheData);
  786. Logs.out('Games cache loaded successfully');
  787. }
  788. // 在模块加载时尝试从缓存恢复数据
  789. loadGamesFromCache();
  790. // 监听进程退出事件,保存GAMES数据
  791. process.on('exit', saveGamesToCache);
  792. process.on('SIGINT', () => {
  793. process.exit(0);
  794. });
  795. process.on('SIGTERM', () => {
  796. process.exit(0);
  797. });
  798. process.on('SIGUSR2', () => {
  799. process.exit(0);
  800. });
  801. module.exports = {
  802. updateLeaguesList, getFilteredLeagues,
  803. updateGamesList, updateGamesEvents,
  804. getGamesRelation,
  805. updateGamesResult,
  806. getSolutions,
  807. getTotalProfitWithSid,
  808. getTotalProfitWithBetInfo,
  809. }