GamesPs.js 32 KB

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