GamesPs.js 21 KB

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