GamesPs.js 20 KB

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