GamesPs.js 21 KB

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