GamesPs.js 21 KB

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