GamesPs.js 25 KB

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