GamesPs.js 35 KB

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