GamesPs.js 34 KB

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