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. 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, 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. if (typeof(mk) === 'undefined' || mk === '') {
  472. return true;
  473. }
  474. return item.mk == mk;
  475. }).sort((a, b) => a.timestamp - b.timestamp);
  476. if (listEvents) {
  477. return relations;
  478. }
  479. const gamesRelation = relations.map(item => {
  480. const { rel, ...relationInfo } = item;
  481. const tempRel = { ...rel };
  482. Object.keys(tempRel).forEach(platform => {
  483. const { events, evtime, sptime, special, ...gameInfo } = tempRel[platform];
  484. tempRel[platform] = gameInfo;
  485. });
  486. return { ...relationInfo, rel: tempRel };
  487. });
  488. return gamesRelation;
  489. }
  490. /**
  491. * 定时更新关联比赛列表
  492. */
  493. const updateGamesRelation = () => {
  494. fetchGamesRelation()
  495. .then(gamesRelation => {
  496. const baseList = {};
  497. gamesRelation.map(item => {
  498. const baseGame = item.rel?.['ps'] ?? {};
  499. return { ...baseGame, mk: item.mk };
  500. }).forEach(item => {
  501. const marketType = getMarketType(item.mk);
  502. if (!baseList[marketType]) {
  503. baseList[marketType] = [];
  504. }
  505. baseList[marketType].push(item);
  506. });
  507. Object.keys(baseList).forEach(marketType => {
  508. syncBaseList({ marketType, games: baseList[marketType] });
  509. });
  510. const updateCount = {
  511. add: 0,
  512. update: 0,
  513. delete: 0
  514. };
  515. gamesRelation.forEach(item => {
  516. const { id, mk } = item;
  517. const oldItem = GAMES.Relations[id];
  518. if (!oldItem) {
  519. GAMES.Relations[id] = item;
  520. updateCount.add ++;
  521. }
  522. else if (oldItem.mk != mk) {
  523. GAMES.Relations[id] = item;
  524. updateCount.update ++;
  525. }
  526. });
  527. const relations = new Set(gamesRelation.map(item => +item.id));
  528. Object.keys(GAMES.Relations).forEach(id => {
  529. if (!relations.has(+id)) {
  530. delete GAMES.Relations[id];
  531. updateCount.delete ++;
  532. }
  533. });
  534. if (updateCount.add || updateCount.update || updateCount.delete) {
  535. Logs.out('updateGamesRelation', updateCount);
  536. }
  537. else {
  538. Logs.outDev('updateGamesRelation', updateCount);
  539. }
  540. })
  541. .catch(err => {
  542. Logs.out('updateGamesRelation', err.message);
  543. })
  544. .finally(() => {
  545. setTimeout(updateGamesRelation, 60000);
  546. });
  547. }
  548. updateGamesRelation();
  549. const gamesRelationCleanup = () => {
  550. const relations = Object.values(GAMES.Relations);
  551. const expireTime = Date.now() - 1000*60;
  552. relations.forEach(item => {
  553. const { rel } = item;
  554. Object.keys(rel).forEach(platform => {
  555. const { evtime, sptime } = rel[platform];
  556. if (evtime && evtime < expireTime) {
  557. delete rel[platform].events;
  558. delete rel[platform].evtime;
  559. }
  560. if (sptime && sptime < expireTime) {
  561. delete rel[platform].special;
  562. delete rel[platform].sptime;
  563. }
  564. });
  565. });
  566. }
  567. /**
  568. * 同步比赛结果
  569. */
  570. const syncGamesResult = async (result) => {
  571. if (IS_DEV) {
  572. return Logs.out('updateGamesResult', result);
  573. }
  574. axios.post(`${BASE_API_URL}/p/syncMatchResult`, result, { proxy: false })
  575. .then(res => {
  576. // Logs.out('syncMatchResult', res.data);
  577. })
  578. .catch(err => {
  579. Logs.out('syncMatchResult', err.message);
  580. });
  581. }
  582. /**
  583. * 更新比赛结果
  584. */
  585. const updateGamesResult = (result) => {
  586. syncGamesResult(result);
  587. return Promise.resolve();
  588. }
  589. /**
  590. * 同步中单方案
  591. */
  592. const syncSolutions = (solutions) => {
  593. if (IS_DEV) {
  594. return Logs.out('syncSolutions', solutions);
  595. }
  596. axios.post(`${BASE_API_URL}/p/syncDsOpportunity`, solutions, { proxy: false })
  597. .then(res => {
  598. // Logs.out('syncSolutions', res.data);
  599. })
  600. .catch(err => {
  601. Logs.out('syncSolutions', err.message);
  602. });
  603. }
  604. /**
  605. * 更新中单方案
  606. */
  607. const getCprKey = (cpr) => {
  608. const { k, p, v } = cpr;
  609. return `${k}_${p}_${v}`;
  610. }
  611. const compareCpr = (cpr1, cpr2) => {
  612. const key1 = getCprKey(cpr1);
  613. const key2 = getCprKey(cpr2);
  614. return key1 === key2;
  615. }
  616. const updateSolutions = (solutions, eventsLogsMap) => {
  617. if (solutions?.length) {
  618. const solutionsHistory = GAMES.Solutions;
  619. const updateIds = { add: [], update: [], retain: [], remove: [] }
  620. solutions.forEach(item => {
  621. const { sid, cpr, sol: { win_average } } = item;
  622. if (!solutionsHistory[sid]) {
  623. solutionsHistory[sid] = item;
  624. updateIds.add.push(sid);
  625. return;
  626. }
  627. const historySolution = solutionsHistory[sid];
  628. if (historySolution.sol.win_average !== win_average || !compareCpr(historySolution.cpr, cpr)) {
  629. solutionsHistory[sid] = item;
  630. updateIds.update.push(sid);
  631. return;
  632. }
  633. const { timestamp } = item;
  634. historySolution.timestamp = timestamp;
  635. updateIds.retain.push(sid);
  636. });
  637. const solutionsMap = new Map(solutions.map(item => [item.sid, item]));
  638. Object.keys(solutionsHistory).forEach(sid => {
  639. if (!solutionsMap.has(sid)) {
  640. delete solutionsHistory[sid];
  641. updateIds.remove.push(sid);
  642. }
  643. });
  644. const solutionUpdate = {};
  645. Object.keys(updateIds).forEach(key => {
  646. if (key == 'retain' || key == 'remove') {
  647. solutionUpdate[key] = updateIds[key];
  648. }
  649. else {
  650. solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  651. }
  652. });
  653. syncSolutions(solutionUpdate);
  654. if (updateIds.add.length / solutions.length > 0.25 ||
  655. updateIds.remove.length / solutions.length > 0.25
  656. ) {
  657. const { expireEvents, removeEvents } = eventsLogsMap;
  658. const expireEvemtsMap = {};
  659. expireEvents.forEach(item => {
  660. const { mk, platform, info, evExpire, spExpire, evtime, sptime } = item;
  661. if (!expireEvemtsMap[mk]) {
  662. expireEvemtsMap[mk] = {};
  663. }
  664. if (!expireEvemtsMap[mk][platform]) {
  665. expireEvemtsMap[mk][platform] = {};
  666. }
  667. if (!expireEvemtsMap[mk][platform].list) {
  668. expireEvemtsMap[mk][platform].list = [];
  669. }
  670. if (!expireEvemtsMap[mk][platform].evtime) {
  671. expireEvemtsMap[mk][platform].evtime = evtime;
  672. }
  673. if (!expireEvemtsMap[mk][platform].sptime) {
  674. expireEvemtsMap[mk][platform].sptime = sptime;
  675. }
  676. expireEvemtsMap[mk][platform].list.push({ info, evExpire, spExpire, evtime, sptime });
  677. });
  678. Object.keys(expireEvemtsMap).forEach(mk => {
  679. Object.keys(expireEvemtsMap[mk]).forEach(platform => {
  680. Logs.out('invalid events, mk %d, platform %s, expire %d, evtime %d, sptime %d',
  681. mk, platform,
  682. expireEvemtsMap[mk][platform].list.length,
  683. expireEvemtsMap[mk][platform].evtime,
  684. expireEvemtsMap[mk][platform].sptime,
  685. )
  686. });
  687. });
  688. Logs.out('solutions add %d, update %d, retain %d, remove %d',
  689. updateIds.add.length, updateIds.update.length, updateIds.retain.length, updateIds.remove.length);
  690. }
  691. else {
  692. Logs.outDev('solutions update complete');
  693. }
  694. }
  695. }
  696. /**
  697. * 获取中单方案
  698. */
  699. const getSolutions = async ({ win_min, no_events }) => {
  700. // Logs.out('getSolutions', win_min);
  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 solutions = solutionsList.sort((a, b) => b.sol.win_average - a.sol.win_average)
  706. .filter(item => {
  707. const { sol: { win_average } } = item;
  708. return win_average >= (win_min ?? minShowAmount);
  709. })
  710. .map(item => {
  711. const { info: { id } } = item;
  712. const { mk, rel } = relationsMap.get(id);
  713. return {
  714. ...item,
  715. info: { id, mk, ...rel }
  716. }
  717. });
  718. const relIds = solutions.map(item => item.info.id);
  719. let gamesEvents = null;
  720. if (!no_events) {
  721. gamesEvents = getGamesEvents({ relIds });
  722. }
  723. return { solutions, gamesEvents };
  724. }
  725. /**
  726. * 获取单个中单方案
  727. */
  728. const getSolution = async (sid) => {
  729. if (!sid) {
  730. return Promise.reject(new Error('sid is required'));
  731. }
  732. const solution = GAMES.Solutions[sid];
  733. if (!solution) {
  734. return Promise.reject(new Error('solution not found'));
  735. }
  736. return solution;
  737. }
  738. /**
  739. * 通过比赛 ID 获取中单方案
  740. */
  741. const getSolutionsByIds = async (ids) => {
  742. const baseList = Object.values(GAMES.Baselist).flat();
  743. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  744. const result = {};
  745. ids.forEach(id => {
  746. const baseGame = baseMap.get(id);
  747. result[id] = {};
  748. result[id].matches = baseGame?.matches ?? [];
  749. result[id].sols = [];
  750. });
  751. Object.values(GAMES.Solutions).forEach(item => {
  752. const { info: { id } } = item;
  753. if (result[id]) {
  754. result[id].sols.push(item);
  755. }
  756. });
  757. return result;
  758. }
  759. /**
  760. * 清理中单方案
  761. */
  762. const solutionsCleanup = () => {
  763. const solutionsHistory = GAMES.Solutions;
  764. const updateIds = { remove: [] }
  765. Object.keys(solutionsHistory).forEach(sid => {
  766. const { timestamp } = solutionsHistory[sid];
  767. const nowTime = Date.now();
  768. if (nowTime - timestamp > 1000*60) {
  769. delete solutionsHistory[sid];
  770. updateIds.remove.push(sid);
  771. return;
  772. }
  773. const solution = solutionsHistory[sid];
  774. const eventTime = solution.info.timestamp;
  775. if (nowTime > eventTime) {
  776. delete solutionsHistory[sid];
  777. updateIds.remove.push(sid);
  778. }
  779. });
  780. if (updateIds.remove.length) {
  781. syncSolutions(updateIds);
  782. }
  783. }
  784. /**
  785. * 定时清理中单方案
  786. * 定时清理盘口信息
  787. */
  788. setInterval(() => {
  789. cleanupBaseList();
  790. solutionsCleanup();
  791. gamesRelationCleanup();
  792. }, 1000*30);
  793. /**
  794. * 获取综合利润
  795. */
  796. const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
  797. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  798. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  799. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  800. const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
  801. return profit;
  802. }
  803. /**
  804. * 通过 sid 获取综合利润
  805. */
  806. const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
  807. const preSolution = GAMES.Solutions[sid1];
  808. const subSolution = GAMES.Solutions[sid2];
  809. const sol1 = preSolution?.sol;
  810. const sol2 = subSolution?.sol;
  811. if (!sol1) {
  812. return Promise.reject(new Error('sid1 已失效'));
  813. }
  814. if (!sol2) {
  815. return Promise.reject(new Error('sid2 已失效'));
  816. }
  817. const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  818. return { profit, solutions: [preSolution, subSolution] };
  819. }
  820. /**
  821. * 通过盘口信息获取综合利润
  822. */
  823. const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
  824. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  825. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  826. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  827. if (fixed) {
  828. return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
  829. }
  830. const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
  831. return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  832. }
  833. /**
  834. * 获取后台设置
  835. */
  836. // const getSetting = async () => {
  837. // return ;
  838. // }
  839. /**
  840. * 异常通知
  841. */
  842. const notifyException = (message) => {
  843. if (IS_DEV) {
  844. return Logs.out('notifyException', { message });
  845. }
  846. const chat_id = -1003032820471;
  847. axios.get(`${BASE_API_URL}/telegram/jump`, { params: { chat_id, message } }, { proxy: false })
  848. .then(() => {
  849. Logs.out('notifyException', '通知成功');
  850. })
  851. .catch(err => {
  852. Logs.out('notifyException', err.message);
  853. });
  854. }
  855. /**
  856. * 从子进程获取数据
  857. */
  858. const getDataFromChild = (type, callback) => {
  859. const id = ++Request.count;
  860. Request.callbacks[id] = callback;
  861. events_child.send({ method: 'get', id, type });
  862. }
  863. /**
  864. * 向子进程发送数据
  865. */
  866. const postDataToChild = (type, data) => {
  867. events_child.send({ method: 'post', type, data });
  868. }
  869. /**
  870. * 处理子进程消息
  871. */
  872. events_child.on('message', async (message) => {
  873. const { callbacks } = Request;
  874. const { method, id, type, data } = message;
  875. if (method == 'get' && id) {
  876. let responseData = null;
  877. if (type == 'getGamesRelation') {
  878. responseData = getGamesRelation({ listEvents: true });
  879. }
  880. else if (type == 'getSetting') {
  881. responseData = getSetting();
  882. }
  883. // else if (type == 'getSolutionHistory') {
  884. // responseData = getSolutionHistory();
  885. // }
  886. events_child.send({ type: 'response', id, data: responseData });
  887. }
  888. else if (method == 'post') {
  889. if (type == 'updateSolutions') {
  890. updateSolutions(data.solutions, data.eventsLogsMap);
  891. }
  892. }
  893. else if (method == 'response' && id && callbacks[id]) {
  894. callbacks[id](data);
  895. delete callbacks[id];
  896. }
  897. });
  898. events_child.stderr?.on('data', data => {
  899. Logs.out('events_child stderr', data.toString());
  900. });
  901. const settingUpdate = (fields) => {
  902. updateSetting(fields);
  903. postDataToChild('updateSetting', fields);
  904. }
  905. const syncSetting = async () => {
  906. const setting = await Setting.get();
  907. settingUpdate(setting.toObject());
  908. }
  909. syncSetting();
  910. Setting.onUpdate(settingUpdate);
  911. /**
  912. * 保存GAMES数据到缓存文件
  913. */
  914. const saveGamesToCache = () => {
  915. Cache.setData(GamesCacheFile, GAMES, err => {
  916. if (err) {
  917. Logs.out('Failed to save games cache:', err.message);
  918. }
  919. else {
  920. Logs.out('Games cache saved successfully');
  921. }
  922. });
  923. }
  924. /**
  925. * 从缓存文件加载GAMES数据
  926. */
  927. const loadGamesFromCache = () => {
  928. const gamesCacheData = Cache.getData(GamesCacheFile, true);
  929. Object.assign(GAMES, gamesCacheData);
  930. Logs.out('Games cache loaded successfully');
  931. }
  932. // 在模块加载时尝试从缓存恢复数据
  933. loadGamesFromCache();
  934. // 监听进程退出事件,保存GAMES数据
  935. process.on('exit', saveGamesToCache);
  936. process.on('SIGINT', () => {
  937. process.exit(0);
  938. });
  939. process.on('SIGTERM', () => {
  940. process.exit(0);
  941. });
  942. process.on('SIGUSR2', () => {
  943. process.exit(0);
  944. });
  945. module.exports = {
  946. updateLeaguesList, getFilteredLeagues,
  947. updateGamesList, updateGamesEvents,
  948. getGamesRelation,
  949. updateGamesResult,
  950. getSolutions, getSolution, getSolutionsByIds,
  951. getTotalProfitWithSid,
  952. getTotalProfitWithBetInfo,
  953. notifyException,
  954. }