GamesPs.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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. update: 0,
  406. delete: 0
  407. };
  408. gamesRelation.forEach(item => {
  409. const { id, mk } = item;
  410. const oldItem = GAMES.Relations[id];
  411. if (!oldItem) {
  412. GAMES.Relations[id] = item;
  413. updateCount.add ++;
  414. }
  415. else if (oldItem.mk != mk) {
  416. GAMES.Relations[id] = item;
  417. updateCount.update ++;
  418. }
  419. });
  420. const relations = new Set(gamesRelation.map(item => +item.id));
  421. Object.keys(GAMES.Relations).forEach(id => {
  422. if (!relations.has(+id)) {
  423. delete GAMES.Relations[id];
  424. updateCount.delete ++;
  425. }
  426. else {
  427. const { rel } = GAMES.Relations[id];
  428. const relTime = rel.ps?.timestamp;
  429. if (relTime && relTime < Date.now()) {
  430. delete GAMES.Relations[id];
  431. updateCount.delete ++;
  432. }
  433. }
  434. });
  435. Logs.outDev('updateGamesRelation', updateCount);
  436. })
  437. .catch(err => {
  438. Logs.out('updateGamesRelation', err.message);
  439. })
  440. .finally(() => {
  441. setTimeout(updateGamesRelation, 60000);
  442. });
  443. }
  444. updateGamesRelation();
  445. const gamesRelationCleanup = () => {
  446. const relations = Object.values(GAMES.Relations);
  447. const expireTime = Date.now() - 1000*60;
  448. relations.forEach(item => {
  449. const { rel } = item;
  450. Object.keys(rel).forEach(platform => {
  451. const { evtime, sptime } = rel[platform];
  452. if (evtime && evtime < expireTime) {
  453. delete rel[platform].events;
  454. delete rel[platform].evtime;
  455. }
  456. if (sptime && sptime < expireTime) {
  457. delete rel[platform].special;
  458. delete rel[platform].sptime;
  459. }
  460. });
  461. });
  462. }
  463. /**
  464. * 同步比赛结果
  465. */
  466. const syncGamesResult = async (result) => {
  467. if (IS_DEV) {
  468. return Logs.out('updateGamesResult', result);
  469. }
  470. axios.post(`${BASE_URL}/syncMatchResult`, result)
  471. .then(res => {
  472. // Logs.out('syncMatchResult', res.data);
  473. })
  474. .catch(err => {
  475. Logs.out('syncMatchResult', err.message);
  476. });
  477. }
  478. /**
  479. * 更新比赛结果
  480. */
  481. const updateGamesResult = (result) => {
  482. syncGamesResult(result);
  483. return Promise.resolve();
  484. }
  485. /**
  486. * 同步中单方案
  487. */
  488. const syncSolutions = (solutions) => {
  489. if (IS_DEV) {
  490. return Logs.out('syncSolutions', solutions);
  491. }
  492. axios.post(`${BASE_URL}/syncDsOpportunity`, solutions)
  493. .then(res => {
  494. // Logs.out('syncSolutions', res.data);
  495. })
  496. .catch(err => {
  497. Logs.out('syncSolutions', err.message);
  498. });
  499. }
  500. /**
  501. * 更新中单方案
  502. */
  503. const getCprKey = (cpr) => {
  504. const { k, p, v } = cpr;
  505. return `${k}_${p}_${v}`;
  506. }
  507. const compareCpr = (cpr1, cpr2) => {
  508. const key1 = getCprKey(cpr1);
  509. const key2 = getCprKey(cpr2);
  510. return key1 === key2;
  511. }
  512. const updateSolutions = (solutions) => {
  513. if (solutions?.length) {
  514. const solutionsHistory = GAMES.Solutions;
  515. const updateIds = { add: [], update: [] }
  516. solutions.forEach(item => {
  517. const { sid, cpr, sol: { win_average } } = item;
  518. if (!solutionsHistory[sid]) {
  519. solutionsHistory[sid] = item;
  520. updateIds.add.push(sid);
  521. return;
  522. }
  523. const historySolution = solutionsHistory[sid];
  524. if (historySolution.sol.win_average !== win_average || !compareCpr(historySolution.cpr, cpr)) {
  525. solutionsHistory[sid] = item;
  526. updateIds.update.push(sid);
  527. return;
  528. }
  529. const { timestamp } = item;
  530. solutionsHistory[sid].timestamp = timestamp;
  531. });
  532. if (updateIds.add.length || updateIds.update.length) {
  533. const solutionUpdate = {};
  534. Object.keys(updateIds).forEach(key => {
  535. solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  536. });
  537. syncSolutions(solutionUpdate);
  538. // Logs.outDev('solutions history update', solutionUpdate);
  539. }
  540. }
  541. }
  542. /**
  543. * 获取中单方案
  544. */
  545. const getSolutions = async () => {
  546. const { minShowAmount } = await getSetting();
  547. const solutionsList = Object.values(GAMES.Solutions);
  548. const gamesRelation = getGamesRelation();
  549. const relationsMap = new Map(gamesRelation.map(item => [item.id, item.rel]));
  550. const solutions = solutionsList.sort((a, b) => b.sol.win_average - a.sol.win_average)
  551. .filter(item => {
  552. const { sol: { win_average } } = item;
  553. return win_average >= minShowAmount;
  554. })
  555. .map(item => {
  556. const { info: { id } } = item;
  557. const relation = relationsMap.get(id);
  558. return {
  559. ...item,
  560. info: { id, ...relation }
  561. }
  562. });
  563. const relIds = solutions.map(item => item.info.id);
  564. const gamesEvents = getGamesEvents({ relIds });
  565. return { solutions, gamesEvents };
  566. }
  567. /**
  568. * 清理中单方案
  569. */
  570. const solutionsCleanup = () => {
  571. const solutionsHistory = GAMES.Solutions;
  572. const updateIds = { remove: [] }
  573. Object.keys(solutionsHistory).forEach(sid => {
  574. const { timestamp } = solutionsHistory[sid];
  575. const nowTime = Date.now();
  576. if (nowTime - timestamp > 1000*60) {
  577. delete solutionsHistory[sid];
  578. updateIds.remove.push(sid);
  579. return;
  580. }
  581. const solution = solutionsHistory[sid];
  582. const eventTime = solution.info.timestamp;
  583. if (nowTime > eventTime) {
  584. delete solutionsHistory[sid];
  585. updateIds.remove.push(sid);
  586. }
  587. });
  588. if (updateIds.remove.length) {
  589. syncSolutions(updateIds);
  590. }
  591. }
  592. /**
  593. * 定时清理中单方案
  594. * 定时清理盘口信息
  595. */
  596. setInterval(() => {
  597. solutionsCleanup();
  598. gamesRelationCleanup();
  599. }, 1000*30);
  600. /**
  601. * 获取综合利润
  602. */
  603. const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
  604. const { innerDefaultAmount, innerRebateRatio } = await getSetting();
  605. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  606. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  607. const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
  608. return profit;
  609. }
  610. /**
  611. * 通过 sid 获取综合利润
  612. */
  613. const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
  614. const preSolution = GAMES.Solutions[sid1];
  615. const subSolution = GAMES.Solutions[sid2];
  616. const sol1 = preSolution?.sol;
  617. const sol2 = subSolution?.sol;
  618. if (!sol1) {
  619. return Promise.reject(new Error('sid1 已失效'));
  620. }
  621. if (!sol2) {
  622. return Promise.reject(new Error('sid2 已失效'));
  623. }
  624. const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  625. return { profit, solutions: [preSolution, subSolution] };
  626. }
  627. /**
  628. * 通过盘口信息获取综合利润
  629. */
  630. const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
  631. const { innerDefaultAmount, innerRebateRatio } = await getSetting();
  632. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  633. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  634. if (fixed) {
  635. return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
  636. }
  637. const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
  638. return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  639. }
  640. /**
  641. * 获取后台设置
  642. */
  643. const getSetting = async () => {
  644. return Setting.get();
  645. }
  646. /**
  647. * 从子进程获取数据
  648. */
  649. const getDataFromChild = (type, callback) => {
  650. const id = ++Request.count;
  651. Request.callbacks[id] = callback;
  652. events_child.send({ method: 'get', id, type });
  653. }
  654. /**
  655. * 向子进程发送数据
  656. */
  657. const postDataToChild = (type, data) => {
  658. events_child.send({ method: 'post', type, data });
  659. }
  660. /**
  661. * 处理子进程消息
  662. */
  663. events_child.on('message', async (message) => {
  664. const { callbacks } = Request;
  665. const { method, id, type, data } = message;
  666. if (method == 'get' && id) {
  667. let responseData = null;
  668. if (type == 'getGamesRelation') {
  669. responseData = getGamesRelation({ listEvents: true });
  670. }
  671. else if (type == 'getSetting') {
  672. responseData = await getSetting();
  673. }
  674. // else if (type == 'getSolutionHistory') {
  675. // responseData = getSolutionHistory();
  676. // }
  677. events_child.send({ type: 'response', id, data: responseData });
  678. }
  679. else if (method == 'post') {
  680. if (type == 'updateSolutions') {
  681. updateSolutions(data);
  682. }
  683. }
  684. else if (method == 'response' && id && callbacks[id]) {
  685. callbacks[id](data);
  686. delete callbacks[id];
  687. }
  688. });
  689. events_child.stderr?.on('data', data => {
  690. Logs.out('events_child stderr', data.toString());
  691. });
  692. Setting.onUpdate(fields => {
  693. postDataToChild('updateSetting', fields);
  694. });
  695. /**
  696. * 保存GAMES数据到缓存文件
  697. */
  698. const saveGamesToCache = () => {
  699. Cache.setData(GamesCacheFile, GAMES, err => {
  700. if (err) {
  701. Logs.out('Failed to save games cache:', err.message);
  702. }
  703. else {
  704. Logs.out('Games cache saved successfully');
  705. }
  706. });
  707. }
  708. /**
  709. * 从缓存文件加载GAMES数据
  710. */
  711. const loadGamesFromCache = () => {
  712. const gamesCacheData = Cache.getData(GamesCacheFile, true);
  713. Object.assign(GAMES, gamesCacheData);
  714. Logs.out('Games cache loaded successfully');
  715. }
  716. // 在模块加载时尝试从缓存恢复数据
  717. loadGamesFromCache();
  718. // 监听进程退出事件,保存GAMES数据
  719. process.on('exit', saveGamesToCache);
  720. process.on('SIGINT', () => {
  721. process.exit(0);
  722. });
  723. process.on('SIGTERM', () => {
  724. process.exit(0);
  725. });
  726. process.on('SIGUSR2', () => {
  727. process.exit(0);
  728. });
  729. module.exports = {
  730. updateLeaguesList, getFilteredLeagues,
  731. updateGamesList, updateGamesEvents,
  732. getGamesRelation,
  733. updateGamesResult,
  734. getSolutions,
  735. getTotalProfitWithSid,
  736. getTotalProfitWithBetInfo,
  737. }