GamesPs.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  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. ['-3', 'ior_rh_35', 'ior_wmh_3', 'ior_rac_25'],
  23. ['-4', 'ior_rh_45', 'ior_wmh_4', 'ior_rac_35'],
  24. ['-5', 'ior_rh_55', 'ior_wmh_5', 'ior_rac_45'],
  25. ['+1', 'ior_rah_05', 'ior_wmc_1', 'ior_rc_15'],
  26. ['+2', 'ior_rah_15', 'ior_wmc_2', 'ior_rc_25'],
  27. ['+3', 'ior_rah_25', 'ior_wmc_3', 'ior_rc_35'],
  28. ['+4', 'ior_rah_35', 'ior_wmc_4', 'ior_rc_45'],
  29. ['+5', 'ior_rah_45', 'ior_wmc_5', 'ior_rc_55'],
  30. ['jqs', 'ior_ot_1', 'ior_ot_2', 'ior_ot_3', 'ior_ot_4', 'ior_ot_5', 'ior_ot_6', 'ior_ot_7'],
  31. ];
  32. const IOR_KEYS_TYPE = {
  33. A: 1, L: 1,
  34. D: 2, K: 2,
  35. }
  36. // 测试环境
  37. // const BASE_API_URL = 'https://dev.api.czxd8.com/api/p';
  38. const IS_DEV = process.env.NODE_ENV == 'development';
  39. const BASE_API_URL = IS_DEV ? 'https://api.qboss.vip/api' : 'http://172.17.222.37/api';
  40. const GAMES = {
  41. Leagues: {},
  42. Baselist: {},
  43. Relations: {},
  44. Solutions: {},
  45. UpdateTimestamp: {},
  46. };
  47. const Request = {
  48. callbacks: {},
  49. count: 0,
  50. }
  51. /**
  52. * 精确浮点数字
  53. * @param {number} number
  54. * @param {number} x
  55. * @returns {number}
  56. */
  57. const fixFloat = (number, x=2) => {
  58. return parseFloat(number.toFixed(x));
  59. }
  60. /**
  61. * 获取市场类型
  62. */
  63. const getMarketType = (mk) => {
  64. if (mk == 0) {
  65. return 'early';
  66. }
  67. else if (mk == 2) {
  68. return 'rollball';
  69. }
  70. return 'today';
  71. }
  72. /**
  73. * 获取策略类型
  74. */
  75. const getRuleType = (rule) => {
  76. const rulePrefix = rule.split(':')[0];
  77. return IOR_KEYS_TYPE[rulePrefix];
  78. }
  79. /**
  80. * 关键词匹配比赛
  81. */
  82. const matchGame = (relation, sk) => {
  83. const keys = [];
  84. Object.keys(relation).forEach(platform => {
  85. const { leagueName, teamHomeName, teamAwayName } = relation[platform];
  86. if (platform == 'ps') {
  87. keys.push(leagueName);
  88. }
  89. keys.push(teamHomeName, teamAwayName);
  90. });
  91. return keys.some(key => key.includes(sk));
  92. }
  93. /**
  94. * 同步联赛列表
  95. */
  96. const syncLeaguesList = ({ mk, leagues }) => {
  97. if (IS_DEV) {
  98. return Logs.out('syncLeaguesList', { mk, leagues });
  99. }
  100. axios.post(`${BASE_API_URL}/p/syncLeague`, { mk, leagues }, { proxy: false })
  101. .then(res => {
  102. // Logs.out('syncLeaguesList', res.data);
  103. })
  104. .catch(err => {
  105. Logs.out('syncLeaguesList', err.message);
  106. });
  107. }
  108. /**
  109. * 更新联赛列表
  110. */
  111. const updateLeaguesList = ({ mk, leagues }) => {
  112. const leaguesMap = GAMES.Leagues;
  113. const nowTime = Date.now();
  114. const expireTime = nowTime - 1000 * 60 * 5;
  115. if (!leaguesMap[mk]) {
  116. leaguesMap[mk] = {
  117. timestamp: 0,
  118. leagues: [],
  119. };
  120. }
  121. if (leaguesMap[mk].timestamp < expireTime ||
  122. JSON.stringify(leaguesMap[mk].leagues) != JSON.stringify(leagues)) {
  123. leaguesMap[mk].leagues = leagues;
  124. leaguesMap[mk].timestamp = nowTime;
  125. syncLeaguesList({ mk, leagues });
  126. return leagues.length;
  127. }
  128. return 0;
  129. }
  130. /**
  131. * 获取筛选过的联赛
  132. */
  133. const getFilteredLeagues = async (mk) => {
  134. return axios.get(`${BASE_API_URL}/p/getLeagueTast?mk=${mk ?? ''}`, { proxy: false })
  135. .then(res => {
  136. if (res.data.code == 0) {
  137. return res.data.data;
  138. }
  139. return Promise.reject(new Error(res.data.message));
  140. });
  141. }
  142. /**
  143. * 同步比赛列表到服务器
  144. */
  145. const syncGamesList = ({ platform, mk, games }) => {
  146. if (IS_DEV) {
  147. return Logs.out('syncGamesList', { platform, mk, games });
  148. }
  149. axios.post(`${BASE_API_URL}/p/syncGames`, { platform, mk, games })
  150. .then(res => {
  151. // Logs.out('syncGamesList', { platform, mk, count: games.length }, res.data);
  152. })
  153. .catch(err => {
  154. Logs.out('syncGamesList', { platform, mk }, err.message);
  155. });
  156. }
  157. /**
  158. * 同步基准比赛列表
  159. */
  160. const syncBaseList = ({ marketType, games }) => {
  161. const baseList = GAMES.Baselist;
  162. // 直接创建新列表
  163. if (!baseList[marketType]) {
  164. baseList[marketType] = games;
  165. return;
  166. }
  167. const newMap = new Map(games.map(item => [item.eventId, item]));
  168. // 删除不存在的项
  169. for (let i = baseList[marketType].length - 1; i >= 0; i--) {
  170. if (!newMap.has(baseList[marketType][i].eventId)) {
  171. baseList[marketType].splice(i, 1);
  172. }
  173. }
  174. // 添加或更新
  175. const oldIds = new Set(baseList[marketType].map(item => item.eventId));
  176. games.forEach(game => {
  177. if (!oldIds.has(game.eventId)) {
  178. // 添加新项
  179. baseList[marketType].push(game);
  180. }
  181. });
  182. }
  183. /**
  184. * 清理基准比赛列表
  185. */
  186. // const cleanupBaseList = () => {
  187. // const baseList = GAMES.Baselist;
  188. // const nowTime = Date.now();
  189. // const expireTime = nowTime - 1000*60*60*3;
  190. // Object.keys(baseList).forEach(marketType => {
  191. // baseList[marketType] = baseList[marketType].filter(item => item.timestamp < expireTime);
  192. // });
  193. // }
  194. /**
  195. * 更新比赛列表
  196. */
  197. const updateGamesList = (({ platform, mk, games } = {}) => {
  198. return new Promise((resolve, reject) => {
  199. if (!platform || !games) {
  200. return reject(new Error('PLATFORM_GAMES_INVALID'));
  201. }
  202. syncGamesList({ platform, mk, games });
  203. resolve();
  204. });
  205. });
  206. /**
  207. * 提交盘口数据
  208. */
  209. // const submitOdds = ({ platform, mk, games }) => {
  210. // if (IS_DEV) {
  211. // return Logs.out('syncOdds', { platform, mk, games });
  212. // }
  213. // axios.post(`${BASE_API_URL}/p/syncOdds`, { platform, mk, games}, { proxy: false })
  214. // .then(res => {
  215. // // Logs.out('syncOdds', { platform, mk, count: games.length }, res.data);
  216. // })
  217. // .catch(err => {
  218. // Logs.out('syncOdds', { platform, mk }, err.message);
  219. // });
  220. // }
  221. /**
  222. * 同步基准盘口
  223. */
  224. const syncBaseEvents = ({ mk, games, outrights }) => {
  225. const {
  226. expireTimeEvents, expireTimeSpecial,
  227. subsidyTime, subsidyAmount,
  228. subsidyRbWmAmount, subsidyRbOtAmount
  229. } = getSetting();
  230. const nowTime = Date.now();
  231. const marketType = getMarketType(mk);
  232. const baseList = GAMES.Baselist;
  233. if (!baseList[marketType]) {
  234. return;
  235. }
  236. const baseMap = new Map(baseList[marketType].map(item => [item.eventId, item]));
  237. games?.forEach(game => {
  238. const { eventId, originId, stage, retime, score, wm, evtime, events } = game;
  239. const baseGame = baseMap.get(eventId);
  240. if (baseGame) {
  241. const { mk } = baseGame;
  242. const isRb = (mk == 2);
  243. if (isRb) {
  244. Object.keys(events).forEach(ior => {
  245. if ((ior.startsWith('ior_r') || ior.startsWith('ior_m')) && subsidyRbWmAmount) {
  246. const sourceOdds = events[ior].v;
  247. events[ior].v = fixFloat(sourceOdds * (1 + subsidyRbWmAmount), 3);
  248. events[ior].s = sourceOdds
  249. }
  250. });
  251. }
  252. baseGame.originId = originId;
  253. baseGame.stage = stage;
  254. baseGame.retime = retime;
  255. baseGame.score = score;
  256. baseGame.wm = wm;
  257. baseGame.evtime = evtime;
  258. baseGame.events = events;
  259. }
  260. });
  261. outrights?.forEach(outright => {
  262. const { parentId, sptime, special } = outright;
  263. const baseGame = baseMap.get(parentId);
  264. if (baseGame) { // 赛前特殊盘口
  265. const { timestamp } = baseGame;
  266. const isSubsidy = timestamp > nowTime && timestamp < nowTime + 1000*60*60*subsidyTime;
  267. if (isSubsidy) {
  268. Object.keys(special).forEach(ior => {
  269. if (ior.startsWith('ior_ot') && subsidyAmount) {
  270. const sourceOdds = special[ior].v;
  271. special[ior].v = fixFloat(sourceOdds * (1 + subsidyAmount), 3);
  272. special[ior].s = sourceOdds
  273. }
  274. });
  275. }
  276. baseGame.sptime = sptime;
  277. baseGame.special = special;
  278. }
  279. else {
  280. const originBaseMap = new Map(baseList[marketType].map(item => [item.originId, item]));
  281. const originBaseGame = originBaseMap.get(parentId);
  282. if (originBaseGame) { // 滚球特殊盘口
  283. Object.keys(special).forEach(ior => {
  284. if (ior.startsWith('ior_wm') && subsidyRbWmAmount) {
  285. const sourceOdds = special[ior].v;
  286. special[ior].v = fixFloat(sourceOdds * (1 + subsidyRbWmAmount), 3);
  287. special[ior].s = sourceOdds
  288. }
  289. else if (ior.startsWith('ior_ot') && subsidyRbOtAmount) {
  290. const sourceOdds = special[ior].v;
  291. special[ior].v = fixFloat(sourceOdds * (1 + subsidyRbOtAmount), 3);
  292. special[ior].s = sourceOdds
  293. }
  294. });
  295. originBaseGame.sptime = sptime;
  296. originBaseGame.special = special;
  297. }
  298. }
  299. });
  300. if (games?.length) {
  301. const gamesList = baseList[marketType]?.map(game => {
  302. const { evtime, events, sptime, special, ...gameInfo } = game;
  303. const expireTimeEv = nowTime - expireTimeEvents;
  304. const expireTimeSP = nowTime - expireTimeSpecial;
  305. let odds = {};
  306. if (evtime > expireTimeEv) {
  307. odds = { ...odds, ...events };
  308. }
  309. if (sptime > expireTimeSP) {
  310. odds = { ...odds, ...special };
  311. }
  312. const matches = PS_IOR_KEYS.map(([label, ...keys]) => {
  313. let match = keys.map(key => {
  314. return {
  315. key,
  316. value: odds[key]?.v ?? 0,
  317. origin: odds[key]?.r,
  318. source: odds[key]?.s,
  319. }
  320. });
  321. if (label == 'jqs') {
  322. match = match.filter(item => item.value !== 0);
  323. }
  324. return {
  325. label,
  326. match
  327. };
  328. }).filter(item => {
  329. if (item.label == 'jqs') {
  330. return item.match.length;
  331. }
  332. else {
  333. return item.match.every(entry => entry.value !== 0);
  334. }
  335. });
  336. game.matches = matches; // matches 也记录下来
  337. let uptime = evtime ?? 0;
  338. return { ...gameInfo, matches, uptime };
  339. });
  340. // if (gamesList.filter(item => item.uptime > 0).length) {
  341. // // if (mk == 2) {
  342. // // Logs.out('syncBaseEvents', JSON.stringify({ mk, gamesList }, null, 2));
  343. // // }
  344. // submitOdds({ platform: 'ps', mk, games: gamesList });
  345. // }
  346. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.['ps'] ?? {});
  347. if (!relatedGames.length) {
  348. return 0;
  349. }
  350. let update = 0;
  351. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  352. gamesList?.forEach(game => {
  353. const { eventId, matches, uptime, stage, retime, score, wm } = game;
  354. const relatedGame = relatedMap.get(eventId);
  355. if (relatedGame) {
  356. const events = {};
  357. matches.forEach(({ label, match }) => {
  358. match.forEach(({ key, value, origin, source }) => {
  359. events[key] = {
  360. v: value,
  361. r: origin,
  362. s: source
  363. };
  364. });
  365. });
  366. relatedGame.evtime = uptime;
  367. relatedGame.events = events;
  368. relatedGame.stage = stage;
  369. relatedGame.retime = retime;
  370. relatedGame.score = score;
  371. relatedGame.wm = wm;
  372. update ++;
  373. }
  374. });
  375. return update;
  376. }
  377. }
  378. const updateGamesEvents = ({ platform, mk, games, outrights, timestamp, tp }) => {
  379. return new Promise((resolve, reject) => {
  380. if (!platform || (!games && !outrights)) {
  381. return reject(new Error('PLATFORM_GAMES_INVALID'));
  382. }
  383. const { UpdateTimestamp } = GAMES;
  384. if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
  385. // Logs.out('updateGamesEvents', { tp, timestamp });
  386. UpdateTimestamp[tp] = timestamp;
  387. }
  388. else {
  389. return resolve({ update: 0 });
  390. }
  391. if (platform == 'ps') {
  392. const update = syncBaseEvents({ mk, games, outrights });
  393. return resolve({ update });
  394. }
  395. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.[platform] ?? {});
  396. if (!relatedGames.length) {
  397. return resolve({ update: 0 });
  398. }
  399. const updateCount = {
  400. update: 0
  401. };
  402. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  403. games?.forEach(game => {
  404. const { eventId, evtime, events, stage, retime, score, wm } = game;
  405. const relatedGame = relatedMap.get(eventId);
  406. if (relatedGame) {
  407. relatedGame.evtime = evtime;
  408. relatedGame.events = events;
  409. relatedGame.stage = stage;
  410. relatedGame.retime = retime;
  411. relatedGame.score = score;
  412. relatedGame.wm = wm;
  413. updateCount.update ++;
  414. }
  415. });
  416. outrights?.forEach(outright => {
  417. const { parentId, sptime, special } = outright;
  418. const relatedGame = relatedMap.get(parentId);
  419. if (relatedGame) {
  420. relatedGame.sptime = sptime;
  421. relatedGame.special = special;
  422. updateCount.update ++;
  423. }
  424. });
  425. resolve(updateCount);
  426. });
  427. }
  428. /**
  429. * 获取比赛盘口
  430. */
  431. const getGamesEvents = ({ platform, relIds = [] } = {}) => {
  432. if (!relIds.length) {
  433. return null;
  434. }
  435. const idSet = new Set(relIds);
  436. const relations = { ...GAMES.Relations };
  437. Object.keys(relations).forEach(id => {
  438. if (idSet.size && !idSet.has(+id)) {
  439. delete relations[id];
  440. }
  441. });
  442. if (platform) {
  443. return Object.values(relations).map(rel => rel[platform] ?? {});
  444. }
  445. const gamesEvents = {};
  446. Object.values(relations).forEach(({ rel }) => {
  447. Object.keys(rel).forEach(platform => {
  448. const game = rel[platform] ?? {};
  449. const { eventId, events, special } = game;
  450. if (!gamesEvents[platform]) {
  451. gamesEvents[platform] = {};
  452. }
  453. gamesEvents[platform][eventId] = { ...events, ...special };
  454. });
  455. });
  456. return gamesEvents;
  457. }
  458. /**
  459. * 获取关联比赛
  460. */
  461. const getDevGameTast = () => {
  462. return new Promise((resolve) => {
  463. const data = Cache.getData(DevGameTastFile, true);
  464. resolve({data});
  465. });
  466. }
  467. const fetchGamesRelation = async (mk='') => {
  468. const getGameTast = Promise.all([
  469. getDevGameTast(),
  470. axios.get(`${BASE_API_URL}/p/getGameTast?mk=${mk}`, { proxy: false })
  471. ]);
  472. return getGameTast.then(([res1, res2]) => {
  473. const resData = res1.data ?? res2.data;
  474. if (resData.code == 0) {
  475. const nowTime = Date.now();
  476. const gamesRelation = resData.data?.filter(item => {
  477. const timestamp = new Date(item.timestamp).getTime();
  478. if (nowTime > timestamp) {
  479. item.mk = 2;
  480. }
  481. item.timestamp = timestamp;
  482. const expireTime = timestamp + 1000*60*60*3;
  483. return expireTime > nowTime;
  484. }).map(item => {
  485. const {
  486. id, mk, league_name,
  487. event_id: ps_event_id,
  488. league_id: ps_league_id,
  489. team_home_name: ps_team_home_name,
  490. team_away_name: ps_team_away_name,
  491. ob_event_id, ob_league_id,
  492. ob_team_home_name,
  493. ob_team_away_name,
  494. hg_event_id, hg_league_id,
  495. hg_team_home_name,
  496. hg_team_away_name,
  497. timestamp,
  498. } = item;
  499. const rel = {
  500. ps: {
  501. eventId: +ps_event_id,
  502. leagueId: +ps_league_id,
  503. leagueName: league_name,
  504. teamHomeName: ps_team_home_name,
  505. teamAwayName: ps_team_away_name,
  506. timestamp
  507. },
  508. ob: ob_event_id ? {
  509. eventId: +ob_event_id,
  510. leagueId: +ob_league_id,
  511. leagueName: league_name,
  512. teamHomeName: ob_team_home_name,
  513. teamAwayName: ob_team_away_name,
  514. timestamp
  515. } : null,
  516. hg: hg_event_id ? {
  517. eventId: +hg_event_id,
  518. leagueId: +hg_league_id,
  519. leagueName: league_name,
  520. teamHomeName: hg_team_home_name,
  521. teamAwayName: hg_team_away_name,
  522. timestamp
  523. } : null
  524. };
  525. return { id: ps_event_id, mk, rel, timestamp };
  526. }) ?? [];
  527. return gamesRelation;
  528. }
  529. return Promise.reject(new Error(resData.message));
  530. });
  531. }
  532. const getGamesRelation = ({ mk=-1, ids, listEvents } = {}) => {
  533. let idsSet = null;
  534. if (ids?.length) {
  535. idsSet = new Set(ids);
  536. }
  537. const relations = Object.values(GAMES.Relations).filter(item => {
  538. if (idsSet && !idsSet.has(item.id)) {
  539. return false;
  540. }
  541. return mk == -1 || item.mk == mk;
  542. }).sort((a, b) => a.timestamp - b.timestamp);
  543. if (listEvents) {
  544. return relations;
  545. }
  546. const gamesRelation = relations.map(item => {
  547. const { rel, ...relationInfo } = item;
  548. const tempRel = { ...rel };
  549. Object.keys(tempRel).forEach(platform => {
  550. const { events, evtime, sptime, special, ...gameInfo } = tempRel[platform];
  551. tempRel[platform] = gameInfo;
  552. });
  553. return { ...relationInfo, rel: tempRel };
  554. });
  555. return gamesRelation;
  556. }
  557. /**
  558. * 定时更新关联比赛列表
  559. */
  560. const updateGamesRelation = () => {
  561. fetchGamesRelation()
  562. .then(gamesRelation => {
  563. const baseList = {};
  564. gamesRelation.map(item => {
  565. const baseGame = item.rel?.['ps'] ?? {};
  566. return { ...baseGame, mk: item.mk };
  567. }).forEach(item => {
  568. const marketType = getMarketType(item.mk);
  569. if (!baseList[marketType]) {
  570. baseList[marketType] = [];
  571. }
  572. baseList[marketType].push(item);
  573. });
  574. Object.keys(baseList).forEach(marketType => {
  575. syncBaseList({ marketType, games: baseList[marketType] });
  576. });
  577. const updateCount = {
  578. add: 0,
  579. update: 0,
  580. delete: 0
  581. };
  582. gamesRelation.forEach(item => {
  583. const { id, mk } = item;
  584. const oldItem = GAMES.Relations[id];
  585. if (!oldItem) {
  586. GAMES.Relations[id] = item;
  587. updateCount.add ++;
  588. }
  589. else if (oldItem.mk != mk) {
  590. GAMES.Relations[id] = item;
  591. updateCount.update ++;
  592. }
  593. });
  594. const relations = new Set(gamesRelation.map(item => +item.id));
  595. Object.keys(GAMES.Relations).forEach(id => {
  596. if (!relations.has(+id)) {
  597. delete GAMES.Relations[id];
  598. updateCount.delete ++;
  599. }
  600. });
  601. if (updateCount.add || updateCount.update || updateCount.delete) {
  602. Logs.out('updateGamesRelation', updateCount);
  603. }
  604. else {
  605. Logs.outDev('updateGamesRelation', updateCount);
  606. }
  607. })
  608. .catch(err => {
  609. Logs.out('updateGamesRelation', err.message);
  610. })
  611. .finally(() => {
  612. setTimeout(updateGamesRelation, 60000);
  613. });
  614. }
  615. updateGamesRelation();
  616. const gamesRelationCleanup = () => {
  617. const relations = Object.values(GAMES.Relations);
  618. const expireTime = Date.now() - 1000*60;
  619. relations.forEach(item => {
  620. const { rel } = item;
  621. Object.keys(rel).forEach(platform => {
  622. const { evtime, sptime } = rel[platform];
  623. if (evtime && evtime < expireTime) {
  624. delete rel[platform].events;
  625. delete rel[platform].evtime;
  626. }
  627. if (sptime && sptime < expireTime) {
  628. delete rel[platform].special;
  629. delete rel[platform].sptime;
  630. }
  631. });
  632. });
  633. }
  634. /**
  635. * 同步比赛结果
  636. */
  637. const syncGamesResult = async (result) => {
  638. if (IS_DEV) {
  639. return Logs.out('updateGamesResult', result);
  640. }
  641. // axios.post(`${BASE_API_URL}/p/syncMatchResult`, result, { proxy: false })
  642. // .then(res => {
  643. // // Logs.out('syncMatchResult', res.data);
  644. // })
  645. // .catch(err => {
  646. // Logs.out('syncMatchResult', err.message);
  647. // });
  648. }
  649. /**
  650. * 更新比赛结果
  651. */
  652. const updateGamesResult = (result) => {
  653. syncGamesResult(result);
  654. return Promise.resolve();
  655. }
  656. /**
  657. * 同步中单方案
  658. */
  659. // const syncSolutions = (solutions) => {
  660. // if (IS_DEV) {
  661. // return Logs.out('syncSolutions', solutions);
  662. // }
  663. // axios.post(`${BASE_API_URL}/p/syncDsOpportunity`, solutions, { proxy: false })
  664. // .then(res => {
  665. // // Logs.out('syncSolutions', res.data);
  666. // })
  667. // .catch(err => {
  668. // Logs.out('syncSolutions', err.message);
  669. // });
  670. // }
  671. /**
  672. * 更新中单方案
  673. */
  674. const getCprKey = (cpr) => {
  675. const { k, p, v } = cpr;
  676. return `${k}_${p}_${v}`;
  677. }
  678. const compareCpr = (cpr1, cpr2) => {
  679. const key1 = getCprKey(cpr1);
  680. const key2 = getCprKey(cpr2);
  681. return key1 === key2;
  682. }
  683. const updateSolutions = (solutions, eventsLogsMap) => {
  684. if (solutions?.length) {
  685. const solutionsHistory = GAMES.Solutions;
  686. const updateIds = { add: [], update: [], retain: [], remove: [] }
  687. solutions.forEach(item => {
  688. const { sid, cpr, sol: { win_average, win_profit_rate } } = item;
  689. if (!solutionsHistory[sid]) {
  690. solutionsHistory[sid] = item;
  691. updateIds.add.push(sid);
  692. return;
  693. }
  694. const historySolution = solutionsHistory[sid];
  695. if (historySolution.sol.win_average !== win_average ||
  696. historySolution.sol.win_profit_rate !== win_profit_rate ||
  697. !compareCpr(historySolution.cpr, cpr)) {
  698. solutionsHistory[sid] = item;
  699. updateIds.update.push(sid);
  700. return;
  701. }
  702. const { timestamp } = item;
  703. historySolution.timestamp = timestamp;
  704. updateIds.retain.push(sid);
  705. });
  706. const solutionsMap = new Map(solutions.map(item => [item.sid, item]));
  707. Object.keys(solutionsHistory).forEach(sid => {
  708. if (!solutionsMap.has(sid)) {
  709. delete solutionsHistory[sid];
  710. updateIds.remove.push(sid);
  711. }
  712. });
  713. const solutionUpdate = {};
  714. Object.keys(updateIds).forEach(key => {
  715. if (key == 'retain' || key == 'remove') {
  716. solutionUpdate[key] = updateIds[key];
  717. }
  718. else {
  719. solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  720. }
  721. });
  722. // syncSolutions(solutionUpdate);
  723. if (updateIds.add.length / solutions.length > 0.25 ||
  724. updateIds.remove.length / solutions.length > 0.25
  725. ) {
  726. const { expireEvents, removeEvents } = eventsLogsMap;
  727. const expireEvemtsMap = {};
  728. expireEvents.forEach(item => {
  729. const { mk, platform, info, evExpire, spExpire, evtime, sptime } = item;
  730. if (!expireEvemtsMap[mk]) {
  731. expireEvemtsMap[mk] = {};
  732. }
  733. if (!expireEvemtsMap[mk][platform]) {
  734. expireEvemtsMap[mk][platform] = {};
  735. }
  736. if (!expireEvemtsMap[mk][platform].list) {
  737. expireEvemtsMap[mk][platform].list = [];
  738. }
  739. if (!expireEvemtsMap[mk][platform].evtime) {
  740. expireEvemtsMap[mk][platform].evtime = evtime;
  741. }
  742. if (!expireEvemtsMap[mk][platform].sptime) {
  743. expireEvemtsMap[mk][platform].sptime = sptime;
  744. }
  745. expireEvemtsMap[mk][platform].list.push({ info, evExpire, spExpire, evtime, sptime });
  746. });
  747. Object.keys(expireEvemtsMap).forEach(mk => {
  748. Object.keys(expireEvemtsMap[mk]).forEach(platform => {
  749. Logs.out('invalid events, mk %d, platform %s, expire %d, evtime %d, sptime %d',
  750. mk, platform,
  751. expireEvemtsMap[mk][platform].list.length,
  752. expireEvemtsMap[mk][platform].evtime,
  753. expireEvemtsMap[mk][platform].sptime,
  754. )
  755. });
  756. });
  757. Logs.out('solutions add %d, update %d, retain %d, remove %d',
  758. updateIds.add.length, updateIds.update.length, updateIds.retain.length, updateIds.remove.length);
  759. }
  760. else {
  761. Logs.outDev('solutions update complete', updateIds);
  762. }
  763. }
  764. }
  765. /**
  766. * 获取中单方案
  767. */
  768. const getSolutions = async ({ win_min, with_events, mk=-1 }) => {
  769. // Logs.out('getSolutions', win_min);
  770. const filterMarketType = +mk;
  771. const { minShowAmount } = getSetting();
  772. const solutionsList = Object.values(GAMES.Solutions);
  773. const gamesRelation = getGamesRelation();
  774. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  775. const mkCount = {
  776. all: 0,
  777. rollball: 0,
  778. today: 0,
  779. early: 0,
  780. }
  781. let solutions = solutionsList.filter(item => {
  782. const { sol: { win_average } } = item;
  783. return win_average >= (win_min ?? minShowAmount);
  784. })
  785. .map(item => {
  786. const { info: { id } } = item;
  787. const { mk, rel } = relationsMap.get(id);
  788. const marketType = getMarketType(mk);
  789. mkCount.all ++;
  790. mkCount[marketType] ++;
  791. return {
  792. ...item,
  793. info: { id, mk, ...rel }
  794. }
  795. });
  796. if (mk >= 0) {
  797. solutions = solutions.filter(item => {
  798. const { info: { mk } } = item;
  799. return mk == filterMarketType;
  800. });
  801. }
  802. solutions = solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  803. const relIds = solutions.map(item => item.info.id);
  804. let gamesEvents;
  805. if (with_events) {
  806. gamesEvents = getGamesEvents({ relIds });
  807. }
  808. return { solutions, gamesEvents, mkCount };
  809. }
  810. /**
  811. * 获取中单方案并按照比赛分组
  812. */
  813. const getGamesSolutions = async ({ win_min, with_events, mk=-1, tp=0, sk }) => {
  814. const filterMarketType = +mk;
  815. const filterDataType = +tp;
  816. const { minShowAmount } = getSetting();
  817. const solutionsList = Object.values(GAMES.Solutions);
  818. const gamesRelation = getGamesRelation({ listEvents: with_events });
  819. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  820. const mkCount = {
  821. all: 0,
  822. rollball: 0,
  823. today: 0,
  824. early: 0,
  825. }
  826. const solutionsMap = {};
  827. solutionsList.forEach(item => {
  828. const { info: { id }, ...solution } = item;
  829. const { rule, sol: { win_average } } = solution;
  830. const ruleType = getRuleType(rule);
  831. if ((filterDataType == 0 || filterDataType == ruleType) && (!!sk || win_average >= (win_min ?? minShowAmount))) {
  832. const gameRelation = relationsMap.get(id);
  833. if (!solutionsMap[id]) {
  834. solutionsMap[id] = { ...gameRelation, solutions: [] };
  835. }
  836. solutionsMap[id].solutions.push(solution);
  837. }
  838. })
  839. const gamesSolutions = Object.values(solutionsMap)
  840. .filter(item => {
  841. const { mk, rel, solutions } = item;
  842. const marketType = getMarketType(mk);
  843. if (!sk || matchGame(rel, sk)) {
  844. mkCount.all ++;
  845. mkCount[marketType] ++;
  846. solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  847. return filterMarketType == -1 || filterMarketType == mk;
  848. }
  849. return false;
  850. })
  851. .sort((a, b) => b.solutions[0].sol.win_average - a.solutions[0].sol.win_average);
  852. return { gamesSolutions, mkCount };
  853. }
  854. /**
  855. * 获取单个中单方案
  856. */
  857. const getSolution = async (sid) => {
  858. if (!sid) {
  859. return Promise.reject(new Error('sid is required'));
  860. }
  861. const solution = GAMES.Solutions[sid];
  862. if (!solution) {
  863. return Promise.reject(new Error('solution not found'));
  864. }
  865. return solution;
  866. }
  867. /**
  868. * 通过比赛 ID 获取中单方案
  869. */
  870. const getSolutionsByIds = async (ids) => {
  871. const baseList = Object.values(GAMES.Baselist).flat();
  872. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  873. const result = {};
  874. ids.forEach(id => {
  875. const baseGame = baseMap.get(id);
  876. result[id] = {};
  877. result[id].matches = baseGame?.matches ?? [];
  878. result[id].sols = [];
  879. });
  880. Object.values(GAMES.Solutions).forEach(item => {
  881. const { info: { id } } = item;
  882. if (result[id]) {
  883. result[id].sols.push(item);
  884. }
  885. });
  886. return result;
  887. }
  888. /**
  889. * 清理中单方案
  890. */
  891. const solutionsCleanup = () => {
  892. const solutionsHistory = GAMES.Solutions;
  893. const updateIds = { remove: [] }
  894. Object.keys(solutionsHistory).forEach(sid => {
  895. const { timestamp } = solutionsHistory[sid];
  896. const nowTime = Date.now();
  897. if (nowTime - timestamp > 1000*60) {
  898. delete solutionsHistory[sid];
  899. updateIds.remove.push(sid);
  900. return;
  901. }
  902. const solution = solutionsHistory[sid];
  903. const eventTime = solution.info.timestamp;
  904. if (nowTime > eventTime) {
  905. delete solutionsHistory[sid];
  906. updateIds.remove.push(sid);
  907. }
  908. });
  909. // if (updateIds.remove.length) {
  910. // syncSolutions(updateIds);
  911. // }
  912. }
  913. /**
  914. * 清理更新时间戳
  915. */
  916. const cleanupUpdateTimestamp = () => {
  917. const updateTimestamp = GAMES.UpdateTimestamp;
  918. const nowTime = Date.now();
  919. const expireTime = nowTime - 1000*60;
  920. Object.keys(updateTimestamp).forEach(key => {
  921. if (updateTimestamp[key] < expireTime) {
  922. delete updateTimestamp[key];
  923. }
  924. });
  925. }
  926. /**
  927. * 定时清理中单方案
  928. * 定时清理盘口信息
  929. */
  930. setInterval(() => {
  931. // cleanupBaseList();
  932. solutionsCleanup();
  933. gamesRelationCleanup();
  934. cleanupUpdateTimestamp();
  935. }, 1000*30);
  936. /**
  937. * 获取综合利润
  938. */
  939. const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
  940. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  941. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  942. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  943. const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
  944. return profit;
  945. }
  946. /**
  947. * 通过 sid 获取综合利润
  948. */
  949. const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
  950. const preSolution = GAMES.Solutions[sid1];
  951. const subSolution = GAMES.Solutions[sid2];
  952. const sol1 = preSolution?.sol;
  953. const sol2 = subSolution?.sol;
  954. if (!sol1) {
  955. return Promise.reject(new Error('sid1 已失效'));
  956. }
  957. if (!sol2) {
  958. return Promise.reject(new Error('sid2 已失效'));
  959. }
  960. const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  961. return { profit, solutions: [preSolution, subSolution] };
  962. }
  963. /**
  964. * 通过盘口信息获取综合利润
  965. */
  966. const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
  967. if (!betInfo1?.cross_type) {
  968. return Promise.reject(new Error('第一个下注信息无效'));
  969. }
  970. if (!betInfo2?.cross_type) {
  971. return Promise.reject(new Error('第二个下注信息无效'));
  972. }
  973. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  974. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  975. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  976. if (fixed) {
  977. return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
  978. }
  979. const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
  980. return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  981. }
  982. /**
  983. * 同步Qboss平台配置
  984. */
  985. const syncQbossConfig = () => {
  986. const setting = getSetting();
  987. if (!setting.syncSettingEnabled) {
  988. // Logs.outDev('syncQbossConfig disabled');
  989. return setTimeout(syncQbossConfig, 1000*5);
  990. }
  991. axios.get(`${BASE_API_URL}/p/QbossSystemConfig`, { proxy: false })
  992. .then(res => {
  993. const { data } = res;
  994. if (!data?.data) {
  995. throw new Error('syncQbossConfig data is empty');
  996. }
  997. const {
  998. qboss_return_ratio,
  999. ob_return_ratio, ob_return_type,
  1000. hg_return_ratio, hg_return_type,
  1001. qboss_jq_add_odds, qboss_jq_add_hours,
  1002. qboss_gq_add_dy_odds, qboss_gq_add_jq_odds,
  1003. } = data.data;
  1004. const qbossSetting = {
  1005. innerRebateRatio: +qboss_return_ratio,
  1006. obRebateRatio: +ob_return_ratio,
  1007. obRebateType: +ob_return_type,
  1008. hgRebateRatio: +hg_return_ratio,
  1009. hgRebateType: +hg_return_type,
  1010. subsidyTime: +qboss_jq_add_hours,
  1011. subsidyAmount: +qboss_jq_add_odds,
  1012. subsidyRbWmAmount: +qboss_gq_add_dy_odds,
  1013. subsidyRbOtAmount: +qboss_gq_add_jq_odds,
  1014. };
  1015. const settingFields = {};
  1016. let needUpdate = false;
  1017. Object.keys(qbossSetting).forEach(key => {
  1018. if (qbossSetting[key] !== setting[key]) {
  1019. settingFields[key] = qbossSetting[key];
  1020. needUpdate = true;
  1021. }
  1022. });
  1023. if (needUpdate) {
  1024. Setting.update(settingFields);
  1025. // Logs.outDev('syncQbossConfig', settingFields);
  1026. }
  1027. // else {
  1028. // Logs.outDev('syncQbossConfig no change');
  1029. // }
  1030. })
  1031. .catch(err => {
  1032. Logs.out('syncQbossConfig error', err.message);
  1033. })
  1034. .finally(() => {
  1035. setTimeout(syncQbossConfig, 1000*15);
  1036. });
  1037. }
  1038. syncQbossConfig();
  1039. /**
  1040. * 异常通知
  1041. */
  1042. const notifyException = (message) => {
  1043. if (IS_DEV) {
  1044. return Logs.out('notifyException', { message });
  1045. }
  1046. const chat_id = -1003032820471;
  1047. axios.get(`${BASE_API_URL}/telegram/jump`, { params: { chat_id, message } }, { proxy: false })
  1048. .then(() => {
  1049. Logs.out('notifyException', '通知成功');
  1050. })
  1051. .catch(err => {
  1052. Logs.out('notifyException', err.message);
  1053. });
  1054. }
  1055. /**
  1056. * 从子进程获取数据
  1057. */
  1058. const getDataFromChild = (type, callback) => {
  1059. const id = ++Request.count;
  1060. Request.callbacks[id] = callback;
  1061. events_child.send({ method: 'get', id, type });
  1062. }
  1063. /**
  1064. * 向子进程发送数据
  1065. */
  1066. const postDataToChild = (type, data) => {
  1067. events_child.send({ method: 'post', type, data });
  1068. }
  1069. /**
  1070. * 处理子进程消息
  1071. */
  1072. events_child.on('message', async (message) => {
  1073. const { callbacks } = Request;
  1074. const { method, id, type, data } = message;
  1075. if (method == 'get' && id) {
  1076. let responseData = null;
  1077. if (type == 'getGamesRelation') {
  1078. responseData = getGamesRelation({ listEvents: true });
  1079. }
  1080. else if (type == 'getSetting') {
  1081. responseData = getSetting();
  1082. }
  1083. // else if (type == 'getSolutionHistory') {
  1084. // responseData = getSolutionHistory();
  1085. // }
  1086. events_child.send({ type: 'response', id, data: responseData });
  1087. }
  1088. else if (method == 'post') {
  1089. if (type == 'updateSolutions') {
  1090. updateSolutions(data.solutions, data.eventsLogsMap);
  1091. }
  1092. }
  1093. else if (method == 'response' && id && callbacks[id]) {
  1094. callbacks[id](data);
  1095. delete callbacks[id];
  1096. }
  1097. });
  1098. events_child.stderr?.on('data', data => {
  1099. Logs.out('events_child stderr', data.toString());
  1100. });
  1101. const settingUpdate = (fields) => {
  1102. updateSetting(fields);
  1103. postDataToChild('updateSetting', fields);
  1104. }
  1105. const syncSetting = async () => {
  1106. const setting = await Setting.get();
  1107. settingUpdate(setting.toObject());
  1108. }
  1109. syncSetting();
  1110. Setting.onUpdate(settingUpdate);
  1111. /**
  1112. * 保存GAMES数据到缓存文件
  1113. */
  1114. const saveGamesToCache = () => {
  1115. Cache.setData(GamesCacheFile, GAMES, err => {
  1116. if (err) {
  1117. Logs.out('Failed to save games cache:', err.message);
  1118. }
  1119. else {
  1120. Logs.out('Games cache saved successfully');
  1121. }
  1122. });
  1123. }
  1124. /**
  1125. * 从缓存文件加载GAMES数据
  1126. */
  1127. const loadGamesFromCache = () => {
  1128. const gamesCacheData = Cache.getData(GamesCacheFile, true);
  1129. Object.keys(GAMES).forEach(key => {
  1130. if (gamesCacheData[key]) {
  1131. GAMES[key] = gamesCacheData[key];
  1132. }
  1133. });
  1134. Logs.out('Games cache loaded successfully');
  1135. }
  1136. // 在模块加载时尝试从缓存恢复数据
  1137. loadGamesFromCache();
  1138. // 监听进程退出事件,保存GAMES数据
  1139. process.on('exit', saveGamesToCache);
  1140. process.on('SIGINT', () => {
  1141. process.exit(0);
  1142. });
  1143. process.on('SIGTERM', () => {
  1144. process.exit(0);
  1145. });
  1146. process.on('SIGUSR2', () => {
  1147. process.exit(0);
  1148. });
  1149. module.exports = {
  1150. updateLeaguesList, getFilteredLeagues,
  1151. updateGamesList, updateGamesEvents,
  1152. getGamesRelation,
  1153. updateGamesResult,
  1154. getSolutions, getGamesSolutions, getSolution, getSolutionsByIds,
  1155. getTotalProfitWithSid,
  1156. getTotalProfitWithBetInfo,
  1157. notifyException,
  1158. }