GamesPs.js 24 KB

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