GamesPs.js 34 KB

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