GamesPs.js 22 KB

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