GamesPs.js 33 KB

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