GamesPs.js 29 KB

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