GamesPs.js 21 KB

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