GamesPs.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  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. ['jqs', 'ior_ot_1', 'ior_ot_2', 'ior_ot_3', 'ior_ot_4', 'ior_ot_5', 'ior_ot_6', 'ior_ot_7'],
  25. ];
  26. // 测试环境
  27. // const BASE_API_URL = 'https://dev.api.czxd8.com/api/p';
  28. const IS_DEV = process.env.NODE_ENV == 'development';
  29. const BASE_API_URL = IS_DEV ? 'https://api.qboss.vip/api' : 'http://172.17.222.37/api';
  30. const GAMES = {
  31. Leagues: {},
  32. Baselist: {},
  33. Relations: {},
  34. Solutions: {},
  35. UpdateTimestamp: {},
  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_API_URL}/p/syncLeague`, { mk, leagues }, { proxy: false })
  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_API_URL}/p/getLeagueTast?mk=${mk ?? ''}`, { proxy: false })
  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_API_URL}/p/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 cleanupBaseList = () => {
  156. // const baseList = GAMES.Baselist;
  157. // const nowTime = Date.now();
  158. // const expireTime = nowTime - 1000*60*60*3;
  159. // Object.keys(baseList).forEach(marketType => {
  160. // baseList[marketType] = baseList[marketType].filter(item => item.timestamp < expireTime);
  161. // });
  162. // }
  163. /**
  164. * 更新比赛列表
  165. */
  166. const updateGamesList = (({ platform, mk, games } = {}) => {
  167. return new Promise((resolve, reject) => {
  168. if (!platform || !games) {
  169. return reject(new Error('PLATFORM_GAMES_INVALID'));
  170. }
  171. syncGamesList({ platform, mk, games });
  172. resolve();
  173. });
  174. });
  175. /**
  176. * 提交盘口数据
  177. */
  178. const submitOdds = ({ platform, mk, games }) => {
  179. if (IS_DEV) {
  180. return Logs.out('syncOdds', { platform, mk, games });
  181. }
  182. axios.post(`${BASE_API_URL}/p/syncOdds`, { platform, mk, games}, { proxy: false })
  183. .then(res => {
  184. // Logs.out('syncOdds', { platform, mk, count: games.length }, res.data);
  185. })
  186. .catch(err => {
  187. Logs.out('syncOdds', { platform, mk }, err.message);
  188. });
  189. }
  190. /**
  191. * 同步基准盘口
  192. */
  193. const syncBaseEvents = ({ mk, games, outrights }) => {
  194. const { expireTimeEvents, expireTimeSpecial } = getSetting();
  195. const marketType = getMarketType(mk);
  196. const baseList = GAMES.Baselist;
  197. if (!baseList[marketType]) {
  198. return;
  199. }
  200. const baseMap = new Map(baseList[marketType].map(item => [item.eventId, item]));
  201. games?.forEach(game => {
  202. const { eventId, originId, stage, retime, score, wm, evtime, events } = game;
  203. const baseGame = baseMap.get(eventId);
  204. if (baseGame) {
  205. baseGame.originId = originId;
  206. baseGame.stage = stage;
  207. baseGame.retime = retime;
  208. baseGame.score = score;
  209. baseGame.wm = wm;
  210. baseGame.evtime = evtime;
  211. baseGame.events = events;
  212. }
  213. });
  214. outrights?.forEach(outright => {
  215. const { parentId, sptime, special } = outright;
  216. const baseGame = baseMap.get(parentId);
  217. if (baseGame) {
  218. baseGame.sptime = sptime;
  219. baseGame.special = special;
  220. }
  221. else {
  222. const originBaseMap = new Map(baseList[marketType].map(item => [item.originId, item]));
  223. const originBaseGame = originBaseMap.get(parentId);
  224. if (originBaseGame) {
  225. originBaseGame.sptime = sptime;
  226. originBaseGame.special = special;
  227. }
  228. }
  229. });
  230. if (games?.length) {
  231. const gamesList = baseList[marketType]?.map(game => {
  232. const { evtime, events, sptime, special, ...gameInfo } = game;
  233. const expireTimeEv = Date.now() - expireTimeEvents;
  234. const expireTimeSP = Date.now() - expireTimeSpecial;
  235. let odds = {};
  236. if (evtime > expireTimeEv) {
  237. odds = { ...odds, ...events };
  238. }
  239. if (sptime > expireTimeSP) {
  240. odds = { ...odds, ...special };
  241. }
  242. const matches = PS_IOR_KEYS.map(([label, ...keys]) => {
  243. let match = keys.map(key => {
  244. return {
  245. key,
  246. value: odds[key]?.v ?? 0,
  247. origin: odds[key]?.r
  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. game.matches = matches; // matches 也记录下来
  266. let uptime = evtime ?? 0;
  267. return { ...gameInfo, matches, uptime };
  268. });
  269. if (gamesList.filter(item => item.uptime > 0).length) {
  270. // if (mk == 2) {
  271. // Logs.out('syncBaseEvents', JSON.stringify({ mk, gamesList }, null, 2));
  272. // }
  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, timestamp, tp }) => {
  307. return new Promise((resolve, reject) => {
  308. if (!platform || (!games && !outrights)) {
  309. return reject(new Error('PLATFORM_GAMES_INVALID'));
  310. }
  311. const { UpdateTimestamp } = GAMES;
  312. if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
  313. // Logs.out('updateGamesEvents', { tp, timestamp });
  314. UpdateTimestamp[tp] = timestamp;
  315. }
  316. else {
  317. return resolve({ update: 0 });
  318. }
  319. if (platform == 'ps') {
  320. const update = syncBaseEvents({ mk, games, outrights });
  321. return resolve({ update });
  322. }
  323. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.[platform] ?? {});
  324. if (!relatedGames.length) {
  325. return resolve({ update: 0 });
  326. }
  327. const updateCount = {
  328. update: 0
  329. };
  330. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  331. games?.forEach(game => {
  332. const { eventId, evtime, events, stage, retime, score, wm } = game;
  333. const relatedGame = relatedMap.get(eventId);
  334. if (relatedGame) {
  335. relatedGame.evtime = evtime;
  336. relatedGame.events = events;
  337. relatedGame.stage = stage;
  338. relatedGame.retime = retime;
  339. relatedGame.score = score;
  340. relatedGame.wm = wm;
  341. updateCount.update ++;
  342. }
  343. });
  344. outrights?.forEach(outright => {
  345. const { parentId, sptime, special } = outright;
  346. const relatedGame = relatedMap.get(parentId);
  347. if (relatedGame) {
  348. relatedGame.sptime = sptime;
  349. relatedGame.special = special;
  350. updateCount.update ++;
  351. }
  352. });
  353. resolve(updateCount);
  354. });
  355. }
  356. /**
  357. * 获取比赛盘口
  358. */
  359. const getGamesEvents = ({ platform, relIds = [] } = {}) => {
  360. if (!relIds.length) {
  361. return null;
  362. }
  363. const idSet = new Set(relIds);
  364. const relations = { ...GAMES.Relations };
  365. Object.keys(relations).forEach(id => {
  366. if (idSet.size && !idSet.has(+id)) {
  367. delete relations[id];
  368. }
  369. });
  370. if (platform) {
  371. return Object.values(relations).map(rel => rel[platform] ?? {});
  372. }
  373. const gamesEvents = {};
  374. Object.values(relations).forEach(({ rel }) => {
  375. Object.keys(rel).forEach(platform => {
  376. const game = rel[platform] ?? {};
  377. const { eventId, events, special } = game;
  378. if (!gamesEvents[platform]) {
  379. gamesEvents[platform] = {};
  380. }
  381. gamesEvents[platform][eventId] = { ...events, ...special };
  382. });
  383. });
  384. return gamesEvents;
  385. }
  386. /**
  387. * 获取关联比赛
  388. */
  389. const getDevGameTast = () => {
  390. return new Promise((resolve) => {
  391. const data = Cache.getData(DevGameTastFile, true);
  392. resolve({data});
  393. });
  394. }
  395. const fetchGamesRelation = async (mk='') => {
  396. const getGameTast = Promise.all([
  397. getDevGameTast(),
  398. axios.get(`${BASE_API_URL}/p/getGameTast?mk=${mk}`, { proxy: false })
  399. ]);
  400. return getGameTast.then(([res1, res2]) => {
  401. const resData = res1.data ?? res2.data;
  402. if (resData.code == 0) {
  403. const nowTime = Date.now();
  404. const gamesRelation = resData.data?.filter(item => {
  405. const timestamp = new Date(item.timestamp).getTime();
  406. if (nowTime > timestamp) {
  407. item.mk = 2;
  408. }
  409. item.timestamp = timestamp;
  410. const expireTime = timestamp + 1000*60*60*3;
  411. return expireTime > nowTime;
  412. }).map(item => {
  413. const {
  414. id, mk, league_name,
  415. event_id: ps_event_id,
  416. league_id: ps_league_id,
  417. team_home_name: ps_team_home_name,
  418. team_away_name: ps_team_away_name,
  419. ob_event_id, ob_league_id,
  420. ob_team_home_name,
  421. ob_team_away_name,
  422. hg_event_id, hg_league_id,
  423. hg_team_home_name,
  424. hg_team_away_name,
  425. timestamp,
  426. } = item;
  427. const rel = {
  428. ps: {
  429. eventId: +ps_event_id,
  430. leagueId: +ps_league_id,
  431. leagueName: league_name,
  432. teamHomeName: ps_team_home_name,
  433. teamAwayName: ps_team_away_name,
  434. timestamp
  435. },
  436. ob: ob_event_id ? {
  437. eventId: +ob_event_id,
  438. leagueId: +ob_league_id,
  439. leagueName: league_name,
  440. teamHomeName: ob_team_home_name,
  441. teamAwayName: ob_team_away_name,
  442. timestamp
  443. } : null,
  444. hg: hg_event_id ? {
  445. eventId: +hg_event_id,
  446. leagueId: +hg_league_id,
  447. leagueName: league_name,
  448. teamHomeName: hg_team_home_name,
  449. teamAwayName: hg_team_away_name,
  450. timestamp
  451. } : null
  452. };
  453. return { id: ps_event_id, mk, rel, timestamp };
  454. }) ?? [];
  455. return gamesRelation;
  456. }
  457. return Promise.reject(new Error(resData.message));
  458. });
  459. }
  460. const getGamesRelation = ({ mk=-1, ids, listEvents } = {}) => {
  461. let idsSet = null;
  462. if (ids?.length) {
  463. idsSet = new Set(ids);
  464. }
  465. const relations = Object.values(GAMES.Relations).filter(item => {
  466. if (idsSet && !idsSet.has(item.id)) {
  467. return false;
  468. }
  469. return mk == -1 || 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. if (updateCount.add || updateCount.update || updateCount.delete) {
  530. Logs.out('updateGamesRelation', updateCount);
  531. }
  532. else {
  533. Logs.outDev('updateGamesRelation', updateCount);
  534. }
  535. })
  536. .catch(err => {
  537. Logs.out('updateGamesRelation', err.message);
  538. })
  539. .finally(() => {
  540. setTimeout(updateGamesRelation, 60000);
  541. });
  542. }
  543. updateGamesRelation();
  544. const gamesRelationCleanup = () => {
  545. const relations = Object.values(GAMES.Relations);
  546. const expireTime = Date.now() - 1000*60;
  547. relations.forEach(item => {
  548. const { rel } = item;
  549. Object.keys(rel).forEach(platform => {
  550. const { evtime, sptime } = rel[platform];
  551. if (evtime && evtime < expireTime) {
  552. delete rel[platform].events;
  553. delete rel[platform].evtime;
  554. }
  555. if (sptime && sptime < expireTime) {
  556. delete rel[platform].special;
  557. delete rel[platform].sptime;
  558. }
  559. });
  560. });
  561. }
  562. /**
  563. * 同步比赛结果
  564. */
  565. const syncGamesResult = async (result) => {
  566. if (IS_DEV) {
  567. return Logs.out('updateGamesResult', result);
  568. }
  569. axios.post(`${BASE_API_URL}/p/syncMatchResult`, result, { proxy: false })
  570. .then(res => {
  571. // Logs.out('syncMatchResult', res.data);
  572. })
  573. .catch(err => {
  574. Logs.out('syncMatchResult', err.message);
  575. });
  576. }
  577. /**
  578. * 更新比赛结果
  579. */
  580. const updateGamesResult = (result) => {
  581. syncGamesResult(result);
  582. return Promise.resolve();
  583. }
  584. /**
  585. * 同步中单方案
  586. */
  587. const syncSolutions = (solutions) => {
  588. if (IS_DEV) {
  589. return Logs.out('syncSolutions', solutions);
  590. }
  591. axios.post(`${BASE_API_URL}/p/syncDsOpportunity`, solutions, { proxy: false })
  592. .then(res => {
  593. // Logs.out('syncSolutions', res.data);
  594. })
  595. .catch(err => {
  596. Logs.out('syncSolutions', err.message);
  597. });
  598. }
  599. /**
  600. * 更新中单方案
  601. */
  602. const getCprKey = (cpr) => {
  603. const { k, p, v } = cpr;
  604. return `${k}_${p}_${v}`;
  605. }
  606. const compareCpr = (cpr1, cpr2) => {
  607. const key1 = getCprKey(cpr1);
  608. const key2 = getCprKey(cpr2);
  609. return key1 === key2;
  610. }
  611. const updateSolutions = (solutions, eventsLogsMap) => {
  612. if (solutions?.length) {
  613. const solutionsHistory = GAMES.Solutions;
  614. const updateIds = { add: [], update: [], retain: [], remove: [] }
  615. solutions.forEach(item => {
  616. const { sid, cpr, sol: { win_average, win_profit_rate } } = item;
  617. if (!solutionsHistory[sid]) {
  618. solutionsHistory[sid] = item;
  619. updateIds.add.push(sid);
  620. return;
  621. }
  622. const historySolution = solutionsHistory[sid];
  623. if (historySolution.sol.win_average !== win_average ||
  624. historySolution.sol.win_profit_rate !== win_profit_rate ||
  625. !compareCpr(historySolution.cpr, cpr)) {
  626. solutionsHistory[sid] = item;
  627. updateIds.update.push(sid);
  628. return;
  629. }
  630. const { timestamp } = item;
  631. historySolution.timestamp = timestamp;
  632. updateIds.retain.push(sid);
  633. });
  634. const solutionsMap = new Map(solutions.map(item => [item.sid, item]));
  635. Object.keys(solutionsHistory).forEach(sid => {
  636. if (!solutionsMap.has(sid)) {
  637. delete solutionsHistory[sid];
  638. updateIds.remove.push(sid);
  639. }
  640. });
  641. const solutionUpdate = {};
  642. Object.keys(updateIds).forEach(key => {
  643. if (key == 'retain' || key == 'remove') {
  644. solutionUpdate[key] = updateIds[key];
  645. }
  646. else {
  647. solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  648. }
  649. });
  650. syncSolutions(solutionUpdate);
  651. if (updateIds.add.length / solutions.length > 0.25 ||
  652. updateIds.remove.length / solutions.length > 0.25
  653. ) {
  654. const { expireEvents, removeEvents } = eventsLogsMap;
  655. const expireEvemtsMap = {};
  656. expireEvents.forEach(item => {
  657. const { mk, platform, info, evExpire, spExpire, evtime, sptime } = item;
  658. if (!expireEvemtsMap[mk]) {
  659. expireEvemtsMap[mk] = {};
  660. }
  661. if (!expireEvemtsMap[mk][platform]) {
  662. expireEvemtsMap[mk][platform] = {};
  663. }
  664. if (!expireEvemtsMap[mk][platform].list) {
  665. expireEvemtsMap[mk][platform].list = [];
  666. }
  667. if (!expireEvemtsMap[mk][platform].evtime) {
  668. expireEvemtsMap[mk][platform].evtime = evtime;
  669. }
  670. if (!expireEvemtsMap[mk][platform].sptime) {
  671. expireEvemtsMap[mk][platform].sptime = sptime;
  672. }
  673. expireEvemtsMap[mk][platform].list.push({ info, evExpire, spExpire, evtime, sptime });
  674. });
  675. Object.keys(expireEvemtsMap).forEach(mk => {
  676. Object.keys(expireEvemtsMap[mk]).forEach(platform => {
  677. Logs.out('invalid events, mk %d, platform %s, expire %d, evtime %d, sptime %d',
  678. mk, platform,
  679. expireEvemtsMap[mk][platform].list.length,
  680. expireEvemtsMap[mk][platform].evtime,
  681. expireEvemtsMap[mk][platform].sptime,
  682. )
  683. });
  684. });
  685. Logs.out('solutions add %d, update %d, retain %d, remove %d',
  686. updateIds.add.length, updateIds.update.length, updateIds.retain.length, updateIds.remove.length);
  687. }
  688. else {
  689. Logs.outDev('solutions update complete');
  690. }
  691. }
  692. }
  693. /**
  694. * 获取中单方案
  695. */
  696. const getSolutions = async ({ win_min, with_events, mk=-1 }) => {
  697. // Logs.out('getSolutions', win_min);
  698. const filterMarketType = +mk;
  699. const { minShowAmount } = getSetting();
  700. const solutionsList = Object.values(GAMES.Solutions);
  701. const gamesRelation = getGamesRelation();
  702. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  703. const mkCount = {
  704. all: 0,
  705. rollball: 0,
  706. today: 0,
  707. early: 0,
  708. }
  709. let solutions = solutionsList.filter(item => {
  710. const { sol: { win_average } } = item;
  711. return win_average >= (win_min ?? minShowAmount);
  712. })
  713. .map(item => {
  714. const { info: { id } } = item;
  715. const { mk, rel } = relationsMap.get(id);
  716. const marketType = getMarketType(mk);
  717. mkCount.all ++;
  718. mkCount[marketType] ++;
  719. return {
  720. ...item,
  721. info: { id, mk, ...rel }
  722. }
  723. });
  724. if (mk >= 0) {
  725. solutions = solutions.filter(item => {
  726. const { info: { mk } } = item;
  727. return mk == filterMarketType;
  728. });
  729. }
  730. solutions = solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  731. const relIds = solutions.map(item => item.info.id);
  732. let gamesEvents;
  733. if (with_events) {
  734. gamesEvents = getGamesEvents({ relIds });
  735. }
  736. return { solutions, gamesEvents, mkCount };
  737. }
  738. /**
  739. * 获取中单方案并按照比赛分组
  740. */
  741. const getGamesSolutions = async ({ win_min, with_events, mk=-1 }) => {
  742. const filterMarketType = +mk;
  743. const { minShowAmount } = getSetting();
  744. const solutionsList = Object.values(GAMES.Solutions);
  745. const gamesRelation = getGamesRelation({ listEvents: with_events });
  746. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  747. const mkCount = {
  748. all: 0,
  749. rollball: 0,
  750. today: 0,
  751. early: 0,
  752. }
  753. const solutionsMap = {};
  754. solutionsList.filter(item => {
  755. const { sol: { win_average } } = item;
  756. return win_average >= (win_min ?? minShowAmount);
  757. }).forEach(item => {
  758. const { info: { id }, ...solution } = item;
  759. const gameRelation = relationsMap.get(id);
  760. if (!solutionsMap[id]) {
  761. solutionsMap[id] = { ...gameRelation, solutions: [] };
  762. }
  763. solutionsMap[id].solutions.push(solution);
  764. });
  765. const gamesSolutions = Object.values(solutionsMap)
  766. .filter(item => {
  767. const { mk, solutions } = item;
  768. const marketType = getMarketType(mk);
  769. mkCount.all ++;
  770. mkCount[marketType] ++;
  771. solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  772. return filterMarketType == -1 || filterMarketType == mk;
  773. })
  774. .sort((a, b) => b.solutions[0].sol.win_average - a.solutions[0].sol.win_average);
  775. return { gamesSolutions, mkCount };
  776. }
  777. /**
  778. * 获取单个中单方案
  779. */
  780. const getSolution = async (sid) => {
  781. if (!sid) {
  782. return Promise.reject(new Error('sid is required'));
  783. }
  784. const solution = GAMES.Solutions[sid];
  785. if (!solution) {
  786. return Promise.reject(new Error('solution not found'));
  787. }
  788. return solution;
  789. }
  790. /**
  791. * 通过比赛 ID 获取中单方案
  792. */
  793. const getSolutionsByIds = async (ids) => {
  794. const baseList = Object.values(GAMES.Baselist).flat();
  795. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  796. const result = {};
  797. ids.forEach(id => {
  798. const baseGame = baseMap.get(id);
  799. result[id] = {};
  800. result[id].matches = baseGame?.matches ?? [];
  801. result[id].sols = [];
  802. });
  803. Object.values(GAMES.Solutions).forEach(item => {
  804. const { info: { id } } = item;
  805. if (result[id]) {
  806. result[id].sols.push(item);
  807. }
  808. });
  809. return result;
  810. }
  811. /**
  812. * 清理中单方案
  813. */
  814. const solutionsCleanup = () => {
  815. const solutionsHistory = GAMES.Solutions;
  816. const updateIds = { remove: [] }
  817. Object.keys(solutionsHistory).forEach(sid => {
  818. const { timestamp } = solutionsHistory[sid];
  819. const nowTime = Date.now();
  820. if (nowTime - timestamp > 1000*60) {
  821. delete solutionsHistory[sid];
  822. updateIds.remove.push(sid);
  823. return;
  824. }
  825. const solution = solutionsHistory[sid];
  826. const eventTime = solution.info.timestamp;
  827. if (nowTime > eventTime) {
  828. delete solutionsHistory[sid];
  829. updateIds.remove.push(sid);
  830. }
  831. });
  832. if (updateIds.remove.length) {
  833. syncSolutions(updateIds);
  834. }
  835. }
  836. /**
  837. * 清理更新时间戳
  838. */
  839. const cleanupUpdateTimestamp = () => {
  840. const updateTimestamp = GAMES.UpdateTimestamp;
  841. const nowTime = Date.now();
  842. const expireTime = nowTime - 1000*60;
  843. Object.keys(updateTimestamp).forEach(key => {
  844. if (updateTimestamp[key] < expireTime) {
  845. delete updateTimestamp[key];
  846. }
  847. });
  848. }
  849. /**
  850. * 定时清理中单方案
  851. * 定时清理盘口信息
  852. */
  853. setInterval(() => {
  854. // cleanupBaseList();
  855. solutionsCleanup();
  856. gamesRelationCleanup();
  857. cleanupUpdateTimestamp();
  858. }, 1000*30);
  859. /**
  860. * 获取综合利润
  861. */
  862. const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
  863. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  864. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  865. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  866. const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
  867. return profit;
  868. }
  869. /**
  870. * 通过 sid 获取综合利润
  871. */
  872. const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
  873. const preSolution = GAMES.Solutions[sid1];
  874. const subSolution = GAMES.Solutions[sid2];
  875. const sol1 = preSolution?.sol;
  876. const sol2 = subSolution?.sol;
  877. if (!sol1) {
  878. return Promise.reject(new Error('sid1 已失效'));
  879. }
  880. if (!sol2) {
  881. return Promise.reject(new Error('sid2 已失效'));
  882. }
  883. const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  884. return { profit, solutions: [preSolution, subSolution] };
  885. }
  886. /**
  887. * 通过盘口信息获取综合利润
  888. */
  889. const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
  890. if (!betInfo1?.cross_type) {
  891. return Promise.reject(new Error('第一个下注信息无效'));
  892. }
  893. if (!betInfo2?.cross_type) {
  894. return Promise.reject(new Error('第二个下注信息无效'));
  895. }
  896. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  897. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  898. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  899. if (fixed) {
  900. return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
  901. }
  902. const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
  903. return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  904. }
  905. /**
  906. * 同步内盘返点设置
  907. */
  908. const syncInnerRebate = () => {
  909. axios.get(`${BASE_API_URL}/p/QbossReturnRatio`, { proxy: false })
  910. .then(res => {
  911. const { data } = res;
  912. if (!data?.data) {
  913. throw new Error('syncInnerRebate data is empty');
  914. }
  915. const ratio = +data.data;
  916. const innerRebateRatio = getSetting('innerRebateRatio');
  917. if (ratio != innerRebateRatio) {
  918. Setting.update({ innerRebateRatio: ratio });
  919. Logs.outDev('syncInnerRebate from %d to %d', innerRebateRatio, ratio);
  920. }
  921. })
  922. .catch(err => {
  923. Logs.out('syncInnerRebate', err.message);
  924. })
  925. .finally(() => {
  926. setTimeout(() => {
  927. syncInnerRebate();
  928. }, 1000*15);
  929. });
  930. }
  931. syncInnerRebate();
  932. /**
  933. * 异常通知
  934. */
  935. const notifyException = (message) => {
  936. if (IS_DEV) {
  937. return Logs.out('notifyException', { message });
  938. }
  939. const chat_id = -1003032820471;
  940. axios.get(`${BASE_API_URL}/telegram/jump`, { params: { chat_id, message } }, { proxy: false })
  941. .then(() => {
  942. Logs.out('notifyException', '通知成功');
  943. })
  944. .catch(err => {
  945. Logs.out('notifyException', err.message);
  946. });
  947. }
  948. /**
  949. * 从子进程获取数据
  950. */
  951. const getDataFromChild = (type, callback) => {
  952. const id = ++Request.count;
  953. Request.callbacks[id] = callback;
  954. events_child.send({ method: 'get', id, type });
  955. }
  956. /**
  957. * 向子进程发送数据
  958. */
  959. const postDataToChild = (type, data) => {
  960. events_child.send({ method: 'post', type, data });
  961. }
  962. /**
  963. * 处理子进程消息
  964. */
  965. events_child.on('message', async (message) => {
  966. const { callbacks } = Request;
  967. const { method, id, type, data } = message;
  968. if (method == 'get' && id) {
  969. let responseData = null;
  970. if (type == 'getGamesRelation') {
  971. responseData = getGamesRelation({ listEvents: true });
  972. }
  973. else if (type == 'getSetting') {
  974. responseData = getSetting();
  975. }
  976. // else if (type == 'getSolutionHistory') {
  977. // responseData = getSolutionHistory();
  978. // }
  979. events_child.send({ type: 'response', id, data: responseData });
  980. }
  981. else if (method == 'post') {
  982. if (type == 'updateSolutions') {
  983. updateSolutions(data.solutions, data.eventsLogsMap);
  984. }
  985. }
  986. else if (method == 'response' && id && callbacks[id]) {
  987. callbacks[id](data);
  988. delete callbacks[id];
  989. }
  990. });
  991. events_child.stderr?.on('data', data => {
  992. Logs.out('events_child stderr', data.toString());
  993. });
  994. const settingUpdate = (fields) => {
  995. updateSetting(fields);
  996. postDataToChild('updateSetting', fields);
  997. }
  998. const syncSetting = async () => {
  999. const setting = await Setting.get();
  1000. settingUpdate(setting.toObject());
  1001. }
  1002. syncSetting();
  1003. Setting.onUpdate(settingUpdate);
  1004. /**
  1005. * 保存GAMES数据到缓存文件
  1006. */
  1007. const saveGamesToCache = () => {
  1008. Cache.setData(GamesCacheFile, GAMES, err => {
  1009. if (err) {
  1010. Logs.out('Failed to save games cache:', err.message);
  1011. }
  1012. else {
  1013. Logs.out('Games cache saved successfully');
  1014. }
  1015. });
  1016. }
  1017. /**
  1018. * 从缓存文件加载GAMES数据
  1019. */
  1020. const loadGamesFromCache = () => {
  1021. const gamesCacheData = Cache.getData(GamesCacheFile, true);
  1022. Object.keys(GAMES).forEach(key => {
  1023. if (gamesCacheData[key]) {
  1024. GAMES[key] = gamesCacheData[key];
  1025. }
  1026. });
  1027. Logs.out('Games cache loaded successfully');
  1028. }
  1029. // 在模块加载时尝试从缓存恢复数据
  1030. loadGamesFromCache();
  1031. // 监听进程退出事件,保存GAMES数据
  1032. process.on('exit', saveGamesToCache);
  1033. process.on('SIGINT', () => {
  1034. process.exit(0);
  1035. });
  1036. process.on('SIGTERM', () => {
  1037. process.exit(0);
  1038. });
  1039. process.on('SIGUSR2', () => {
  1040. process.exit(0);
  1041. });
  1042. module.exports = {
  1043. updateLeaguesList, getFilteredLeagues,
  1044. updateGamesList, updateGamesEvents,
  1045. getGamesRelation,
  1046. updateGamesResult,
  1047. getSolutions, getGamesSolutions, getSolution, getSolutionsByIds,
  1048. getTotalProfitWithSid,
  1049. getTotalProfitWithBetInfo,
  1050. notifyException,
  1051. }