GamesPs.js 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  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. * 同步Qboss平台配置
  907. */
  908. const syncQbossConfig = () => {
  909. axios.get(`${BASE_API_URL}/p/QbossSystemConfig`, { proxy: false })
  910. .then(res => {
  911. const { data } = res;
  912. if (!data?.data) {
  913. throw new Error('syncQbossConfig data is empty');
  914. }
  915. const setting = getSetting();
  916. const { qboss_return_ratio, qboss_jq_add_odds, qboss_jq_add_hours } = data.data;
  917. const qbossSetting = { innerRebateRatio: +qboss_return_ratio, subsidyTime: +qboss_jq_add_hours, subsidyAmount: +qboss_jq_add_odds };
  918. const settingFields = {};
  919. let needUpdate = false;
  920. Object.keys(qbossSetting).forEach(key => {
  921. if (qbossSetting[key] !== setting[key]) {
  922. settingFields[key] = qbossSetting[key];
  923. needUpdate = true;
  924. }
  925. });
  926. console.log('settingFields', settingFields);
  927. if (needUpdate) {
  928. Setting.update(settingFields);
  929. Logs.outDev('syncQbossConfig', settingFields);
  930. }
  931. else {
  932. Logs.outDev('syncQbossConfig no change');
  933. }
  934. })
  935. .catch(err => {
  936. Logs.out('syncQbossConfig error', err.message);
  937. })
  938. .finally(() => {
  939. setTimeout(() => {
  940. syncQbossConfig();
  941. }, 1000*15);
  942. });
  943. }
  944. syncQbossConfig();
  945. /**
  946. * 异常通知
  947. */
  948. const notifyException = (message) => {
  949. if (IS_DEV) {
  950. return Logs.out('notifyException', { message });
  951. }
  952. const chat_id = -1003032820471;
  953. axios.get(`${BASE_API_URL}/telegram/jump`, { params: { chat_id, message } }, { proxy: false })
  954. .then(() => {
  955. Logs.out('notifyException', '通知成功');
  956. })
  957. .catch(err => {
  958. Logs.out('notifyException', err.message);
  959. });
  960. }
  961. /**
  962. * 从子进程获取数据
  963. */
  964. const getDataFromChild = (type, callback) => {
  965. const id = ++Request.count;
  966. Request.callbacks[id] = callback;
  967. events_child.send({ method: 'get', id, type });
  968. }
  969. /**
  970. * 向子进程发送数据
  971. */
  972. const postDataToChild = (type, data) => {
  973. events_child.send({ method: 'post', type, data });
  974. }
  975. /**
  976. * 处理子进程消息
  977. */
  978. events_child.on('message', async (message) => {
  979. const { callbacks } = Request;
  980. const { method, id, type, data } = message;
  981. if (method == 'get' && id) {
  982. let responseData = null;
  983. if (type == 'getGamesRelation') {
  984. responseData = getGamesRelation({ listEvents: true });
  985. }
  986. else if (type == 'getSetting') {
  987. responseData = getSetting();
  988. }
  989. // else if (type == 'getSolutionHistory') {
  990. // responseData = getSolutionHistory();
  991. // }
  992. events_child.send({ type: 'response', id, data: responseData });
  993. }
  994. else if (method == 'post') {
  995. if (type == 'updateSolutions') {
  996. updateSolutions(data.solutions, data.eventsLogsMap);
  997. }
  998. }
  999. else if (method == 'response' && id && callbacks[id]) {
  1000. callbacks[id](data);
  1001. delete callbacks[id];
  1002. }
  1003. });
  1004. events_child.stderr?.on('data', data => {
  1005. Logs.out('events_child stderr', data.toString());
  1006. });
  1007. const settingUpdate = (fields) => {
  1008. updateSetting(fields);
  1009. postDataToChild('updateSetting', fields);
  1010. }
  1011. const syncSetting = async () => {
  1012. const setting = await Setting.get();
  1013. console.log('syncSetting', setting);
  1014. settingUpdate(setting.toObject());
  1015. }
  1016. syncSetting();
  1017. Setting.onUpdate(settingUpdate);
  1018. /**
  1019. * 保存GAMES数据到缓存文件
  1020. */
  1021. const saveGamesToCache = () => {
  1022. Cache.setData(GamesCacheFile, GAMES, err => {
  1023. if (err) {
  1024. Logs.out('Failed to save games cache:', err.message);
  1025. }
  1026. else {
  1027. Logs.out('Games cache saved successfully');
  1028. }
  1029. });
  1030. }
  1031. /**
  1032. * 从缓存文件加载GAMES数据
  1033. */
  1034. const loadGamesFromCache = () => {
  1035. const gamesCacheData = Cache.getData(GamesCacheFile, true);
  1036. Object.keys(GAMES).forEach(key => {
  1037. if (gamesCacheData[key]) {
  1038. GAMES[key] = gamesCacheData[key];
  1039. }
  1040. });
  1041. Logs.out('Games cache loaded successfully');
  1042. }
  1043. // 在模块加载时尝试从缓存恢复数据
  1044. loadGamesFromCache();
  1045. // 监听进程退出事件,保存GAMES数据
  1046. process.on('exit', saveGamesToCache);
  1047. process.on('SIGINT', () => {
  1048. process.exit(0);
  1049. });
  1050. process.on('SIGTERM', () => {
  1051. process.exit(0);
  1052. });
  1053. process.on('SIGUSR2', () => {
  1054. process.exit(0);
  1055. });
  1056. module.exports = {
  1057. updateLeaguesList, getFilteredLeagues,
  1058. updateGamesList, updateGamesEvents,
  1059. getGamesRelation,
  1060. updateGamesResult,
  1061. getSolutions, getGamesSolutions, getSolution, getSolutionsByIds,
  1062. getTotalProfitWithSid,
  1063. getTotalProfitWithBetInfo,
  1064. notifyException,
  1065. }