GamesPs.js 22 KB

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