GamesPs.js 23 KB

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