GamesPs.js 32 KB

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