GamesPs.js 21 KB

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