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. ObOriginalData: {},
  46. UpdateTimestamp: {},
  47. };
  48. const Request = {
  49. callbacks: {},
  50. count: 0,
  51. }
  52. /**
  53. * 精确浮点数字
  54. * @param {number} number
  55. * @param {number} x
  56. * @returns {number}
  57. */
  58. const fixFloat = (number, x=2) => {
  59. return parseFloat(number.toFixed(x));
  60. }
  61. /**
  62. * 获取市场类型
  63. */
  64. const getMarketType = (mk) => {
  65. if (mk == 0) {
  66. return 'early';
  67. }
  68. else if (mk == 2) {
  69. return 'rollball';
  70. }
  71. return 'today';
  72. }
  73. /**
  74. * 获取策略类型
  75. */
  76. const getRuleType = (rule) => {
  77. const rulePrefix = rule.split(':')[0];
  78. return IOR_KEYS_TYPE[rulePrefix];
  79. }
  80. /**
  81. * 关键词匹配比赛
  82. */
  83. const matchGame = (relation, sk) => {
  84. const keys = [];
  85. Object.keys(relation).forEach(platform => {
  86. const { leagueName, teamHomeName, teamAwayName } = relation[platform];
  87. if (platform == 'ps') {
  88. keys.push(leagueName);
  89. }
  90. keys.push(teamHomeName, teamAwayName);
  91. });
  92. return keys.some(key => key.includes(sk));
  93. }
  94. /**
  95. * 同步联赛列表
  96. */
  97. const syncLeaguesList = ({ mk, leagues }) => {
  98. if (IS_DEV) {
  99. return Logs.out('syncLeaguesList', { mk, leagues });
  100. }
  101. axios.post(`${BASE_API_URL}/p/syncLeague`, { mk, leagues }, { proxy: false })
  102. .then(res => {
  103. // Logs.out('syncLeaguesList', res.data);
  104. })
  105. .catch(err => {
  106. Logs.out('syncLeaguesList', err.message);
  107. });
  108. }
  109. /**
  110. * 更新联赛列表
  111. */
  112. const updateLeaguesList = ({ mk, leagues, platform='ps' }) => {
  113. const { Leagues } = GAMES;
  114. if (!Leagues[platform]) {
  115. Leagues[platform] = {};
  116. }
  117. const leaguesMap = Leagues[platform];
  118. const nowTime = Date.now();
  119. const expireTime = nowTime - 1000 * 60 * 5;
  120. if (!leaguesMap[mk]) {
  121. leaguesMap[mk] = {
  122. timestamp: 0,
  123. leagues: [],
  124. };
  125. }
  126. if (leaguesMap[mk].timestamp < expireTime ||
  127. JSON.stringify(leaguesMap[mk].leagues) != JSON.stringify(leagues)) {
  128. leaguesMap[mk].leagues = leagues;
  129. leaguesMap[mk].timestamp = nowTime;
  130. if (platform == 'ps') {
  131. syncLeaguesList({ mk, leagues });
  132. }
  133. return leagues.length;
  134. }
  135. return 0;
  136. }
  137. /**
  138. * 获取筛选过的联赛
  139. */
  140. const getFilteredLeagues = async (mk) => {
  141. return axios.get(`${BASE_API_URL}/p/getLeagueTast?mk=${mk ?? ''}`, { proxy: false })
  142. .then(res => {
  143. if (res.data.code == 0) {
  144. return res.data.data;
  145. }
  146. return Promise.reject(new Error(res.data.message));
  147. });
  148. }
  149. /**
  150. * 更新OB原始数据
  151. */
  152. const updateOriginalData = ({ leagues, matches }) => {
  153. const { ObOriginalData } = GAMES;
  154. ObOriginalData.leagues = leagues;
  155. ObOriginalData.matches = matches;
  156. }
  157. /**
  158. * 获取OB原始数据
  159. */
  160. const getOriginalData = () => {
  161. const { ObOriginalData } = GAMES;
  162. return ObOriginalData;
  163. }
  164. /**
  165. * 同步比赛列表到服务器
  166. */
  167. const syncGamesList = ({ platform, mk, games }) => {
  168. if (IS_DEV) {
  169. return Logs.out('syncGamesList', { platform, mk, games });
  170. }
  171. axios.post(`${BASE_API_URL}/p/syncGames`, { platform, mk, games })
  172. .then(res => {
  173. // Logs.out('syncGamesList', { platform, mk, count: games.length }, res.data);
  174. })
  175. .catch(err => {
  176. Logs.out('syncGamesList', { platform, mk }, err.message);
  177. });
  178. }
  179. /**
  180. * 同步基准比赛列表
  181. */
  182. const syncBaseList = ({ marketType, games }) => {
  183. const baseList = GAMES.Baselist;
  184. // 直接创建新列表
  185. if (!baseList[marketType]) {
  186. baseList[marketType] = games;
  187. return;
  188. }
  189. const newMap = new Map(games.map(item => [item.eventId, item]));
  190. // 删除不存在的项
  191. for (let i = baseList[marketType].length - 1; i >= 0; i--) {
  192. if (!newMap.has(baseList[marketType][i].eventId)) {
  193. baseList[marketType].splice(i, 1);
  194. }
  195. }
  196. // 添加或更新
  197. const oldIds = new Set(baseList[marketType].map(item => item.eventId));
  198. games.forEach(game => {
  199. if (!oldIds.has(game.eventId)) {
  200. // 添加新项
  201. baseList[marketType].push(game);
  202. }
  203. });
  204. }
  205. /**
  206. * 清理基准比赛列表
  207. */
  208. // const cleanupBaseList = () => {
  209. // const baseList = GAMES.Baselist;
  210. // const nowTime = Date.now();
  211. // const expireTime = nowTime - 1000*60*60*3;
  212. // Object.keys(baseList).forEach(marketType => {
  213. // baseList[marketType] = baseList[marketType].filter(item => item.timestamp < expireTime);
  214. // });
  215. // }
  216. /**
  217. * 更新比赛列表
  218. */
  219. const updateGamesList = (({ platform, mk, games } = {}) => {
  220. return new Promise((resolve, reject) => {
  221. if (!platform || !games) {
  222. return reject(new Error('PLATFORM_GAMES_INVALID'));
  223. }
  224. syncGamesList({ platform, mk, games });
  225. resolve();
  226. });
  227. });
  228. /**
  229. * 提交盘口数据
  230. */
  231. // const submitOdds = ({ platform, mk, games }) => {
  232. // if (IS_DEV) {
  233. // return Logs.out('syncOdds', { platform, mk, games });
  234. // }
  235. // axios.post(`${BASE_API_URL}/p/syncOdds`, { platform, mk, games}, { proxy: false })
  236. // .then(res => {
  237. // // Logs.out('syncOdds', { platform, mk, count: games.length }, res.data);
  238. // })
  239. // .catch(err => {
  240. // Logs.out('syncOdds', { platform, mk }, err.message);
  241. // });
  242. // }
  243. /**
  244. * 同步基准盘口
  245. */
  246. const syncBaseEvents = ({ mk, games, outrights }) => {
  247. const {
  248. expireTimeEvents, expireTimeSpecial,
  249. subsidyTime, subsidyAmount,
  250. subsidyRbWmAmount, subsidyRbOtAmount
  251. } = getSetting();
  252. const nowTime = Date.now();
  253. const marketType = getMarketType(mk);
  254. const baseList = GAMES.Baselist;
  255. if (!baseList[marketType]) {
  256. return;
  257. }
  258. const baseMap = new Map(baseList[marketType].map(item => [item.eventId, item]));
  259. games?.forEach(game => {
  260. const { eventId, originId, stage, retime, score, wm, evtime, events } = game;
  261. const baseGame = baseMap.get(eventId);
  262. if (baseGame) {
  263. const { mk } = baseGame;
  264. const isRb = (mk == 2);
  265. if (isRb) {
  266. Object.keys(events).forEach(ior => {
  267. if ((ior.startsWith('ior_r') || ior.startsWith('ior_m')) && subsidyRbWmAmount) {
  268. const sourceOdds = events[ior].v;
  269. events[ior].v = fixFloat(sourceOdds * (1 + subsidyRbWmAmount), 3);
  270. events[ior].s = sourceOdds
  271. }
  272. });
  273. }
  274. baseGame.originId = originId;
  275. baseGame.stage = stage;
  276. baseGame.retime = retime;
  277. baseGame.score = score;
  278. baseGame.wm = wm;
  279. baseGame.evtime = evtime;
  280. baseGame.events = events;
  281. }
  282. });
  283. outrights?.forEach(outright => {
  284. const { parentId, sptime, special } = outright;
  285. const baseGame = baseMap.get(parentId);
  286. if (baseGame) { // 赛前特殊盘口
  287. const { timestamp } = baseGame;
  288. const isSubsidy = timestamp > nowTime && timestamp < nowTime + 1000*60*60*subsidyTime;
  289. if (isSubsidy) {
  290. Object.keys(special).forEach(ior => {
  291. if (ior.startsWith('ior_ot') && subsidyAmount) {
  292. const sourceOdds = special[ior].v;
  293. special[ior].v = fixFloat(sourceOdds * (1 + subsidyAmount), 3);
  294. special[ior].s = sourceOdds
  295. }
  296. });
  297. }
  298. baseGame.sptime = sptime;
  299. baseGame.special = special;
  300. }
  301. else {
  302. const originBaseMap = new Map(baseList[marketType].map(item => [item.originId, item]));
  303. const originBaseGame = originBaseMap.get(parentId);
  304. if (originBaseGame) { // 滚球特殊盘口
  305. Object.keys(special).forEach(ior => {
  306. if (ior.startsWith('ior_wm') && subsidyRbWmAmount) {
  307. const sourceOdds = special[ior].v;
  308. special[ior].v = fixFloat(sourceOdds * (1 + subsidyRbWmAmount), 3);
  309. special[ior].s = sourceOdds
  310. }
  311. else if (ior.startsWith('ior_ot') && subsidyRbOtAmount) {
  312. const sourceOdds = special[ior].v;
  313. special[ior].v = fixFloat(sourceOdds * (1 + subsidyRbOtAmount), 3);
  314. special[ior].s = sourceOdds
  315. }
  316. });
  317. originBaseGame.sptime = sptime;
  318. originBaseGame.special = special;
  319. }
  320. }
  321. });
  322. if (games?.length) {
  323. const gamesList = baseList[marketType]?.map(game => {
  324. const { evtime, events, sptime, special, ...gameInfo } = game;
  325. const expireTimeEv = nowTime - expireTimeEvents;
  326. const expireTimeSP = nowTime - expireTimeSpecial;
  327. let odds = {};
  328. if (evtime > expireTimeEv) {
  329. odds = { ...odds, ...events };
  330. }
  331. if (sptime > expireTimeSP) {
  332. odds = { ...odds, ...special };
  333. }
  334. const matches = PS_IOR_KEYS.map(([label, ...keys]) => {
  335. let match = keys.map(key => {
  336. return {
  337. key,
  338. value: odds[key]?.v ?? 0,
  339. origin: odds[key]?.r,
  340. source: odds[key]?.s,
  341. }
  342. });
  343. if (label == 'jqs') {
  344. match = match.filter(item => item.value !== 0);
  345. }
  346. return {
  347. label,
  348. match
  349. };
  350. }).filter(item => {
  351. if (item.label == 'jqs') {
  352. return item.match.length;
  353. }
  354. else {
  355. return item.match.every(entry => entry.value !== 0);
  356. }
  357. });
  358. game.matches = matches; // matches 也记录下来
  359. let uptime = evtime ?? 0;
  360. return { ...gameInfo, matches, uptime };
  361. });
  362. // if (gamesList.filter(item => item.uptime > 0).length) {
  363. // // if (mk == 2) {
  364. // // Logs.out('syncBaseEvents', JSON.stringify({ mk, gamesList }, null, 2));
  365. // // }
  366. // submitOdds({ platform: 'ps', mk, games: gamesList });
  367. // }
  368. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.['ps'] ?? {});
  369. if (!relatedGames.length) {
  370. return 0;
  371. }
  372. let update = 0;
  373. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  374. gamesList?.forEach(game => {
  375. const { eventId, matches, uptime, stage, retime, score, wm } = game;
  376. const relatedGame = relatedMap.get(eventId);
  377. if (relatedGame) {
  378. const events = {};
  379. matches.forEach(({ label, match }) => {
  380. match.forEach(({ key, value, origin, source }) => {
  381. events[key] = {
  382. v: value,
  383. r: origin,
  384. s: source
  385. };
  386. });
  387. });
  388. relatedGame.evtime = uptime;
  389. relatedGame.events = events;
  390. relatedGame.stage = stage;
  391. relatedGame.retime = retime;
  392. relatedGame.score = score;
  393. relatedGame.wm = wm;
  394. update ++;
  395. }
  396. });
  397. return update;
  398. }
  399. }
  400. const updateGamesEvents = ({ platform, mk, games, outrights, timestamp, tp }) => {
  401. return new Promise((resolve, reject) => {
  402. if (!platform || (!games && !outrights)) {
  403. return reject(new Error('PLATFORM_GAMES_INVALID'));
  404. }
  405. const { UpdateTimestamp } = GAMES;
  406. if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
  407. // Logs.out('updateGamesEvents', { tp, timestamp });
  408. UpdateTimestamp[tp] = timestamp;
  409. }
  410. else {
  411. return resolve({ update: 0 });
  412. }
  413. if (platform == 'ps') {
  414. const update = syncBaseEvents({ mk, games, outrights });
  415. return resolve({ update });
  416. }
  417. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.[platform] ?? {});
  418. if (!relatedGames.length) {
  419. return resolve({ update: 0 });
  420. }
  421. const updateCount = {
  422. update: 0
  423. };
  424. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  425. games?.forEach(game => {
  426. const { eventId, evtime, events, stage, retime, score, wm } = game;
  427. const relatedGame = relatedMap.get(eventId);
  428. if (relatedGame) {
  429. relatedGame.evtime = evtime;
  430. relatedGame.events = events;
  431. relatedGame.stage = stage;
  432. relatedGame.retime = retime;
  433. relatedGame.score = score;
  434. relatedGame.wm = wm;
  435. updateCount.update ++;
  436. }
  437. });
  438. outrights?.forEach(outright => {
  439. const { parentId, sptime, special } = outright;
  440. const relatedGame = relatedMap.get(parentId);
  441. if (relatedGame) {
  442. relatedGame.sptime = sptime;
  443. relatedGame.special = special;
  444. updateCount.update ++;
  445. }
  446. });
  447. resolve(updateCount);
  448. });
  449. }
  450. /**
  451. * 获取比赛盘口
  452. */
  453. const getGamesEvents = ({ platform, relIds = [] } = {}) => {
  454. if (!relIds.length) {
  455. return null;
  456. }
  457. const idSet = new Set(relIds);
  458. const relations = { ...GAMES.Relations };
  459. Object.keys(relations).forEach(id => {
  460. if (idSet.size && !idSet.has(+id)) {
  461. delete relations[id];
  462. }
  463. });
  464. if (platform) {
  465. return Object.values(relations).map(rel => rel[platform] ?? {});
  466. }
  467. const gamesEvents = {};
  468. Object.values(relations).forEach(({ rel }) => {
  469. Object.keys(rel).forEach(platform => {
  470. const game = rel[platform] ?? {};
  471. const { eventId, events, special } = game;
  472. if (!gamesEvents[platform]) {
  473. gamesEvents[platform] = {};
  474. }
  475. gamesEvents[platform][eventId] = { ...events, ...special };
  476. });
  477. });
  478. return gamesEvents;
  479. }
  480. /**
  481. * 获取关联比赛
  482. */
  483. const getDevGameTast = () => {
  484. return new Promise((resolve) => {
  485. const data = Cache.getData(DevGameTastFile, true);
  486. resolve({data});
  487. });
  488. }
  489. const fetchGamesRelation = async (mk='') => {
  490. const getGameTast = Promise.all([
  491. getDevGameTast(),
  492. axios.get(`${BASE_API_URL}/p/getGameTast?mk=${mk}`, { proxy: false })
  493. ]);
  494. return getGameTast.then(([res1, res2]) => {
  495. const resData = res1.data ?? res2.data;
  496. if (resData.code == 0) {
  497. const nowTime = Date.now();
  498. const gamesRelation = resData.data?.filter(item => {
  499. const timestamp = new Date(item.timestamp).getTime();
  500. if (nowTime > timestamp) {
  501. item.mk = 2;
  502. }
  503. item.timestamp = timestamp;
  504. const expireTime = timestamp + 1000*60*60*3;
  505. return expireTime > nowTime;
  506. }).map(item => {
  507. const {
  508. id, mk, league_name,
  509. event_id: ps_event_id,
  510. league_id: ps_league_id,
  511. team_home_name: ps_team_home_name,
  512. team_away_name: ps_team_away_name,
  513. ob_event_id, ob_league_id,
  514. ob_team_home_name,
  515. ob_team_away_name,
  516. hg_event_id, hg_league_id,
  517. hg_team_home_name,
  518. hg_team_away_name,
  519. timestamp,
  520. } = item;
  521. const rel = {
  522. ps: {
  523. eventId: +ps_event_id,
  524. leagueId: +ps_league_id,
  525. leagueName: league_name,
  526. teamHomeName: ps_team_home_name,
  527. teamAwayName: ps_team_away_name,
  528. timestamp
  529. },
  530. ob: ob_event_id ? {
  531. eventId: +ob_event_id,
  532. leagueId: +ob_league_id,
  533. leagueName: league_name,
  534. teamHomeName: ob_team_home_name,
  535. teamAwayName: ob_team_away_name,
  536. timestamp
  537. } : null,
  538. hg: hg_event_id ? {
  539. eventId: +hg_event_id,
  540. leagueId: +hg_league_id,
  541. leagueName: league_name,
  542. teamHomeName: hg_team_home_name,
  543. teamAwayName: hg_team_away_name,
  544. timestamp
  545. } : null
  546. };
  547. return { id: ps_event_id, mk, rel, timestamp };
  548. }) ?? [];
  549. return gamesRelation;
  550. }
  551. return Promise.reject(new Error(resData.message));
  552. });
  553. }
  554. const getGamesRelation = ({ mk=-1, ids, listEvents } = {}) => {
  555. let idsSet = null;
  556. if (ids?.length) {
  557. idsSet = new Set(ids);
  558. }
  559. const relations = Object.values(GAMES.Relations).filter(item => {
  560. if (idsSet && !idsSet.has(item.id)) {
  561. return false;
  562. }
  563. return mk == -1 || item.mk == mk;
  564. }).sort((a, b) => a.timestamp - b.timestamp);
  565. if (listEvents) {
  566. return relations;
  567. }
  568. const gamesRelation = relations.map(item => {
  569. const { rel, ...relationInfo } = item;
  570. const tempRel = { ...rel };
  571. Object.keys(tempRel).forEach(platform => {
  572. const { events, evtime, sptime, special, ...gameInfo } = tempRel[platform];
  573. tempRel[platform] = gameInfo;
  574. });
  575. return { ...relationInfo, rel: tempRel };
  576. });
  577. return gamesRelation;
  578. }
  579. /**
  580. * 定时更新关联比赛列表
  581. */
  582. const updateGamesRelation = () => {
  583. fetchGamesRelation()
  584. .then(gamesRelation => {
  585. const baseList = {};
  586. gamesRelation.map(item => {
  587. const baseGame = item.rel?.['ps'] ?? {};
  588. return { ...baseGame, mk: item.mk };
  589. }).forEach(item => {
  590. const marketType = getMarketType(item.mk);
  591. if (!baseList[marketType]) {
  592. baseList[marketType] = [];
  593. }
  594. baseList[marketType].push(item);
  595. });
  596. Object.keys(baseList).forEach(marketType => {
  597. syncBaseList({ marketType, games: baseList[marketType] });
  598. });
  599. const updateCount = {
  600. add: 0,
  601. update: 0,
  602. delete: 0
  603. };
  604. gamesRelation.forEach(item => {
  605. const { id, mk } = item;
  606. const oldItem = GAMES.Relations[id];
  607. if (!oldItem) {
  608. GAMES.Relations[id] = item;
  609. updateCount.add ++;
  610. }
  611. else if (oldItem.mk != mk) {
  612. GAMES.Relations[id] = item;
  613. updateCount.update ++;
  614. }
  615. });
  616. const relations = new Set(gamesRelation.map(item => +item.id));
  617. Object.keys(GAMES.Relations).forEach(id => {
  618. if (!relations.has(+id)) {
  619. delete GAMES.Relations[id];
  620. updateCount.delete ++;
  621. }
  622. });
  623. if (updateCount.add || updateCount.update || updateCount.delete) {
  624. Logs.out('updateGamesRelation', updateCount);
  625. }
  626. else {
  627. Logs.outDev('updateGamesRelation', updateCount);
  628. }
  629. })
  630. .catch(err => {
  631. Logs.out('updateGamesRelation', err.message);
  632. })
  633. .finally(() => {
  634. setTimeout(updateGamesRelation, 60000);
  635. });
  636. }
  637. updateGamesRelation();
  638. const gamesRelationCleanup = () => {
  639. const relations = Object.values(GAMES.Relations);
  640. const expireTime = Date.now() - 1000*60;
  641. relations.forEach(item => {
  642. const { rel } = item;
  643. Object.keys(rel).forEach(platform => {
  644. const { evtime, sptime } = rel[platform];
  645. if (evtime && evtime < expireTime) {
  646. delete rel[platform].events;
  647. delete rel[platform].evtime;
  648. }
  649. if (sptime && sptime < expireTime) {
  650. delete rel[platform].special;
  651. delete rel[platform].sptime;
  652. }
  653. });
  654. });
  655. }
  656. /**
  657. * 同步比赛结果
  658. */
  659. const syncGamesResult = async (result) => {
  660. if (IS_DEV) {
  661. return Logs.out('updateGamesResult', result);
  662. }
  663. // axios.post(`${BASE_API_URL}/p/syncMatchResult`, result, { proxy: false })
  664. // .then(res => {
  665. // // Logs.out('syncMatchResult', res.data);
  666. // })
  667. // .catch(err => {
  668. // Logs.out('syncMatchResult', err.message);
  669. // });
  670. }
  671. /**
  672. * 更新比赛结果
  673. */
  674. const updateGamesResult = (result) => {
  675. syncGamesResult(result);
  676. return Promise.resolve();
  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. updateOriginalData, getOriginalData,
  1177. getSolutions, getGamesSolutions, getSolution, getSolutionsByIds,
  1178. getTotalProfitWithSid,
  1179. getTotalProfitWithBetInfo,
  1180. notifyException,
  1181. }