GamesPs.js 32 KB

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