GamesPs.js 24 KB

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