GamesPs.js 23 KB

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