GamesPs.js 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  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_API_URL = 'https://dev.api.czxd8.com/api/p';
  30. const IS_DEV = process.env.NODE_ENV == 'development';
  31. const BASE_API_URL = IS_DEV ? 'https://api.qboss.vip/api' : 'http://172.17.222.37/api';
  32. const GAMES = {
  33. Leagues: {},
  34. Baselist: {},
  35. Relations: {},
  36. Solutions: {},
  37. UpdateTimestamp: {},
  38. };
  39. const Request = {
  40. callbacks: {},
  41. count: 0,
  42. }
  43. /**
  44. * 精确浮点数字
  45. * @param {number} number
  46. * @param {number} x
  47. * @returns {number}
  48. */
  49. const fixFloat = (number, x=2) => {
  50. return parseFloat(number.toFixed(x));
  51. }
  52. /**
  53. * 获取市场类型
  54. */
  55. const getMarketType = (mk) => {
  56. if (mk == 0) {
  57. return 'early';
  58. }
  59. else if (mk == 2) {
  60. return 'rollball';
  61. }
  62. return 'today';
  63. }
  64. /**
  65. * 同步联赛列表
  66. */
  67. const syncLeaguesList = ({ mk, leagues }) => {
  68. if (IS_DEV) {
  69. return Logs.out('syncLeaguesList', { mk, leagues });
  70. }
  71. axios.post(`${BASE_API_URL}/p/syncLeague`, { mk, leagues }, { proxy: false })
  72. .then(res => {
  73. // Logs.out('syncLeaguesList', res.data);
  74. })
  75. .catch(err => {
  76. Logs.out('syncLeaguesList', err.message);
  77. });
  78. }
  79. /**
  80. * 更新联赛列表
  81. */
  82. const updateLeaguesList = ({ mk, leagues }) => {
  83. const leaguesMap = GAMES.Leagues;
  84. const nowTime = Date.now();
  85. const expireTime = nowTime - 1000 * 60 * 5;
  86. if (!leaguesMap[mk]) {
  87. leaguesMap[mk] = {
  88. timestamp: 0,
  89. leagues: [],
  90. };
  91. }
  92. if (leaguesMap[mk].timestamp < expireTime ||
  93. JSON.stringify(leaguesMap[mk].leagues) != JSON.stringify(leagues)) {
  94. leaguesMap[mk].leagues = leagues;
  95. leaguesMap[mk].timestamp = nowTime;
  96. syncLeaguesList({ mk, leagues });
  97. return leagues.length;
  98. }
  99. return 0;
  100. }
  101. /**
  102. * 获取筛选过的联赛
  103. */
  104. const getFilteredLeagues = async (mk) => {
  105. return axios.get(`${BASE_API_URL}/p/getLeagueTast?mk=${mk ?? ''}`, { proxy: false })
  106. .then(res => {
  107. if (res.data.code == 0) {
  108. return res.data.data;
  109. }
  110. return Promise.reject(new Error(res.data.message));
  111. });
  112. }
  113. /**
  114. * 同步比赛列表到服务器
  115. */
  116. const syncGamesList = ({ platform, mk, games }) => {
  117. if (IS_DEV) {
  118. return Logs.out('syncGamesList', { platform, mk, games });
  119. }
  120. axios.post(`${BASE_API_URL}/p/syncGames`, { platform, mk, games })
  121. .then(res => {
  122. // Logs.out('syncGamesList', { platform, mk, count: games.length }, res.data);
  123. })
  124. .catch(err => {
  125. Logs.out('syncGamesList', { platform, mk }, err.message);
  126. });
  127. }
  128. /**
  129. * 同步基准比赛列表
  130. */
  131. const syncBaseList = ({ marketType, games }) => {
  132. const baseList = GAMES.Baselist;
  133. // 直接创建新列表
  134. if (!baseList[marketType]) {
  135. baseList[marketType] = games;
  136. return;
  137. }
  138. const newMap = new Map(games.map(item => [item.eventId, item]));
  139. // 删除不存在的项
  140. for (let i = baseList[marketType].length - 1; i >= 0; i--) {
  141. if (!newMap.has(baseList[marketType][i].eventId)) {
  142. baseList[marketType].splice(i, 1);
  143. }
  144. }
  145. // 添加或更新
  146. const oldIds = new Set(baseList[marketType].map(item => item.eventId));
  147. games.forEach(game => {
  148. if (!oldIds.has(game.eventId)) {
  149. // 添加新项
  150. baseList[marketType].push(game);
  151. }
  152. });
  153. }
  154. /**
  155. * 清理基准比赛列表
  156. */
  157. // const cleanupBaseList = () => {
  158. // const baseList = GAMES.Baselist;
  159. // const nowTime = Date.now();
  160. // const expireTime = nowTime - 1000*60*60*3;
  161. // Object.keys(baseList).forEach(marketType => {
  162. // baseList[marketType] = baseList[marketType].filter(item => item.timestamp < expireTime);
  163. // });
  164. // }
  165. /**
  166. * 更新比赛列表
  167. */
  168. const updateGamesList = (({ platform, mk, games } = {}) => {
  169. return new Promise((resolve, reject) => {
  170. if (!platform || !games) {
  171. return reject(new Error('PLATFORM_GAMES_INVALID'));
  172. }
  173. syncGamesList({ platform, mk, games });
  174. resolve();
  175. });
  176. });
  177. /**
  178. * 提交盘口数据
  179. */
  180. const submitOdds = ({ platform, mk, games }) => {
  181. if (IS_DEV) {
  182. return Logs.out('syncOdds', { platform, mk, games });
  183. }
  184. axios.post(`${BASE_API_URL}/p/syncOdds`, { platform, mk, games}, { proxy: false })
  185. .then(res => {
  186. // Logs.out('syncOdds', { platform, mk, count: games.length }, res.data);
  187. })
  188. .catch(err => {
  189. Logs.out('syncOdds', { platform, mk }, err.message);
  190. });
  191. }
  192. /**
  193. * 同步基准盘口
  194. */
  195. const syncBaseEvents = ({ mk, games, outrights }) => {
  196. const { expireTimeEvents, expireTimeSpecial } = getSetting();
  197. const marketType = getMarketType(mk);
  198. const baseList = GAMES.Baselist;
  199. if (!baseList[marketType]) {
  200. return;
  201. }
  202. const baseMap = new Map(baseList[marketType].map(item => [item.eventId, item]));
  203. games?.forEach(game => {
  204. const { eventId, originId, stage, retime, score, wm, evtime, events } = game;
  205. const baseGame = baseMap.get(eventId);
  206. if (baseGame) {
  207. baseGame.originId = originId;
  208. baseGame.stage = stage;
  209. baseGame.retime = retime;
  210. baseGame.score = score;
  211. baseGame.wm = wm;
  212. baseGame.evtime = evtime;
  213. baseGame.events = events;
  214. }
  215. });
  216. outrights?.forEach(outright => {
  217. const { parentId, sptime, special } = outright;
  218. const baseGame = baseMap.get(parentId);
  219. if (baseGame) {
  220. baseGame.sptime = sptime;
  221. baseGame.special = special;
  222. }
  223. else {
  224. const originBaseMap = new Map(baseList[marketType].map(item => [item.originId, item]));
  225. const originBaseGame = originBaseMap.get(parentId);
  226. if (originBaseGame) {
  227. originBaseGame.sptime = sptime;
  228. originBaseGame.special = special;
  229. }
  230. }
  231. });
  232. if (games?.length) {
  233. const gamesList = baseList[marketType]?.map(game => {
  234. const { evtime, events, sptime, special, ...gameInfo } = game;
  235. const expireTimeEv = Date.now() - expireTimeEvents;
  236. const expireTimeSP = Date.now() - expireTimeSpecial;
  237. let odds = {};
  238. if (evtime > expireTimeEv) {
  239. odds = { ...odds, ...events };
  240. }
  241. if (sptime > expireTimeSP) {
  242. odds = { ...odds, ...special };
  243. }
  244. const matches = PS_IOR_KEYS.map(([label, ...keys]) => {
  245. let match = keys.map(key => {
  246. return {
  247. key,
  248. value: odds[key]?.v ?? 0,
  249. origin: odds[key]?.r
  250. }
  251. });
  252. if (label == 'jqs') {
  253. match = match.filter(item => item.value !== 0);
  254. }
  255. return {
  256. label,
  257. match
  258. };
  259. }).filter(item => {
  260. if (item.label == 'jqs') {
  261. return item.match.length;
  262. }
  263. else {
  264. return item.match.every(entry => entry.value !== 0);
  265. }
  266. });
  267. game.matches = matches; // matches 也记录下来
  268. let uptime = evtime ?? 0;
  269. return { ...gameInfo, matches, uptime };
  270. });
  271. if (gamesList.filter(item => item.uptime > 0).length) {
  272. // if (mk == 2) {
  273. // Logs.out('syncBaseEvents', JSON.stringify({ mk, gamesList }, null, 2));
  274. // }
  275. submitOdds({ platform: 'ps', mk, games: gamesList });
  276. }
  277. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.['ps'] ?? {});
  278. if (!relatedGames.length) {
  279. return 0;
  280. }
  281. let update = 0;
  282. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  283. gamesList?.forEach(game => {
  284. const { eventId, matches, uptime, stage, retime, score, wm } = game;
  285. const relatedGame = relatedMap.get(eventId);
  286. if (relatedGame) {
  287. const events = {};
  288. matches.forEach(({ label, match }) => {
  289. match.forEach(({ key, value, origin }) => {
  290. events[key] = {
  291. v: value,
  292. r: origin
  293. };
  294. });
  295. });
  296. relatedGame.evtime = uptime;
  297. relatedGame.events = events;
  298. relatedGame.stage = stage;
  299. relatedGame.retime = retime;
  300. relatedGame.score = score;
  301. relatedGame.wm = wm;
  302. update ++;
  303. }
  304. });
  305. return update;
  306. }
  307. }
  308. const updateGamesEvents = ({ platform, mk, games, outrights, timestamp, tp }) => {
  309. return new Promise((resolve, reject) => {
  310. if (!platform || (!games && !outrights)) {
  311. return reject(new Error('PLATFORM_GAMES_INVALID'));
  312. }
  313. const { UpdateTimestamp } = GAMES;
  314. if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
  315. // Logs.out('updateGamesEvents', { tp, timestamp });
  316. UpdateTimestamp[tp] = timestamp;
  317. }
  318. else {
  319. return resolve({ update: 0 });
  320. }
  321. if (platform == 'ps') {
  322. const update = syncBaseEvents({ mk, games, outrights });
  323. return resolve({ update });
  324. }
  325. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.[platform] ?? {});
  326. if (!relatedGames.length) {
  327. return resolve({ update: 0 });
  328. }
  329. const updateCount = {
  330. update: 0
  331. };
  332. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  333. games?.forEach(game => {
  334. const { eventId, evtime, events, stage, retime, score, wm } = game;
  335. const relatedGame = relatedMap.get(eventId);
  336. if (relatedGame) {
  337. relatedGame.evtime = evtime;
  338. relatedGame.events = events;
  339. relatedGame.stage = stage;
  340. relatedGame.retime = retime;
  341. relatedGame.score = score;
  342. relatedGame.wm = wm;
  343. updateCount.update ++;
  344. }
  345. });
  346. outrights?.forEach(outright => {
  347. const { parentId, sptime, special } = outright;
  348. const relatedGame = relatedMap.get(parentId);
  349. if (relatedGame) {
  350. relatedGame.sptime = sptime;
  351. relatedGame.special = special;
  352. updateCount.update ++;
  353. }
  354. });
  355. resolve(updateCount);
  356. });
  357. }
  358. /**
  359. * 获取比赛盘口
  360. */
  361. const getGamesEvents = ({ platform, relIds = [] } = {}) => {
  362. if (!relIds.length) {
  363. return null;
  364. }
  365. const idSet = new Set(relIds);
  366. const relations = { ...GAMES.Relations };
  367. Object.keys(relations).forEach(id => {
  368. if (idSet.size && !idSet.has(+id)) {
  369. delete relations[id];
  370. }
  371. });
  372. if (platform) {
  373. return Object.values(relations).map(rel => rel[platform] ?? {});
  374. }
  375. const gamesEvents = {};
  376. Object.values(relations).forEach(({ rel }) => {
  377. Object.keys(rel).forEach(platform => {
  378. const game = rel[platform] ?? {};
  379. const { eventId, events, special } = game;
  380. if (!gamesEvents[platform]) {
  381. gamesEvents[platform] = {};
  382. }
  383. gamesEvents[platform][eventId] = { ...events, ...special };
  384. });
  385. });
  386. return gamesEvents;
  387. }
  388. /**
  389. * 获取关联比赛
  390. */
  391. const getDevGameTast = () => {
  392. return new Promise((resolve) => {
  393. const data = Cache.getData(DevGameTastFile, true);
  394. resolve({data});
  395. });
  396. }
  397. const fetchGamesRelation = async (mk='') => {
  398. const getGameTast = Promise.all([
  399. getDevGameTast(),
  400. axios.get(`${BASE_API_URL}/p/getGameTast?mk=${mk}`, { proxy: false })
  401. ]);
  402. return getGameTast.then(([res1, res2]) => {
  403. const resData = res1.data ?? res2.data;
  404. if (resData.code == 0) {
  405. const nowTime = Date.now();
  406. const gamesRelation = resData.data?.filter(item => {
  407. const timestamp = new Date(item.timestamp).getTime();
  408. if (nowTime > timestamp) {
  409. item.mk = 2;
  410. }
  411. item.timestamp = timestamp;
  412. const expireTime = timestamp + 1000*60*60*3;
  413. return expireTime > nowTime;
  414. }).map(item => {
  415. const {
  416. id, mk, league_name,
  417. event_id: ps_event_id,
  418. league_id: ps_league_id,
  419. team_home_name: ps_team_home_name,
  420. team_away_name: ps_team_away_name,
  421. ob_event_id, ob_league_id,
  422. ob_team_home_name,
  423. ob_team_away_name,
  424. hg_event_id, hg_league_id,
  425. hg_team_home_name,
  426. hg_team_away_name,
  427. timestamp,
  428. } = item;
  429. const rel = {
  430. ps: {
  431. eventId: +ps_event_id,
  432. leagueId: +ps_league_id,
  433. leagueName: league_name,
  434. teamHomeName: ps_team_home_name,
  435. teamAwayName: ps_team_away_name,
  436. timestamp
  437. },
  438. ob: ob_event_id ? {
  439. eventId: +ob_event_id,
  440. leagueId: +ob_league_id,
  441. leagueName: league_name,
  442. teamHomeName: ob_team_home_name,
  443. teamAwayName: ob_team_away_name,
  444. timestamp
  445. } : null,
  446. hg: hg_event_id ? {
  447. eventId: +hg_event_id,
  448. leagueId: +hg_league_id,
  449. leagueName: league_name,
  450. teamHomeName: hg_team_home_name,
  451. teamAwayName: hg_team_away_name,
  452. timestamp
  453. } : null
  454. };
  455. return { id: ps_event_id, mk, rel, timestamp };
  456. }) ?? [];
  457. return gamesRelation;
  458. }
  459. return Promise.reject(new Error(resData.message));
  460. });
  461. }
  462. const getGamesRelation = ({ mk=-1, ids, listEvents } = {}) => {
  463. let idsSet = null;
  464. if (ids?.length) {
  465. idsSet = new Set(ids);
  466. }
  467. const relations = Object.values(GAMES.Relations).filter(item => {
  468. if (idsSet && !idsSet.has(item.id)) {
  469. return false;
  470. }
  471. return mk == -1 || item.mk == mk;
  472. }).sort((a, b) => a.timestamp - b.timestamp);
  473. if (listEvents) {
  474. return relations;
  475. }
  476. const gamesRelation = relations.map(item => {
  477. const { rel, ...relationInfo } = item;
  478. const tempRel = { ...rel };
  479. Object.keys(tempRel).forEach(platform => {
  480. const { events, evtime, sptime, special, ...gameInfo } = tempRel[platform];
  481. tempRel[platform] = gameInfo;
  482. });
  483. return { ...relationInfo, rel: tempRel };
  484. });
  485. return gamesRelation;
  486. }
  487. /**
  488. * 定时更新关联比赛列表
  489. */
  490. const updateGamesRelation = () => {
  491. fetchGamesRelation()
  492. .then(gamesRelation => {
  493. const baseList = {};
  494. gamesRelation.map(item => {
  495. const baseGame = item.rel?.['ps'] ?? {};
  496. return { ...baseGame, mk: item.mk };
  497. }).forEach(item => {
  498. const marketType = getMarketType(item.mk);
  499. if (!baseList[marketType]) {
  500. baseList[marketType] = [];
  501. }
  502. baseList[marketType].push(item);
  503. });
  504. Object.keys(baseList).forEach(marketType => {
  505. syncBaseList({ marketType, games: baseList[marketType] });
  506. });
  507. const updateCount = {
  508. add: 0,
  509. update: 0,
  510. delete: 0
  511. };
  512. gamesRelation.forEach(item => {
  513. const { id, mk } = item;
  514. const oldItem = GAMES.Relations[id];
  515. if (!oldItem) {
  516. GAMES.Relations[id] = item;
  517. updateCount.add ++;
  518. }
  519. else if (oldItem.mk != mk) {
  520. GAMES.Relations[id] = item;
  521. updateCount.update ++;
  522. }
  523. });
  524. const relations = new Set(gamesRelation.map(item => +item.id));
  525. Object.keys(GAMES.Relations).forEach(id => {
  526. if (!relations.has(+id)) {
  527. delete GAMES.Relations[id];
  528. updateCount.delete ++;
  529. }
  530. });
  531. if (updateCount.add || updateCount.update || updateCount.delete) {
  532. Logs.out('updateGamesRelation', updateCount);
  533. }
  534. else {
  535. Logs.outDev('updateGamesRelation', updateCount);
  536. }
  537. })
  538. .catch(err => {
  539. Logs.out('updateGamesRelation', err.message);
  540. })
  541. .finally(() => {
  542. setTimeout(updateGamesRelation, 60000);
  543. });
  544. }
  545. updateGamesRelation();
  546. const gamesRelationCleanup = () => {
  547. const relations = Object.values(GAMES.Relations);
  548. const expireTime = Date.now() - 1000*60;
  549. relations.forEach(item => {
  550. const { rel } = item;
  551. Object.keys(rel).forEach(platform => {
  552. const { evtime, sptime } = rel[platform];
  553. if (evtime && evtime < expireTime) {
  554. delete rel[platform].events;
  555. delete rel[platform].evtime;
  556. }
  557. if (sptime && sptime < expireTime) {
  558. delete rel[platform].special;
  559. delete rel[platform].sptime;
  560. }
  561. });
  562. });
  563. }
  564. /**
  565. * 同步比赛结果
  566. */
  567. const syncGamesResult = async (result) => {
  568. if (IS_DEV) {
  569. return Logs.out('updateGamesResult', result);
  570. }
  571. axios.post(`${BASE_API_URL}/p/syncMatchResult`, result, { proxy: false })
  572. .then(res => {
  573. // Logs.out('syncMatchResult', res.data);
  574. })
  575. .catch(err => {
  576. Logs.out('syncMatchResult', err.message);
  577. });
  578. }
  579. /**
  580. * 更新比赛结果
  581. */
  582. const updateGamesResult = (result) => {
  583. syncGamesResult(result);
  584. return Promise.resolve();
  585. }
  586. /**
  587. * 同步中单方案
  588. */
  589. const syncSolutions = (solutions) => {
  590. if (IS_DEV) {
  591. return Logs.out('syncSolutions', solutions);
  592. }
  593. axios.post(`${BASE_API_URL}/p/syncDsOpportunity`, solutions, { proxy: false })
  594. .then(res => {
  595. // Logs.out('syncSolutions', res.data);
  596. })
  597. .catch(err => {
  598. Logs.out('syncSolutions', err.message);
  599. });
  600. }
  601. /**
  602. * 更新中单方案
  603. */
  604. const getCprKey = (cpr) => {
  605. const { k, p, v } = cpr;
  606. return `${k}_${p}_${v}`;
  607. }
  608. const compareCpr = (cpr1, cpr2) => {
  609. const key1 = getCprKey(cpr1);
  610. const key2 = getCprKey(cpr2);
  611. return key1 === key2;
  612. }
  613. const updateSolutions = (solutions, eventsLogsMap) => {
  614. if (solutions?.length) {
  615. const solutionsHistory = GAMES.Solutions;
  616. const updateIds = { add: [], update: [], retain: [], remove: [] }
  617. solutions.forEach(item => {
  618. const { sid, cpr, sol: { win_average } } = item;
  619. if (!solutionsHistory[sid]) {
  620. solutionsHistory[sid] = item;
  621. updateIds.add.push(sid);
  622. return;
  623. }
  624. const historySolution = solutionsHistory[sid];
  625. if (historySolution.sol.win_average !== win_average || !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, no_events, mk=-1 }) => {
  697. // Logs.out('getSolutions', win_min);
  698. const marketType = +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 == marketType;
  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 = null;
  733. if (!no_events) {
  734. gamesEvents = getGamesEvents({ relIds });
  735. }
  736. return { solutions, gamesEvents, mkCount };
  737. }
  738. /**
  739. * 获取单个中单方案
  740. */
  741. const getSolution = async (sid) => {
  742. if (!sid) {
  743. return Promise.reject(new Error('sid is required'));
  744. }
  745. const solution = GAMES.Solutions[sid];
  746. if (!solution) {
  747. return Promise.reject(new Error('solution not found'));
  748. }
  749. return solution;
  750. }
  751. /**
  752. * 通过比赛 ID 获取中单方案
  753. */
  754. const getSolutionsByIds = async (ids) => {
  755. const baseList = Object.values(GAMES.Baselist).flat();
  756. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  757. const result = {};
  758. ids.forEach(id => {
  759. const baseGame = baseMap.get(id);
  760. result[id] = {};
  761. result[id].matches = baseGame?.matches ?? [];
  762. result[id].sols = [];
  763. });
  764. Object.values(GAMES.Solutions).forEach(item => {
  765. const { info: { id } } = item;
  766. if (result[id]) {
  767. result[id].sols.push(item);
  768. }
  769. });
  770. return result;
  771. }
  772. /**
  773. * 清理中单方案
  774. */
  775. const solutionsCleanup = () => {
  776. const solutionsHistory = GAMES.Solutions;
  777. const updateIds = { remove: [] }
  778. Object.keys(solutionsHistory).forEach(sid => {
  779. const { timestamp } = solutionsHistory[sid];
  780. const nowTime = Date.now();
  781. if (nowTime - timestamp > 1000*60) {
  782. delete solutionsHistory[sid];
  783. updateIds.remove.push(sid);
  784. return;
  785. }
  786. const solution = solutionsHistory[sid];
  787. const eventTime = solution.info.timestamp;
  788. if (nowTime > eventTime) {
  789. delete solutionsHistory[sid];
  790. updateIds.remove.push(sid);
  791. }
  792. });
  793. if (updateIds.remove.length) {
  794. syncSolutions(updateIds);
  795. }
  796. }
  797. /**
  798. * 定时清理中单方案
  799. * 定时清理盘口信息
  800. */
  801. setInterval(() => {
  802. // cleanupBaseList();
  803. solutionsCleanup();
  804. gamesRelationCleanup();
  805. }, 1000*30);
  806. /**
  807. * 获取综合利润
  808. */
  809. const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
  810. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  811. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  812. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  813. const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
  814. return profit;
  815. }
  816. /**
  817. * 通过 sid 获取综合利润
  818. */
  819. const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
  820. const preSolution = GAMES.Solutions[sid1];
  821. const subSolution = GAMES.Solutions[sid2];
  822. const sol1 = preSolution?.sol;
  823. const sol2 = subSolution?.sol;
  824. if (!sol1) {
  825. return Promise.reject(new Error('sid1 已失效'));
  826. }
  827. if (!sol2) {
  828. return Promise.reject(new Error('sid2 已失效'));
  829. }
  830. const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  831. return { profit, solutions: [preSolution, subSolution] };
  832. }
  833. /**
  834. * 通过盘口信息获取综合利润
  835. */
  836. const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
  837. if (!betInfo1?.cross_type) {
  838. return Promise.reject(new Error('第一个下注信息无效'));
  839. }
  840. if (!betInfo2?.cross_type) {
  841. return Promise.reject(new Error('第二个下注信息无效'));
  842. }
  843. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  844. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  845. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  846. if (fixed) {
  847. return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
  848. }
  849. const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
  850. return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  851. }
  852. /**
  853. * 获取后台设置
  854. */
  855. // const getSetting = async () => {
  856. // return ;
  857. // }
  858. /**
  859. * 异常通知
  860. */
  861. const notifyException = (message) => {
  862. if (IS_DEV) {
  863. return Logs.out('notifyException', { message });
  864. }
  865. const chat_id = -1003032820471;
  866. axios.get(`${BASE_API_URL}/telegram/jump`, { params: { chat_id, message } }, { proxy: false })
  867. .then(() => {
  868. Logs.out('notifyException', '通知成功');
  869. })
  870. .catch(err => {
  871. Logs.out('notifyException', err.message);
  872. });
  873. }
  874. /**
  875. * 从子进程获取数据
  876. */
  877. const getDataFromChild = (type, callback) => {
  878. const id = ++Request.count;
  879. Request.callbacks[id] = callback;
  880. events_child.send({ method: 'get', id, type });
  881. }
  882. /**
  883. * 向子进程发送数据
  884. */
  885. const postDataToChild = (type, data) => {
  886. events_child.send({ method: 'post', type, data });
  887. }
  888. /**
  889. * 处理子进程消息
  890. */
  891. events_child.on('message', async (message) => {
  892. const { callbacks } = Request;
  893. const { method, id, type, data } = message;
  894. if (method == 'get' && id) {
  895. let responseData = null;
  896. if (type == 'getGamesRelation') {
  897. responseData = getGamesRelation({ listEvents: true });
  898. }
  899. else if (type == 'getSetting') {
  900. responseData = getSetting();
  901. }
  902. // else if (type == 'getSolutionHistory') {
  903. // responseData = getSolutionHistory();
  904. // }
  905. events_child.send({ type: 'response', id, data: responseData });
  906. }
  907. else if (method == 'post') {
  908. if (type == 'updateSolutions') {
  909. updateSolutions(data.solutions, data.eventsLogsMap);
  910. }
  911. }
  912. else if (method == 'response' && id && callbacks[id]) {
  913. callbacks[id](data);
  914. delete callbacks[id];
  915. }
  916. });
  917. events_child.stderr?.on('data', data => {
  918. Logs.out('events_child stderr', data.toString());
  919. });
  920. const settingUpdate = (fields) => {
  921. updateSetting(fields);
  922. postDataToChild('updateSetting', fields);
  923. }
  924. const syncSetting = async () => {
  925. const setting = await Setting.get();
  926. settingUpdate(setting.toObject());
  927. }
  928. syncSetting();
  929. Setting.onUpdate(settingUpdate);
  930. /**
  931. * 保存GAMES数据到缓存文件
  932. */
  933. const saveGamesToCache = () => {
  934. Cache.setData(GamesCacheFile, GAMES, err => {
  935. if (err) {
  936. Logs.out('Failed to save games cache:', err.message);
  937. }
  938. else {
  939. Logs.out('Games cache saved successfully');
  940. }
  941. });
  942. }
  943. /**
  944. * 从缓存文件加载GAMES数据
  945. */
  946. const loadGamesFromCache = () => {
  947. const gamesCacheData = Cache.getData(GamesCacheFile, true);
  948. Object.keys(GAMES).forEach(key => {
  949. if (gamesCacheData[key]) {
  950. GAMES[key] = gamesCacheData[key];
  951. }
  952. });
  953. Logs.out('Games cache loaded successfully');
  954. }
  955. // 在模块加载时尝试从缓存恢复数据
  956. loadGamesFromCache();
  957. // 监听进程退出事件,保存GAMES数据
  958. process.on('exit', saveGamesToCache);
  959. process.on('SIGINT', () => {
  960. process.exit(0);
  961. });
  962. process.on('SIGTERM', () => {
  963. process.exit(0);
  964. });
  965. process.on('SIGUSR2', () => {
  966. process.exit(0);
  967. });
  968. module.exports = {
  969. updateLeaguesList, getFilteredLeagues,
  970. updateGamesList, updateGamesEvents,
  971. getGamesRelation,
  972. updateGamesResult,
  973. getSolutions, getSolution, getSolutionsByIds,
  974. getTotalProfitWithSid,
  975. getTotalProfitWithBetInfo,
  976. notifyException,
  977. }