GamesPs.js 28 KB

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